python connect4.py

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python connect4.py相关的知识,希望对你有一定的参考价值。

# play the game of connect 4


def make_board():
  """
  create the blank connect game board
  It's a list of list 6 X 7
  @returns: the board created(list)
  """
  board = []
  for row in range(6):
    board.append(["*"] * 7)
  return board

def display_board(board):
  """
  display the given board.
  @board: a list of list of characters.
  @returns: None
  """
  for row in range(6):
    # display the column headers
    print(abs(row - 5), end = "")
    for col in range(7):
      print((" %s" % board[row][col]), end="")
    print("")
  print(" ", end="")

  # print the last line
  for col in range(7):
    print((" %d" % col), end="")
  print(" \n")

def check_row_win(board, player):
  """
  check if there is a win in a row
  @board: a list of lists of characters.
  @player: X or O
  @returns: true if there is a row win and false otherwise
  """
  height = len(board[0])
  width = len(board)
  for y in range(height):
    for x in range(width - 3):
      if board[x][y] == player and board[x+1][y] == player and board[x+2][y] == player and board[x+3][y] == player:
        display_board(board)
        print("%s won the game." % player)
        return True
  return False

def check_col_win(board, player):
  """
  check if there is a win in a col
  @board: a list of lists of characters.
  @player: X or O
  @returns: true if there is a col win and false otherwise
  """
  height = len(board[0])
  width = len(board)
  for x in range(width):
    for y in range(height - 3):
      if board[x][y] == player and board[x][y+1] == player and board[x][y+2] == player and board[x][y+3] == player:
        display_board(board)
        print("%s won the game." % player)
        return True
  return False

def check_diag_win(board, player):
  """
  check if there is a win in a diagonal
  @board: a list of lists of characters.
  @player: X or O
  @returns: true if there is a diagonal win and false otherwise
  """
  height = len(board[0])
  width = len(board)
  # check / diagonal
  for x in range(width - 3):
    for y in range(3, height):
      if board[x][y] == player and board[x+1][y-1] == player and board[x+2][y-2] == player and board[x+3][y-3] == player:
        display_board(board)
        print("%s won the game." % player)
        return True
  # check \ diagonal
  for x in range(width - 3):
    for y in range(height - 3):
      if board[x][y] == player and board[x+1][y+1] == player and board[x+2][y+2] == player and board[x+3][y+3] == player:
        display_board(board)
        print("%s won the game." % player)
        return True
  return False

def check_who_win(board, player):
    return (check_col_win(board, player) or check_row_win(board, player) or check_diag_win(board, player))

def check_tie(board):
  """
  check if there is a tie
  @board: a list of lists of characters.
  @returns: true if there is a tie and false otherwise
  """
  for row in range(6):
    for col in range(7):
      if board[row][col] == '*':
        return False

  return True

def check_win(board):
  """
  check if there is a win
  @board: a list of lists of characters.
  @returns: true if there is a tie and false otherwise
  """
  # check who win
  if check_who_win(board, 'O') or check_who_win(board, 'X'):
    return True
  elif check_tie(board): # check tie
    display_board(board)
    print("The game ended in a tie.")
    return True
  else:
    return False

def is_valid_int(integer):
  """
  checks to see if number represents a valid integer
  @number: a string that might represent an integer
  @returns: true if the string represents an integer
  """
  integer = integer.strip()
  if len(integer) == 0:
    return False
  else:
    return (integer.isdigit() or #only digits
      #or a negative sign followed by digits
      (integer.startswith('-') and integer[1:].isdigit()))

def is_valid_move(str_move, board):
  """
  check if the move is valid on the given board
  @str_move: the potential move. should be column
  @board: a list of lists of characters.
  @returns: True if the move is valid and False otherswise
  """
  if not is_valid_int(str_move):#row isn't a number
    return False

  col = int(str_move)

  if col not in range(7): #move needs to be on the board
    return False

  if board[0][col] != '*': # column is full
    return False

  return True #move wasn't illegal so it must be legal

def get_move(player, board):
  """
  get a valid move from the player
  @player: a string representing the current player
  @board: the board
  @returns: a valid move, which is Int
  """
  move = '' #make the move start as wrong so that we always go into the while loop
  while not is_valid_move(move, board): #while the input is invalid
    move = input('%s please enter a move: ' % player) #keep asking for input

  #turn to integers
  col = int(move)
  return col

def make_move(piece, move, board):
    """
    make the change to the board
    @piece: X or O
    @move: a move which is checked
    """
    can_put_positon_list = []
    index = 0
    # find the lowest row can put a symbol
    for row in board:
      if board[index][move] == '*':
        can_put_positon_list.append([index, move])
      else:
        break
      index += 1
    # get the last of the list, is the lowest
    can_put_position = can_put_positon_list[len(can_put_positon_list) - 1]
    row = can_put_position[0]
    col = can_put_position[1]
    board[row][col] = piece

def play_game():
    """
    Play the connect 4 game
    """
    board = make_board()

    turn = 0 #if turn is 0 it is X's turn and if it is 1 it is O's turn
    XO = 'XO'

    while check_win(board) == False:
      display_board(board)
      move = get_move(XO[turn], board)
      make_move(XO[turn], move, board)
      turn = (turn + 1) % 2 #change the turn
      print("")

if __name__ == '__main__':
    play_game()

以上是关于python connect4.py的主要内容,如果未能解决你的问题,请参考以下文章

001--python全栈--基础知识--python安装

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python

Python 介绍

Python学习之认识python