def askinput_server(game_state: connectfour.GameState, connection: ConnectfourConnection): while True: if game_state.turn == connectfour.RED: move = input("Red player DROP or POP: ") player = int(input("Red player column 1-7: ")) player_move = move + ' ' + str(player) _write_line(connection, player_move.upper()) if move == 'DROP': return connectfour.drop(game_state, player - 1) else: return connectfour.pop(game_state, player - 1) else: if _read_line(connection) == 'OKAY': server_move = _read_line(connection) togetridoftheline = _read_line(connection) move = server_move.split()[0] player = int(server_move.split()[1]) if move == 'DROP': return connectfour.drop(game_state, player - 1) else: return connectfour.pop(game_state, player - 1) else: _expect_line(connection, 'READY') return game_state
def movement() -> str: ''' allows the player to pop or drop a disc into a given column and determines the winner''' gs = connectfour.new_game() connectfour_board.print_board(gs.board) print('If you want to drop type D, press enter and a column number.') print('If you want to pop type P, press enter and a column number.') while True: try: command = input() col = int(input()) if command[0] == 'D': gs = connectfour.drop(gs, col - 1) connectfour_board.print_board(gs.board) else: gs = connectfour.pop(gs, col - 1) connectfour_board.print_board(gs.board) if connectfour.winner(gs) != connectfour.NONE: x = connectfour.winner(gs) if x == 1: print('RED WINS!') elif x == 2: print('YELLOW WINS!') return command + ' ' + col except ValueError: print('Try again') pass
def update_board(updatedBoard: connectfour.GameState, user_input:str) -> connectfour.GameState: '''updates board so game state is always current ''' valid_column_numbers = '1234567' if user_input[0:4].upper() == "DROP": try: if user_input[-1] not in valid_column_numbers: connectfour.InvalidMoveError(Exception) print('Error, try again') new_input = read_game_command() return update_board(updatedBoard, new_input) new_board = connectfour.drop(updatedBoard, int(user_input[-1])-1) return(new_board) except connectfour.InvalidMoveError: print('Error, try again') new_input = read_game_command() return update_board(updatedBoard, new_input) elif user_input[0:3].upper() == "POP": try: if user_input[-1] not in valid_column_numbers: connectfour.InvalidMoveError(Exception) print('Error, try again') new_input = read_game_command() return update_board(updatedBoard, new_input) new_board = connectfour.pop(updatedBoard, int(user_input[-1])-1) return(new_board) except connectfour.InvalidMoveError: print('Error, try again') new_input = read_game_command() return update_board(updatedBoard, new_input) else: print('Error, try again') new_input = read_game_command() return update_board(updatedBoard,new_input)
def run_game(position: 'GameState') -> 'GameState' or None: connectfour.winner(position) if connectfour.winner(position) == connectfour.NONE: theanswer = local_tools.obtainanswer() if theanswer == 'D': column_num = local_tools.overlimit(position) nextstep = connectfour.drop(position, column_num) local_tools.board(nextstep) return run_game(nextstep) elif theanswer == 'P': column_num = int(input('Enter a column number from 1-7: ')) - 1 try: nextstep = connectfour.pop(position, column_num) except: run_game(position) else: local_tools.board(nextstep) return run_game(nextstep) else: thewinner = connectfour.winner(position) if thewinner == 1: print('Red wins!') elif thewinner == 2: print('Yellow wins!')
def movechecker(gamestate, column, move) -> 'current_gamestate': ''' This function will take in the game state and column input and ask the user if they want to drop or pop. Then it will perform the action, and return the new current game state. If it is an invalid move, it will ask the user to re-input the moves. If the game is over, it will print game over.''' while True: try: if move == 'DROP': current_gamestate = connectfour.drop(gamestate, column) print("MOVE: " + move + ' {}'.format(column + 1)) return current_gamestate elif move == 'POP': current_gamestate = connectfour.pop(gamestate, column) print("MOVE: " + move + ' {}'.format(column + 1)) return current_gamestate except connectfour.InvalidMoveError: print("INVALID MOVE ERROR") column = connectfour_tools.columninput() move = connectfour_tools.moveinput() except connectfour.GameOverError: print("Game is over.") break
def user_move(game: "GameState", move: str) -> "GameState": """updates local game board""" if move[0] == 'd': game = connectfour.drop(game, int(move[2:]) - 1) else: game = connectfour.pop(game, int(move[2:]) - 1) return game
def play_game_for_yellow(position: 'GameState', dorp: str, col: str) -> 'GameState' or None: connectfour.winner(position) print(dorp + col) if connectfour.winner(position) == connectfour.NONE: if dorp == 'D': nextmove = connectfour.drop(position, col) board(nextmove) return play_game_for_red(nextmove, connection, connectionout) elif dorp == 'P': column_num = int(input('Enter a column number from 1-7: ')) - 1 try: nextmove = connectfour.pop(position, column_num) except: play_game(position) else: board(nextmove) return play_game_for_red(nextmove, connection, connectionout) else: thewinner = connectfour.winner(position) if thewinner == 1: print('Red wins!') elif thewinner == 2: print('Yellow wins!')
def gaming_board(mystring, david): ''' This has three function. The first is to update david object by applying column with functhings (e.g. drop, pop) The second is to check it has error by using try/exception. When DROP on the full column or POP the empty column, it raises error and simply printing 'DROP/POP ERROR' and require it once again ''' myinput_command = mystring[:-2].lower() myinput_column = int(mystring[-1]) - 1 if myinput_command == 'drop': try: david = connectfour.drop(david, myinput_column) except: print('DROP ERROR') elif myinput_command == 'pop': try: david = connectfour.pop(david, myinput_column) except: print('POP ERROR') board_copy(david.board) return david
def yellow_turn( game_state: connectfour.GameState, connection: connectfour_socket.GameConnect) -> connectfour.GameState: '''Takes input from the server and handles turn sequence.''' turn_message = connectfour_socket.receive_message(connection) message_split = turn_message.split() action = message_split[0] col_num = int(message_split[-1]) print("Yellow's move: {} {}".format(action, col_num)) print() if action == 'DROP': game = connectfour.drop(game_state, col_num - 1) if not connectfour.InvalidMoveError: connection.socket.close() print('Game connection closed due to improper server action.') else: pass elif action == 'POP': game = connectfour.pop(game_state, col_num - 1) message = '{} {}'.format(action, col_num) connectfour_socket._write_line(connection, message) if not connectfour.InvalidMoveError: connection.socket.close() print('Game connection closed due to improper server action.') else: pass else: connection.socket.close() print('Game connection closed due to improper server action.') return game
def take_action_on_command(player_input: str, game_state: connectfour.GameState) -> connectfour.GameState: if player_input.startswith("DROP"): column_num = int(player_input[5:]) - 1 return connectfour.drop(game_state, column_num) elif player_input.startswith("POP"): column_num = int(player_input[4:]) - 1 return connectfour.pop(game_state, column_num)
def clientmovechecker(gamestate) -> 'current_gamestate, movecol': ''' This function will take in the current gamestate, then it will ask the user for a column and move input, if the move is invalid, it will ask the user to to reinput the column and move. If it is valid, perform the move and return a new gamestate and the move and column combined as a str.''' column = connectfour_tools.columninput() move = connectfour_tools.moveinput() while True: try: if move == 'DROP': current_gamestate = connectfour.drop(gamestate, column) print("MOVE: " + move + ' {}'.format(column + 1)) movecol = str(move + ' {}'.format(column + 1)) return current_gamestate, movecol elif move == 'POP': current_gamestate = connectfour.pop(gamestate, column) print("MOVE: " + move + ' {}'.format(column + 1)) movecol = str(move + ' {}'.format(column + 1)) return current_gamestate, movecol except connectfour.InvalidMoveError: print("INVALID MOVE.") column = connectfour_tools.columninput() move = connectfour_tools.moveinput() except connectfour.GameOverError: print("Game is over.") break
def run_game(position: 'GameState') -> 'GameState' or None: connectfour.winner(position) if connectfour.winner(position) == connectfour.NONE: theanswer = obtainanswer() if theanswer == 'D': column_num = overlimit(position) nextstep = connectfour.drop(position, column_num) board(nextstep) return run_game(nextstep) elif theanswer == 'P': column_num = int(input('Enter a column number from 1-7: ')) - 1 try: nextstep = connectfour.pop(position, column_num) except: run_game(position) else: board(nextstep) return run_game(nextstep) ## if nextstep == connectfour.InvalidMoveError(): ## run_game(position) ## else: ## board(nextstep) ## return run_game(nextstep) else: thewinner = connectfour.winner(position) if thewinner == 1: print('Red wins!') elif thewinner == 2: print('Yellow wins!')
def turn(currentBoard: connectfour.GameState) -> connectfour.GameState: while True: printBoard(currentBoard) if (currentBoard.turn == connectfour.RED): print("Red Turn") if (currentBoard.turn == connectfour.YELLOW): print("Yellow Turn") nextIn = input( "\n\"POP *column number*\" to pop out piece | \"DROP *column number*\" to drop piece\n" ) if nextIn.upper().startswith("POP "): try: return connectfour.pop(currentBoard, int(nextIn[4::]) - 1) except: print("Please Enter Proper Input") ## return turn(currentBoard) continue elif nextIn.upper().startswith("DROP "): try: return connectfour.drop(currentBoard, int(nextIn[5::]) - 1) except: print("Please Enter Proper Input") ## return turn(currentBoard) continue print("Please Enter Proper Input:")
def check_move(move: str, game: connectfour.GameState) -> bool: '''checks if the moves is good''' move = move.upper() try: if move[0:4] == 'DROP': connectfour.drop(game, (int(move[5:]) - 1)) elif move[0:3] == 'POP': connectfour.pop(game, (int(move[4:]) - 1)) else: return False except (connectfour.InvalidMoveError, ValueError, connectfour.GameOverError): return False else: return True
def get_valid_move(gamestate: connectfour.GameState) -> str: ''' asks the player to input a move and test if it is a valid move, if yes, return the move type and col as one str ''' while True: try: move_type = pop_or_drop() move_col = column_command() if move_type == 'DROP': gamestate = connectfour.drop(gamestate, move_col) else: gamestate = connectfour.pop(gamestate, move_col) if gamestate != None: return '{} {}'.format(move_type, move_col) except KeyboardInterrupt: quit() except: print('Invalid move. Please try again!')
def server_step(response:str,GameBoard) ->connectfour.GameState or None: ''' Recording the server command and return new game board. The AI may send wrong command, if so the pragram will closing the connection and quit ''' try: command = response.split() if command[0].upper() == 'DROP': col_num = int(command[1]) if 1<= col_num <= connectfour.BOARD_COLUMNS: NewBoard = connectfour.drop(GameBoard,col_num -1) return NewBoard else: pass elif command[0].upper() == 'POP': col_num = int(command[1]) if 1<= col_num <= connectfour.BOARD_COLUMNS: NewBoard = connectfour.pop(GameBoard,col_num-1) return NewBoard else: pass else: pass except ValueError: pass
def checkMove(gamestate: connectfour.GameState, choice: str, col_num: str): """Takes in the user"s choice and see if the move is valid by calling drop or pop from connectfour If no expection is raised when checking the move then it will return True otherwise False""" if choice == "DROP": try: connectfour.drop(gamestate, col_num - 1) return True except connectfour.InvalidMoveError: return False elif choice == "POP": try: connectfour.pop(gamestate, col_num - 1) return True except connectfour.InvalidMoveError: return False return False
def drop_to(state, play: action) -> tuple: '''Returns GameState after new move has been executed''' if play.drop_pop.lower() == 'drop': new_state = connectfour.drop(state, int(play.num) - 1) return new_state elif play.drop_pop.lower() == 'pop': new_state = connectfour.pop(state, int(play.num) - 1) return new_state
def change_board(gamestate:object,user_input,column_number): '''changes the board and updates the gamestate according to the users action''' if user_input == 'DROP': gamestate = connectfour.drop(gamestate, (int(column_number)-1)) if user_input == 'POP': gamestate = connectfour.pop(gamestate, (int(column_number)-1)) print_board(gamestate) return( gamestate )
def checkMove(gamestate: connectfour.GameState, choice: str, col_num: str): """Takes in the user"s choice and see if the move is valid by calling drop or pop from connectfour If no expection is raised when checking the move then it will return True otherwise False""" if choice == "DROP": try: connectfour.drop(gamestate, col_num-1) return True except connectfour.InvalidMoveError: return False elif choice == "POP": try: connectfour.pop(gamestate, col_num-1) return True except connectfour.InvalidMoveError: return False return False
def user_pop(response, GameState): ''' Given the response this 'pops' a piece on the connect four board ''' column = int(response[1]) column = column - 1 return(connectfour.pop(GameState, column)) print()
def action(move: str, column_num: int, game_state: 'GameState') -> 'GameState': '''implements pop or drop''' if move == 'DROP': return connectfour.drop(game_state, column_num - 1) elif move == 'POP': return connectfour.pop(game_state, column_num - 1)
def user_pop(response, GameState): ''' Given the response this 'pops' a piece on the connect four board ''' column = int(response[1]) column = column - 1 return (connectfour.pop(GameState, column)) print()
def AI_move(gstate: connectfour.GameState, move: str) -> connectfour.GameState: '''Enacts a move from the AI under the assumption that the move is valid.''' commands = move.split() column = int(commands[1]) if commands[0] == 'DROP': return connectfour.drop(gstate, column - 1) else: return connectfour.pop(gstate, column - 1)
def _move_for_server(s_move: str, gs: connectfour.GameState) -> connectfour.GameState: col = int(s_move[-1]) - 1 if s_move.startswith('DROP'): gs = connectfour.drop(gs, col) return gs else: gs = connectfour.pop(gs, col) return gs
def makeMove(gamestate: connectfour.GameState, choice: str, col_num: str): """If a valid move was made then the gamestate with the completed move will be returned""" if (checkMove(gamestate, choice, col_num)): if choice == "DROP": return connectfour.drop(gamestate, col_num - 1) elif choice == "POP": return connectfour.pop(gamestate, col_num - 1) else: return gamestate
def execute_turn(gamestate: 'Gamestate', turn_choice: str, column_choice: int) -> 'Gamestate': if turn_choice == 'DROP': gamestate = connectfour.drop(gamestate, column_choice) elif turn_choice == 'POP': try: gamestate = connectfour.pop(gamestate, column_choice) except InvalidMoveError: print('Invalid Move: can only pop YOUR pieces from the bottom row') return gamestate
def make_move(game_state: 'GameState', choice: str) -> 'GameState': "Submits a valid move." choice_option = choice.split()[0] column_number = int(choice.split()[1]) - 1 if choice_option.upper() == 'DROP': return connectfour.drop(game_state, column_number) elif choice_option.upper() == 'POP': return connectfour.pop(game_state, column_number) else: raise connectfour.InvalidMoveError
def makeMove(gamestate: connectfour.GameState, choice: str, col_num: str): """If a valid move was made then the gamestate with the completed move will be returned""" if (checkMove(gamestate, choice, col_num)): if choice == "DROP": return connectfour.drop(gamestate, col_num-1) elif choice == "POP": return connectfour.pop(gamestate, col_num-1) else: return gamestate
def updateState(state: 'gameBoard', action: PlayerCommand): ''' Updates the current Game State. ''' if action.command.upper() == 'DROP': state = connectfour.drop(state, int(action.column) - 1) elif action.command.upper() == 'POP': state = connectfour.pop(state, int(action.column) - 1) return state
def popBoard(currentBoard: cf.GameState, col: int) -> (cf.GameState, str, int): try: return cf.pop(currentBoard, col), "POP ", col except ValueError: print("Please Enter Valid Column") return currentBoard, "INVALID_COLUMN", 0 pass except cf.InvalidMoveError: print("Please Enter Valid Pop") return currentBoard, "INVALID_MOVE", 0 pass
def handle_move(_game :'connectfour.ConnectFourGameState', column:int, move:str)-> None: ''' handle the command regarding the moves taken bh players''' try: if move == 'drop': return connectfour.drop(_game,column-1) elif move == 'pop': return connectfour.pop(_game,column-1) else: print("the given input is not a valid input.") except connectfour.InvalidMoveError: print("invalid move") return _game
def run_pop(game_state: connectfour.GameState, column: int) -> connectfour.GameState: '''Pops a piece from the bottom of a selected column if it is valid''' try: new_GameState = connectfour.pop(game_state, column-1) display_game_board(new_GameState.board) return new_GameState except connectfour.InvalidMoveError: print('COLUMN DOES NOT HAVE YOUR PIECE AT THE BOTTOM ROW') return game_state
def drop_or_pop_action(game_state, user_input) -> 'game_state': player_input_spliter = user_input.split() player_option = player_input_spliter[0].upper() player_column = int(player_input_spliter[1]) - 1 if player_option == 'DROP': game_state = connectfour.drop(game_state, player_column) return game_state elif player_option == 'POP': game_state = connectfour.pop(game_state, player_column) return game_state
def handle_move(_game :'connectfour.ConnectFourGameState', column:int, move:str)-> None: ''' handle the command regarding the moves taken bh players''' try: if move == 'drop': return connectfour.drop(_game,column-1) elif move == 'pop': return connectfour.pop(_game,column-1) except connectfour.InvalidMoveError: print("oops ! invalid move") return _game except connectfour.GameOverError: print("The game is already over!") return _game
def program(game): """ program that handles the connect four game """ while connectfour.winner(game) == 0: # while there is no winner if game.turn == 1: # if it is red player's turn print("Player RED make your move") # prints this message print() elif game.turn == 2: # if it is yellow players turn print("Player YELLOW make your move") # prints this message print() sharedfunctions.print_board(game.board) # print a new game current_move = sharedfunctions.get_move() # gets the players move and stores it in a variable while True: try: if current_move[0].upper() == "DROP": # if players says they want to drop game = connectfour.drop( game, int(current_move[-1]) - 1 ) # drops the players move in appropriate column and changes the game state elif current_move[0].upper() == "POP": # if player says they want to pop game = connectfour.pop( game, int(current_move[-1]) - 1 ) # pops players move as long as players piece is in specified column except: print("Invalid Move") # if playes move is invalid prints this message print() current_move = sharedfunctions.get_move() # recursively ask for players move until input is acceptable else: break # leave the function print("\n\n") sharedfunctions.print_board(game.board) # prints new game state print("Game Over") # when game is over prints this message if game.turn == 1: # if it is red playes turn print("Player YELLOW is the Winner") # print this message elif game.turn == 2: # if is is yellow players turn print("Player RED is the Winner") # print this message
def each_turn() -> None: ''' Simulates turn for each player, updates gamestate, displays the board for the user to see and shows whose turn it is. Breaks and Displays the winner when the game is won. ''' game = connectfour.new_game() while True: common.display_turn(game) player_move = common.interpret_user_input() if player_move.Action == 'D': try: game = connectfour.drop(game, player_move.Col_Num) print() common.board_display(game) except: print('Invalid Move') elif player_move.Action == 'P': try: game = connectfour.pop(game, player_move.Col_Num) print() common.board_display(game) except: print('Invalid Move') else: print('Try again') if winner(game): break
def pop_piece(game_state: 'GameState', col_num: int): new_state = connectfour.pop(game_state, col_num) return new_state
def main_program(game): ''' program that handles the connect four game ''' try: x = random() #(prompts user for a username, host and port. this is the first function in this module c = connecting.connection(x.host, x.port) #connects to given host and port connecting.send_move(c, 'I32CFSP_HELLO ' + x.username) #send a message and includes the username provided by user connecting.read_line(c) #reads a line from the server connecting.send_move(c, 'AI_GAME') #sends this message to the server connecting.read_line(c) #reads a line from the server while connectfour.winner(game) == 0: #while there is no winner if game.turn == 1: #if it is player print('Player RED make your move') #prints this message print() sharedfunctions.print_board(game.board) #print a new game while True: try: current_move = sharedfunctions.get_move() #gets the players move and stores it in a variable print('\n') if current_move[0].upper().startswith('DROP'): #takes players input at first index, makes it uppercase and checks if it equals a string current_move = int(current_move[-1]) #converts players move at last index to an integer current_move = current_move - 1 #subtracts 1 from players move to account for indexing game = connectfour.drop(game, current_move) #calls drop function from connectfour module that handles dropping a piece onto connect four board sharedfunctions.print_board(game.board) #prints updated game board connecting.send_move(c, 'DROP ' + str(current_move+1)) #sends string and adds one to players move to account for subtractoin earlier then converts players move back to a string to send to the server break #leaves the function elif current_move[0].upper().startswith('POP'): #takes players input at first index, makes it uppercase and checks if it equals a string current_move = int(current_move[-1]) #converts players move at last index to an integer current_move = current_move - 1 #subtracts 1 from players move to account for indexing game = connectfour.pop(game, current_move) #calls pop function from connectfour module that handles popping a piece onto connect four board sharedfunctions.print_board(game.board) #prints updated game board connecting.send_move(c, 'POP ' + str(current_move+1)) #sends string and adds one to players move to account for subtractoin earlier then converts players move back to a string to send to the server break #leaves the function except: print('Invalid Move') #prints this message if try statement fails print() elif game.turn == 2: #if it is the servers move connecting.read_line(c) #read input from server servers_move = connecting.read_line(c) #reads another line from server. this is servers move if servers_move.startswith('POP'): #if servers move starts with POP servers_move = int(servers_move.split()[-1]) #split servers input and grab last index and convert to an integer servers_move = servers_move - 1 #subtracts one from servers move to account for 0 indexing connecting.read_line(c) #read line of input from server game = connectfour.pop(game, servers_move) #calls pop function from connectfour module that handles popping a piece onto connect four board sharedfunctions.print_board(game.board) #prints updated game board else: servers_move = int(servers_move.split()[-1]) #split servers input and grab last index and convert to an integer servers_move = servers_move - 1 #subtracts one from servers move to account for 0 indexing connecting.read_line(c) #read line of input from server game = connectfour.drop(game, servers_move) #calls drop function from connectfour module that handles dropping a piece onto connect four board sharedfunctions.print_board(game.board) #prints updated game board print('\n\n') sharedfunctions.print_board(game.board) #prints new game state print('Game Over') #when the game is over prints this message if game.turn == 1: #if it is red players turn (player red has lost) print('Sorry, you have lost') #prints this message elif game.turn == 2: #if it yellow players move (player yellow has lost) print('Congratulations! You have won') #prints this message except: print('The connection was unsuccessful') finally: try: connecting.close(c) #closes the connection except: print('Goodbye')
def pop_piece(col_num: int): new_state = connectfour.pop(new_board, col_num) return pop_piece
def pop_piece(game_state: 'GameState', col_num: int): ''' Pops a piece in the game board and returns it''' new_state = connectfour.pop(game_state, col_num) return new_state
def execute_move(game_state,player_move) -> 'game_state': ''' Performs a local move based on a player action ''' if player_move.action == ACTION_POP: return connectfour.pop(game_state, player_move.col) elif player_move.action == ACTION_DROP: return connectfour.drop(game_state, player_move.col)