def userinterface() -> None: ''' This method runs the connection between this program and the server program to play a game of connect four, using functions from this and other classes imported from above. ''' try: _welcome_screen()#Welcomes the user. connection = '' #Used here to avoid error when user doesn't enter a host and port connection = _connect_ui() #connects the program to the server username = _request_username() #Gets a username for the user connectfour_protocol.interact(connection, username, 'I32CFSP_HELLO ', 'WELCOME ' + username) #Sends the initial client message specifying protocol connectfour_protocol.interact(connection, 'AI_GAME', '', 'READY') #Sends the client protocol and gets the server protocol to start the AI game_state = connectfour_shared.initiate_game() #Starts new game and prints the board while True: try: move = connectfour_shared.request_move() #Gets users move game_state = connectfour_shared.update_board(game_state, move)#updates the board connectfour_shared.print_board(game_state)#prints the new game_state response = connectfour_protocol.interact(connection, move, '', 'READY')#Response from the server if response == None:#Gets out of loop if server doesn't respond break game_state = connectfour_shared.update_board(game_state, response)#Updates the board with server's move connectfour_shared.print_board(game_state)#Prints the board. except: print('Invalid move, please try again')#Exception when user enters invalid move except ConnectionRefusedError:#If socket fais to connect print('Connection failed') except OSError:#If invalid IP adress print('Not a valid IP Address') except:#In other cases of errors print("Sorry we weren't able to connect to that server") finally:#Closes the connectino if one was made. if(connection!=''): connectfour_protocol.close(connection) print('Game over')
def make_move(game_state : connectfour.ConnectFourGameState) -> connectfour.ConnectFourGameState: ''' Takes in the game state and asks the user for a move. Then it updates the board and if that fails the appropriate exception is displayed to the user followed by a reprompt for a valid move. ''' while(True): try: move = connectfour_shared.request_move() #gets a move return connectfour_shared.update_board(game_state, move) #updates board break except ValueError:#makes sure column number is valid print('Column number must be between 1 and {}'.format(connectfour.BOARD_COLUMNS)) except connectfour.ConnectFourGameOverError: #checks if game is over print('The game has already ended.') raise SystemExit(0) except connectfour.InvalidConnectFourMoveError: #checks if move is valid if move[0].upper() == 'DROP': print('The column is too full to drop a piece in.') else: print('The row selected is either empty, or the bottom piece is not your own.')