def client_to_server(address,port,Start_Game): server_socket = socket.socket() try: print('This is the address and port: ', address, ':', port) server_socket.connect((address,int(port))) print('Connecting...') client_protocol(server_socket)# check this function player_first_move(Start_Game,server_socket) winning_player = connectfour.winning_player(Start_Game) while winning_player == connectfour.winning_player(Start_Game) : file_in = server_socket.makefile('r') move_info = file_in.readline() print('this move info ' + move_info) file_in.close() if len(move_info)== 0: break else: gamestate = Start_Game._replace(turn= connectfour._opposite_turn(Start_Game.turn)) client_game(gamestate,move_info,server_socket) except: print('Unable to connect.') as_client(Start_Game) finally: server_socket.close() print('Game Over')
def get_connection(address,port,Start_Game): listen_socket = socket.socket() listen_address = (address, int(port)) try: listen_socket.bind(listen_address) pass except: print('Error. Invalid address.') as_server(Start_Game) listen_socket.listen(0) print('Connection pending...') connection_soc, address = listen_socket.accept() print('{} is connected!'.format(address)) listen_socket.close() receive_protocols(connection_soc) print('waiting for player to move.') winning_player = connectfour.winning_player(Start_Game) while winning_player == connectfour.winning_player(Start_Game) : file_in = connection_soc.makefile('r') move_info = file_in.readline() print('this is move info:' + move_info) file_in.close() if len(move_info)== 0: break else: server_game(Start_Game,move_info,connection_soc) print('game over') connection_soc.close() return
def client_to_server(address, port, Start_Game): server_socket = socket.socket() try: print('This is the address and port: ', address, ':', port) server_socket.connect((address, int(port))) print('Connecting...') client_protocol(server_socket) # check this function player_first_move(Start_Game, server_socket) winning_player = connectfour.winning_player(Start_Game) while winning_player == connectfour.winning_player(Start_Game): file_in = server_socket.makefile('r') move_info = file_in.readline() print('this move info ' + move_info) file_in.close() if len(move_info) == 0: break else: gamestate = Start_Game._replace( turn=connectfour._opposite_turn(Start_Game.turn)) client_game(gamestate, move_info, server_socket) except: print('Unable to connect.') as_client(Start_Game) finally: server_socket.close() print('Game Over')
def user_interface()->None: print("Welcome to Connect Four!") last_state = connectfour.new_game_state() linkui._rotate_board(last_state) while True: option = linkui.ask_for_option() if option == 'D': try: col = linkui.ask_for_col_drop() except: print('Invalid value.') else: last_state = linkui.option_d(last_state,col) elif option == 'P': try: col = linkui.ask_for_col_pop() except: print('Invalid value.') else: last_state = linkui.option_p(last_state,col) else: print('Invalid Command.') if connectfour.winning_player(last_state) != ' ': print("Player " + connectfour.winning_player(last_state) + " wins!") break rematch()
def get_connection(address, port, Start_Game): listen_socket = socket.socket() listen_address = (address, int(port)) try: listen_socket.bind(listen_address) pass except: print('Error. Invalid address.') as_server(Start_Game) listen_socket.listen(0) print('Connection pending...') connection_soc, address = listen_socket.accept() print('{} is connected!'.format(address)) listen_socket.close() receive_protocols(connection_soc) print('waiting for player to move.') winning_player = connectfour.winning_player(Start_Game) while winning_player == connectfour.winning_player(Start_Game): file_in = connection_soc.makefile('r') move_info = file_in.readline() print('this is move info:' + move_info) file_in.close() if len(move_info) == 0: break else: server_game(Start_Game, move_info, connection_soc) print('game over') connection_soc.close() return
def play_game(myConnectFourConnection): ''' The client and server take turns playing the game when there is no winner ''' print('\nHere is the gameboard:\n') gameState = ConnectFour_ui.game_state() ConnectFour_ui.print_gameboard(gameState) server_move = [] Cond = True while Cond: if connectfour.winning_player(gameState) != connectfour.NONE: print('\nPlayer', connectfour.winning_player(gameState), 'wins!') return elif gameState.turn == 'R': user = ConnectFour_ui.user_move(gameState) if connectfour.winning_player(user[0]) == connectfour.RED: print('Player', connectfour.winning_player(user[0]), 'wins!') Cond = False else: server_move = ConnectFour_SocketHandling.servers_next_move(myConnectFourConnection, user[1]) gameState = user[0] else: server = server_turn(server_move, gameState) gameState = server
def game_handler(connection:server.GameConnection,s:'Game State'): '''Takes the game state and game connection as arguments and calls the game_play function and the board_display function for each players move and returns the winning player ''' print('WELCOME TO CONNECT 4 GAME') username=read_username() server.send(connection,'I32CFSP_HELLO '+username) print(server.read_line(connection)) server.send(connection,'AI_GAME ') print(server.read_line(connection)) while True: if connectfour.winning_player(s)==connectfour.NONE: if s.turn==connectfour.RED: print('Player ',username) s=game_play(s,connection) common_file.board_display(s) elif s.turn==connectfour.YELLOW: print('Player AI') s=common_file.game_move(s,server.read(connection)) if s==None: print('Invalid move by Server') server.close(connection) return None common_file.board_display(s) elif connectfour.winning_player(s)==connectfour.RED: return username elif connectfour.winning_player(s)==connectfour.YELLOW: return 'AI'
def _conduct_connectfour_battle(): ''' conduct the battle with AI''' _welcome_banner() user_host = input('Please specify your IP address or a host.').strip() user_port = int(input('Please enter the port.')) user_id = input('Please enter your User ID.').strip() the_winner = connectfour.NONE user_player = connectfour.RED ai_player = connectfour.YELLOW column_number = connectfour.BOARD_COLUMNS connect_four_connection = connectfour_I32CFSP_final.connect(user_host, user_port) try: if connectfour_I32CFSP_final.login(connect_four_connection, user_id): print('Welcome, {}!'.format(user_id)) else: print('Login Failed.') #consdering to erase the "else" what do you think? if connectfour_I32CFSP_final.declare_match(connect_four_connection): print('Initializing the game.') else: print('Battle request Failed.') #consdering to erase the "else" what do you think? game_state = connectfour_tools.init_the_game() while the_winner == connectfour.NONE: _make_move_please(game_state, user_player, ai_player, user_id) try: action = connectfour_tools.ask_action() move = connectfour_tools.ask_move() if not connectfour_I32CFSP_final.drop_or_pop_request(action, move, connect_four_connection): raise connectfour.InvalidConnectFourMoveError() game_state = connectfour_tools.pop_or_drop(game_state, action, move) connectfour_tools.display_board(game_state.board) the_winner = connectfour.winning_player(game_state) # break if the user player wins on his/her move if the_winner != connectfour.NONE: break _make_move_please(game_state, user_player, ai_player, user_id) ai_message = connectfour_I32CFSP_final.classify_ai_move(connect_four_connection) game_state = connectfour_tools.pop_or_drop(game_state, ai_message.action, ai_message.move) connectfour_tools.display_board(game_state.board) the_winner = connectfour.winning_player(game_state) except ValueError: print('This is invalid move. Please type in 1~{}\n'.format(column_number)) except connectfour.InvalidConnectFourMoveError: print('This is invalid move. Please try again.\n') _print_the_winning_player(the_winner, user_player, ai_player, user_id) except: print('Disconnected! Goodbye!')
def menu() -> None: 'This function is the main menu of the connect four console game' game = connectfour.new_game_state() winner = connectfour.NONE while True: while True: username = input('Please enter a username (no spaces!): ').strip() if username.find(' ') < 0: break else: print( 'Invalid input. Please try a username without spaces.\n') host = input('Please enter the host name: ') while True: try: port = int(input('Please enter the port: ')) break except: print('Invalid input, please enter a number.\n') print('Trying to connect...') try: connection = connectfour_protocol.connect(host, port) print('Connected Successfully!') if connectfour_protocol.login(connection, username) == True: print('Login Successful!') if connectfour_protocol.startGame(connection) == True: print('Game Started!') break else: print('Could not Start Game! Try again.\n') connectfour_protocol.close(connection) else: print('Could not log in! Try again.\n') connectfour_protocol.close(connection) except: print('Connection Failed! Try again.\n') try: while winner == connectfour.NONE: while game.turn == connectfour.RED: connectfour_game_functions.printBoard(game) game = connectfour_game_functions.directions_network( game, username, connection) winner = connectfour.winning_player(game) if winner == connectfour.RED: break connectfour_game_functions.printBoard(game) game = connectfour_game_functions.move_network_ai(game, connection) winner = connectfour.winning_player(game) connectfour_game_functions.printBoard(game) if winner == connectfour.RED: print('The winner is ' + username + '!') else: print('The winner is AI!') finally: connectfour_protocol.close(connection)
def main(): print('Starting a new game...!') newgamestate = connectfour.new_game_state() ## connectfour.BOARD_ROWS = int(input('How many columns would you like to play with?: ')) ## connectfour.BOARD_COLUMNS = int(input('How many rows would you like to play with?: ')) while True: if newgamestate.turn == 'R': red_turn = int( input( '''Red's turn!\n Please enter the corresponding numbers for desired action\n 1.) Drop piece, 2.)Pop Piece: ''' )) if red_turn == 1: red_drop = int( input( "Enter number of column to drop red piece from 0 to {}: " .format(connectfour.BOARD_COLUMNS - 1))) if red_drop > connectfour.BOARD_COLUMNS or red_drop < 0: raise connectfour.InvalidConnectFourMoveError() else: newgamestate = connectfour.drop_piece( newgamestate, red_drop) print_board(newgamestate) else: red_pop = int( input( 'Enter column number to pop red piece from 0 to {}: '. format(connectfour.BOARD_COLUMNS - 1))) if red_pop > connectfour.BOARD_COLUMNS or red_pop < 0: raise connectfour.InvalidConnectFourMoveError() else: newgamestate = connectfour.pop_piece(newgamestate, red_pop) print_board(newgamestate) else: yellow_turn = int( input( '''Yellow's turn!\n Please enter the corresponding numbers for desired action\n 1.) Drop piece, 2.)Pop Piece: ''' )) if yellow_turn == 1: yellow_drop = int( input( "Enter column number to drop yellow piece from 0 to {}: " .format(connectfour.BOARD_COLUMNS - 1))) newgamestate = connectfour.drop_piece(newgamestate, yellow_drop) print_board(newgamestate) else: yellow_pop = int( input( 'Enter column number to pop yellow piece from 0 to {}: ' .format(connectfour.BOARD_COLUMNS - 1))) newgamestate = connectfour.pop_piece(newgamestate, yellow_pop) print_board(newgamestate) if connectfour.winning_player(newgamestate) == 'R': print('RED player has won! Congradulations!') break elif connectfour.winning_player(newgamestate) == 'Y': print('YELLOW player has won! Congradulations!') break
def menu() -> None: 'This function is the main menu of the connect four console game' game = connectfour.new_game_state() winner = connectfour.NONE while True: while True: username = input('Please enter a username (no spaces!): ').strip() if username.find(' ') < 0: break else: print('Invalid input. Please try a username without spaces.\n') host = input('Please enter the host name: ') while True: try: port = int(input('Please enter the port: ')) break except: print('Invalid input, please enter a number.\n') print('Trying to connect...') try: connection = connectfour_protocol.connect(host, port) print('Connected Successfully!') if connectfour_protocol.login(connection, username) == True: print('Login Successful!') if connectfour_protocol.startGame(connection) == True: print('Game Started!') break else: print('Could not Start Game! Try again.\n') connectfour_protocol.close(connection) else: print('Could not log in! Try again.\n') connectfour_protocol.close(connection) except: print('Connection Failed! Try again.\n') try: while winner == connectfour.NONE: while game.turn == connectfour.RED: connectfour_game_functions.printBoard(game) game = connectfour_game_functions.directions_network(game, username, connection) winner = connectfour.winning_player(game) if winner == connectfour.RED: break connectfour_game_functions.printBoard(game) game = connectfour_game_functions.move_network_ai(game, connection) winner = connectfour.winning_player(game) connectfour_game_functions.printBoard(game) if winner == connectfour.RED: print('The winner is ' + username + '!') else: print('The winner is AI!') finally: connectfour_protocol.close(connection)
def _conduct_connectfour_battle(): '''conduct the battle with AI''' _welcome_banner() user_host = input('Please specify your IP address or a host.').strip() user_port = int(input('Please enter the port.')) user_id = input('Please enter your User ID.').strip() the_winner = connectfour.NONE user_player = connectfour.RED ai_player = connectfour.YELLOW column_number = connectfour.BOARD_COLUMNS try: connect_four_connection = connectfour_I32CFSP_final.connect( user_host, user_port) if connectfour_I32CFSP_final.login(connect_four_connection, user_id): print('Welcome, {}!'.format(user_id)) if connectfour_I32CFSP_final.declare_match(connect_four_connection): print('Initializing the game.') game_state = connectfour_tools.init_the_game() while the_winner == connectfour.NONE: _make_move_please(game_state, user_player, ai_player, user_id) try: action = connectfour_tools.ask_action() move = connectfour_tools.ask_move() if connectfour_I32CFSP_final.drop_or_pop_request( action, move, connect_four_connection) == False: raise connectfour.InvalidConnectFourMoveError() game_state = connectfour_tools.pop_or_drop( game_state, action, move) connectfour_tools.display_board(game_state.board) the_winner = connectfour.winning_player(game_state) if the_winner != connectfour.NONE: break _make_move_please(game_state, user_player, ai_player, user_id) ai_message = connectfour_I32CFSP_final.classify_ai_move( connect_four_connection) game_state = connectfour_tools.pop_or_drop( game_state, ai_message.action, ai_message.move) connectfour_tools.display_board(game_state.board) the_winner = connectfour.winning_player(game_state) except ValueError: print('This is invalid move. Please type in 1~{}\n'.format( column_number)) except connectfour.InvalidConnectFourMoveError: print('This is invalid move. Please try again.\n') _print_the_winning_player(the_winner, user_player, ai_player, user_id) except: print('Disconnected! Goodbye!')
def check_game_progress(newgamestate): if connectfour.winning_player(newgamestate) == 'R': print('RED player has won! Congradulations!') return True elif connectfour.winning_player(newgamestate) == 'Y': print('YELLOW player has won! Congradulations!') return True else: return False
def move_menu(game): while True: C4S.print_board(game) print('Current turn: ' + game.turn) move = C4S.pop_or_drop() game = C4S.make_move(game, move) if connectfour.winning_player(game) == connectfour.RED or connectfour.winning_player(game) == connectfour.YELLOW: C4S.print_board(game) print('Winning player: ' + connectfour.winning_player(game)) break
def decide_over(state: connectfour.ConnectFourGameState)->bool: '''takes as input the state, and prints out the winner and return true if there is one''' if connectfour.winning_player(state) == connectfour.YELLOW: print('Game Over! The winner is Yellow!') return True elif connectfour.winning_player(state) == connectfour.RED: print('Game Over! The winner is Red!') return True return False
def who_r_you(): state = connectfour.new_game_state() mode = input( 'Please enter what mode you want to play as (s: server, c: client, con: console): ' ) if mode == 's': return server(state) elif mode == 'c': return client(state) elif mode == 'con': return console() state = connectfour.new_game_state() winner = ' ' print_board(state.board) while winner == ' ': drop_or_pop = input('It\'s ' + state.turn + ' turn. Do you want to drop or pop? ') while drop_or_pop == 'drop': column = input('Which column (0-6) do you want to drop? ') newstate = _drop_piece(state, column) if state != newstate: state = newstate winner = connectfour.winning_player(state) break while drop_or_pop == 'pop': try: column = input('Which column (0-6) do you want to pop? ') newstate = _pop_piece(state, column) if state != newstate: state = newstate winner = connectfour.winning_player(state) break if state.board == connectfour.new_game_state().board: break except: print( 'Error. There is no piece you can pop out.\n' + 'Please look for another column to pop out or you can drop another piece.' ) break while drop_or_pop != 'drop' and drop_or_pop != 'pop': print('Missspell. Please try again, drop or pop?') break else: if winner == 'R': print('Red won.') elif winner == 'Y': print('Yellow won.')
def who_r_you(): state = connectfour.new_game_state() mode=input('Please enter what mode you want to play as (s: server, c: client, con: console): ') if mode == 's': return server(state) elif mode == 'c': return client(state) elif mode == 'con': return console() state = connectfour.new_game_state() winner = ' ' print_board(state.board) while winner == ' ': drop_or_pop = input('It\'s ' + state.turn +' turn. Do you want to drop or pop? ') while drop_or_pop == 'drop': column = input('Which column (0-6) do you want to drop? ') newstate = _drop_piece(state,column) if state != newstate: state = newstate winner = connectfour.winning_player(state) break while drop_or_pop == 'pop': try: column = input('Which column (0-6) do you want to pop? ') newstate = _pop_piece(state,column) if state != newstate: state = newstate winner = connectfour.winning_player(state) break if state.board == connectfour.new_game_state().board: break except: print('Error. There is no piece you can pop out.\n' + 'Please look for another column to pop out or you can drop another piece.') break while drop_or_pop != 'drop' and drop_or_pop != 'pop': print('Missspell. Please try again, drop or pop?') break else: if winner == 'R': print('Red won.') elif winner == 'Y': print ('Yellow won.')
def main(): loaded = connectfour.new_game_state() while True: message = input( "message(enter 'DROP number(1-7)'or 'POP number(1-7)': ") test = loaded if len(message) == 6 and message[0:5] == "DROP ": if message[5] == "1" or message[5] == "2" or message[ 5] == "3" or message[5] == "4" or message[ 5] == "5" or message[5] == "6" or message[5] == "7": loaded = offline_library.DROP1(message, loaded) if loaded == None: loaded = test continue ###ask user to input POP or DROP, ###check if the operation is valid, ###if the action is invalid, ask user to input again if connectfour.winning_player(loaded) == True: winner = connectfour.winning_player(loaded) if winner == 1: print("Game over, Red wins!") break elif winner == 2: print("Game over, Yellow wins!") break ###call win function to check if there is a winner after user move elif len(message) == 5 and message[0:4] == "POP ": if message[4] == "1" or message[4] == "2" or message[ 4] == "3" or message[4] == "4" or message[ 4] == "5" or message[4] == "6" or message[4] == "7": loaded = offline_library.DROP1(message, loaded) if loaded == None: loaded = test continue if connectfour.winning_player(loaded) == True: winner = connectfour.winning_player(loaded) if winner == 1: print("Game over, Red wins!") break elif winner == 2: print("Game over, Yellow wins!") break else: print("Please enter valid operation.") continue
def main_program() -> None: ## while True: State = C.new_game_state() while True: winner = C.winning_player(State) F.new_board(State.board) if winner != C.NONE: break try: print("It's " + F.full_name(State.turn) + " player's turn. ", end = '') command = input(F.Menu).upper() if command == 'A': column_number = int(input('please enter the column number: ')) State = C.drop_piece(State, column_number - 1) print() elif command == 'B': column_number = int(input('please enter the column number: ')) State = C.pop_piece(State, column_number - 1) print() else: F.invalid_command(command) except C.InvalidConnectFourMoveError: print('\nInvaild command. Please try again.\n') except ValueError: print('\nError. Column number must be between 1 and 7.\n') except C.ConnectFourGameOverError: print('\nError. Game is over.\n') if winner == C.RED: print('Red player wins!') elif winner == C.YELLOW: print('Yellow player wins!') print()
def main(): '''function that runs connectfour consol''' print('Welcome to ConnectFour! \n') print('Player 1, you are the R player. Player 2, you are the Y player') the_winner = connectfour.NONE player_one = connectfour.RED player_two = connectfour.YELLOW connectfour_function.display_board(connectfour.new_game_state().board) game_state = connectfour.new_game_state() #play the game until it ends while the_winner == connectfour.NONE: if game_state.turn == player_one: print('Player 1 this is your turn. please make a move') else: print('Player 2 this is your turn. please make a move') try: move = int(input('where will you drop your piece? type 1~7')) - 1 game_state = connectfour.drop_piece(game_state, move) connectfour_function.display_board(game_state.board) the_winner = connectfour.winning_player(game_state) except ValueError: print('Invalid input. Please type integer between 1 and 7') except connectfour.InvalidConnectFourMoveError: print('The column is full. Please select other column') #print the winner if the_winner == player_one: print('player 1, you won!') else: print('player 2, you won!')
def init_game(): ''' Creates and instance of the game for 2 players and runs until there is a winner ''' game_state=connectfour.new_game_state() connectfourfunctions.print_board_game(game_state.board) winner = ' ' while True: try: player=(input(game_state.turn + ":Drop and a col number or Pop and a col number: ")) command,col=player.split() col=int(col) game_state=connectfourfunctions.give_turn(game_state,command,col) except: pass winner=connectfour.winning_player(game_state) connectfourfunctions.print_board_game(game_state.board) if (winner != ' '): print(winner+" Won") break
def main(): '''function that runs connectfour consol''' print('Welcome to ConnectFour! \n') print('Player 1, you are the R player. Player 2, you are the Y player') the_winner = connectfour.NONE player_one = connectfour.RED player_two = connectfour.YELLOW connectfour_function.display_board(connectfour.new_game_state().board) game_state = connectfour.new_game_state() #play the game until it ends while the_winner == connectfour.NONE: if game_state.turn == player_one: print('Player 1 this is your turn. please make a move') else: print('Player 2 this is your turn. please make a move') try: move = int(input('where will you drop your piece? type 1~7'))-1 game_state = connectfour.drop_piece(game_state, move) connectfour_function.display_board(game_state.board) the_winner = connectfour.winning_player(game_state) except ValueError: print('Invalid input. Please type integer between 1 and 7') except connectfour.InvalidConnectFourMoveError: print('The column is full. Please select other column') #print the winner if the_winner == player_one: print('player 1, you won!') else: print('player 2, you won!')
def _run_user_interface() -> None: ''' Runs the console-mode user interface from start to finish. Depending on if there is a winner or not, the end state game board will or will not be printed ''' winner = ' ' host=str((input("Enter Host: "))) port=int((input("Enter Port: "))) try: connection = connectfourserver.connect(host,port) username = _ask_for_username() connectfourserver.hello(connection, username) connectfourfunctions.print_board_game(game_state.board) while _handle_command(connection): _handle_ai_command(connection) if connectfourserver._expect_line(connection, 'READY') == False: break connectfourfunctions.print_board_game(game_state.board) except: print("Error when Connecting") connection=None finally: winner=connectfour.winning_player(game_state) if (winner != ' '): connectfourfunctions.print_board_game(game_state.board) if(connection!=None): connectfourserver.close(connection)
def move_pop(gamestate): try: pop = eval(input('please select a row(0-5): ')) except SyntaxError: print('invalid input') return move_pop(gamestate) except NameError: print('invalid input') return move_pop(gamestate) try: gamestate = gamestate._replace( board=connectfour.pop_piece(gamestate, pop).board, turn=connectfour._opposite_turn(gamestate.turn)) display_board(gamestate) return move_ops(gamestate) except ValueError: print('\n' + str(drop) + ' Not avalid column') move_pop(gamestate) except connectfour.ConnectFourGameOverError: print('Game Over') print('winner: ' + connectfour.winning_player(gamestate)) return except connectfour.InvalidConnectFourMoveError: print('Column is full') move_pop(gamestate)
def __init__(self: object): """Init new game""" self.state = connectfour.new_game_state() while True: self.print_state() winner = connectfour.winning_player(self.state) if winner != connectfour.NONE: if winner == connectfour.RED: print("Red is the winner!") elif winner == connectfour.YELLOW: print("Yellow is the winner!") break input_is_vaild = False while not input_is_vaild: action = self._get_input() try: if action["action"] == "d": self.state = connectfour.drop_piece( self.state, action["column_number"] - 1) elif action["action"] == "p": self.state = connectfour.pop_piece( self.state, action["column_number"] - 1) else: raise connectfour.InvalidConnectFourMoveError() input_is_vaild = True except: print("Sorry, invalid move.")
def start_game() -> None: print("\nGame has started") #creates a brand new game state that can be modified game_state = connectfour.new_game_state() while True: #Outputs the game to the console gamelogic.display_board(game_state) if game_state.turn == 'R': print("\nRed Player: Make your move!") if game_state.turn == 'Y': print("\nYellow Player: Make your move!") column_number = gamelogic.ask_for_column() move_type = gamelogic.ask_for_type() #updates the game state with the new moves in place game_state = gamelogic.make_move(game_state, column_number, move_type) #checks to see if a player has won winning_player = connectfour.winning_player(game_state) if winning_player != " ": if winning_player == "R": print("\n### Red Is The Winner! ###") elif winning_player == "Y": print("\n### Yellow Is The Winner! ### ") gamelogic.display_board(game_state) print() break
def _main(): '''function that runs connectfour consol''' _greet_to_players(connectfour.RED, connectfour.YELLOW) the_winner = connectfour.NONE player_one = connectfour.RED player_two = connectfour.YELLOW column_number = connectfour.BOARD_COLUMNS game_state = connectfour_tools.init_the_game() while the_winner == connectfour.NONE: _please_make_move(game_state, player_one, player_two) try: action = connectfour_tools.ask_action() move = connectfour_tools.ask_move() game_state = connectfour_tools.pop_or_drop(game_state, action, move) connectfour_tools.display_board(game_state.board) the_winner = connectfour.winning_player(game_state) except ValueError: print('This is invalid move. Please type in 1~{}\n'.format(column_number)) except connectfour.InvalidConnectFourMoveError: print('This is invalid move. Please try again.\n') connectfour_tools.print_the_winning_player(the_winner, player_one, player_two)
def play_console_only_game(): ''' The user plays for both the Red and Yellow players until there is a winner and the game ends ''' print('\nHere is the gameboard:\n') gameState = ConnectFour_ui.game_state() ConnectFour_ui.print_gameboard(gameState) while True: if connectfour.winning_player(gameState) != connectfour.NONE: print('\nPlayer', connectfour.winning_player(gameState), 'wins!\nThank you. Good-bye!') return else: move = ConnectFour_ui.user_move(gameState) gameState = move[0]
def main(): ''' Main function flow. ''' connectfour_ui.draw_current_board(connectfour.new_game_state()) current_game_state = connectfour.new_game_state() while True: if connectfour.winning_player(current_game_state) == 1: print("The winner is RED!") break elif connectfour.winning_player(current_game_state) == 2: print("The winner is YELLOW!") break move, column_number = connectfour_ui.move_input() current_game_state = connectfour_ui.move(move, column_number, current_game_state) connectfour_ui.draw_current_board(current_game_state)
def _run_user_interface() -> None: """ Main method for running player vs. player """ current_game_state = connectfour.new_game_state() while connectfour.winning_player(current_game_state) == connectfour.NONE: current_game_state = player_turn(current_game_state) print(connectfour_shared_methods.display_winner(current_game_state))
def game_handler(s: 'Game State'): '''Takes the current game state as an argument and calls the game_play function and the board_display function for each players move and returns the winning player ''' while True: if connectfour.winning_player(s) == connectfour.NONE: if s.turn == connectfour.RED: print('Player RED') s = game_play(s) common_file.board_display(s) elif s.turn == connectfour.YELLOW: print('Player YELLOW') s = game_play(s) common_file.board_display(s) elif connectfour.winning_player(s) == connectfour.RED: return 'RED' elif connectfour.winning_player(s) == connectfour.YELLOW: return 'YELLOW'
def _check_win(game_board: ConnectFourGameState): ''' Checks for a winner at the end of a turn ''' if connectfour.winning_player(game_board) != ' ': winner = True print(_game_over(game_board)) return winner else: pass
def game(): try: host = input("Please enter the host: ") port = input("Please enter the port: ") user_name = input("Please enter Username: "******"Invalid host/port") else: while connectfour.winning_player(game_state) == connectfour.NONE: try: print("[ This is "+'['+"R"+']'+" player's turn ]") print() drop_pop = connectfour_console.drop_input() column_number = input("Which column do you want to drop on? 1-7") print() connectfour_console.valid(game_state,drop_pop) game_state = connectfour_console.pop_n_drop(game_state, drop_pop,column_number) except: print('Please enter drop or pop and a column number from 1 - 7') else: print("[ This is "+'['+"Y"+']'+" player's turn ]") print() print( "THE SERVER'S RESPONSE:") write_to_server = (drop_pop.upper() + ' ' + str(column_number)) server_response = I32CFSP.server_drop(the_connection, write_to_server) if server_response == 'WINNER_RED': break if server_response != 'READY': #Adresses the server invalid server_drop = server_response.split()[0] server_col = server_response.split()[1] game_state = connectfour_console.pop_n_drop(game_state, server_drop, server_col) finally: print(' - CONGRATULATIONS PLAYER: '+connectfour.winning_player(game_state)) I32CFSP.socket_close(the_connection)
def makingmove(stream_socket, state, winner): line_in = I32CFP.read_move(stream_socket) player_game_state = convert_gamestate(state, line_in) winner = connectfour.winning_player(state) if winner != ' ': return winner else: s_move_ops(player_game_state, stream_socket) return winner
def makingmove(stream_socket,state, winner): line_in = I32CFP.read_move(stream_socket) player_game_state = convert_gamestate(state,line_in) winner = connectfour.winning_player(state) if winner != ' ': return winner else: s_move_ops(player_game_state, stream_socket) return winner
def makingmove(stream_socket,state, winner): line = stream_socket.makefile('r') line_in = line.readline() line.close() player_game_state = convert_gamestate(state,line_in) winner = connectfour.winning_player(state) if winner != ' ': return winner else: s_move_ops(player_game_state, stream_socket) return winner
def makingmove(stream_socket, state, winner): line = stream_socket.makefile('r') line_in = line.readline() line.close() player_game_state = convert_gamestate(state, line_in) winner = connectfour.winning_player(state) if winner != ' ': return winner else: s_move_ops(player_game_state, stream_socket) return winner
def gameplay() -> None: board = connectfour.new_game_state() display_board(board[0]) while True: try: if connectfour.winning_player(board) == ' ': if board[1] == 'R': print('\nRed\'s Turn') column = int(input('Enter column number: ')) if board[0][column - 1][-1] == 'R': board = pop_or_drop(board, column) else: board = connectfour.drop_piece(board, column - 1) display_board(board[0]) else: print('\nYellow\'s Turn') column = int(input('Enter column number: ')) if board[0][column - 1][-1] == 'Y': board = pop_or_drop(board, column) else: board = connectfour.drop_piece(board, column - 1) display_board(board[0]) else: player = "" if connectfour.winning_player(board) == 'R': player += "Red Player" else: player += "Yellow Player" print('Game is over! ' + player + ' is the winner!') break except IndexError: print('Column number you entered is not in the range of 1-7!\n') display_board(board[0]) except ValueError: print('Not an integer!\n') display_board(board[0]) except connectfour.InvalidConnectFourMoveError: print('Column is full! Please enter another column number!\n') display_board(board[0])
def mainsingle(): """this is the main function frame that operate in the single player status""" ConnectFourGameState = connectfour.new_game_state() print('Game start!\n') printboard(ConnectFourGameState) print("Enter your move(for example, 'DROP column#' or 'POP column#'\n") while True: #check if there is a winner winnernum = connectfour.winning_player(ConnectFourGameState) if winnernum == connectfour.NONE: if not checkboard(ConnectFourGameState): while True: if ConnectFourGameState[1] == int(1): print("Red turn.") elif ConnectFourGameState[1] == int(2): print("Yellow turn.") try: originalcommand = input("Enter your move: ") order, colnum = command(originalcommand) if (order == 'POP' or order == 'pop') or (order == 'DROP' or order == 'drop'): break else: print( "\nInput format error (must be 'DROP column#' or 'POP column#')\n" ) except: print( "\nInput format error (must be 'DROP column#' or 'POP column#')\n" ) if order == 'DROP' or order == 'drop': try: ConnectFourGameState = connectfour.drop_piece( ConnectFourGameState, colnum - 1) except connectfour.InvalidMoveError: print('\nSorry, this column is already full\n') if order == 'POP' or order == 'pop': try: ConnectFourGameState = connectfour.pop_piece( ConnectFourGameState, colnum - 1) except connectfour.InvalidMoveError: print('\nSorry, this column is empty\n') printboard(ConnectFourGameState) else: print('\nThe board is already full, no winner.\n') return else: break printwinner(winnernum)
def menu() -> None: 'This function is the main menu of the connect four console game' game = connectfour.new_game_state() winner = connectfour.NONE while winner == connectfour.NONE: connectfour_game_functions.printBoard(game) game = connectfour_game_functions.directions_console(game) winner = connectfour.winning_player(game) connectfour_game_functions.printBoard(game) if winner == connectfour.RED: print('The winner is Red!') else: print('The winner is Yellow!')
def console(): state = connectfour.new_game_state() winner = ' ' print_board(state.board) while winner == ' ': drop_or_pop = input('It\'s ' + state.turn +' turn. Please enter either drop or pop: ') while drop_or_pop == 'drop': column = input('Please enter one number from 0 to 6 for the column you want to drop: ') newstate = _drop_piece(state,column) if state != newstate: state = newstate winner = connectfour.winning_player(state) break while drop_or_pop == 'pop': try: column = input('Please enter one number from 0 to 6 for the column you want to pop: ') newstate = _pop_piece(state,column) if state != newstate: state = newstate winner = connectfour.winning_player(state) break if state.board == connectfour.new_game_state().board: break except: print('Error. There is no piece you can pop out.\n' + 'Please look for another column to pop out or you can drop another piece.') break while drop_or_pop != 'drop' and drop_or_pop != 'pop': print('Error. Please enter either drop or pop.') break else: if winner == 'R': print('Red won.') elif winner == 'Y': print ('Yellow won.')
def console_UI(): welcome() game = both.init_game() while both.continue_game(game): print(both.player_name(game.turn)+" player's turn.") move = both.move_decision() column = both.column_decision() print() update_game = both.operate_move(game, move, column) game = update_game print("Congratulations!", both.player_name(connectfour.winning_player(game)), "player wins")
def mainsingle(): #type in 'asfa' return error """this is the main function frame that operate in the single player status""" ConnectFourGameState = connectfour.new_game_state() print('Game start!\n') printboard(ConnectFourGameState) originalcommand = input( "Enter your move(for example, 'DROP column#' or 'POP column#'): ") # instruct player only once about the input format # print board once at the beginning # print whose turn it is # ? ask user to drop and pop (dont change this one now, lets finish other parts first) # accept both capital and lower case while True: #check if there is a winner winnernum = connectfour.winning_player(ConnectFourGameState) if winnernum == connectfour.NONE: if not checkboard(ConnectFourGameState): while True: try: originalcommand = input("Enter your move: ") commandlist = originalcommand.split() order = commandlist[0] colnum = int(commandlist[1]) if (order == 'POP') or (order == 'DROP'): break except: print( "Input format error (must be 'DROP column#' or 'POP column#')" ) if order == 'DROP': try: ConnectFourGameState = connectfour.drop_piece( ConnectFourGameState, colnum - 1) except (connectfour.InvalidMoveError): print('Sorry, this column is already full') if order == 'POP': try: ConnectFourGameState = connectfour.pop_piece( ConnectFourGameState, colnum - 1) except (connectfour.InvalidMoveError): print('Sorry, this column is empty') printboard(ConnectFourGameState) else: print('The board is already full, no winner.') return else: break printwinner(winnernum)
def s_move_drop(state, socket): try: column = eval(input('Which column (0-6) do you want to drop? ')) newstate = _drop_piece(state, column) if state != newstate: state = newstate winner = connectfour.winning_player(state) mode = 'DROP' if state.turn == 'R': wait_player_move(mode, column, socket) elif state.turn == 'Y': wait_server_move(mode, column, socket) finally: return state
def _current_game(current_game: connectfour.ConnectFourGameState, internet=False, connection=None) -> None: '''Makes the moves on the game board''' _print_board(current_game) if internet == False: while connectfour.winning_player(current_game) == connectfour.NONE: split_command = handle_game_menu(current_game).split() if split_command[0] == 'DROP': current_game = connectfour.drop_piece( current_game, int(split_command[1]) - 1) elif split_command[0] == 'POP': current_game = connectfour.pop_piece(current_game, int(split_command[1]) - 1) _print_board(current_game) if connectfour.winning_player(current_game) == 'R': print('Game Over. Red Player has won.') elif connectfour.winning_player(current_game) == 'Y': print('Game Over. Yellow Player has won.') elif internet == True: status = 'OKAY' while status != 'WINNER_RED' or 'WINNER_YELLOW': current_game, status = _send_game_move(connection, current_game) _print_board(current_game) if connectfour.winning_player(current_game) == 'R': status = 'WINNER_RED' break elif connectfour.winning_player(current_game) == 'Y': status = 'WINNER_YELLOW' break print('\n') print("Recieving AI's move...") current_game = _recieve_game_move(connection, current_game) print('Move recieved.') input("Please enter a key to see the AI's move") _print_board(current_game) if connectfour.winning_player(current_game) == 'R': status = 'WINNER_RED' break elif connectfour.winning_player(current_game) == 'Y': status = 'WINNER_YELLOW' break if status == 'WINNER_RED': print('Game Over. Red Player has won.') elif status == 'WINNER_YELLOW': print('Game Over. Yellow Player has won.') else: print(status) print('Error. Ending Game.')
def s_move_drop(state,socket): try: column = eval(input('Which column (0-6) do you want to drop? ')) newstate = _drop_piece(state,column) if state != newstate: state = newstate winner = connectfour.winning_player(state) mode = 'DROP' if state.turn == 'R': wait_player_move(mode, column, socket) elif state.turn == 'Y': wait_server_move(mode,column,socket) finally: return state
def s_move_drop(state,socket): while True: column = input('Which column (0-6) do you want to drop? ') newstate = _drop_piece(state,column) if state != newstate: state = newstate winner = connectfour.winning_player(state) break mode = 'DROP' if state.turn == 'R': wait_player_move(mode, column, socket) elif state.turn == 'Y': wait_server_move(mode,column,socket) return state
def s_move_drop(state, socket): while True: column = input('Which column (0-6) do you want to drop? ') newstate = _drop_piece(state, column) if state != newstate: state = newstate winner = connectfour.winning_player(state) break mode = 'DROP' if state.turn == 'R': wait_player_move(mode, column, socket) elif state.turn == 'Y': wait_server_move(mode, column, socket) return state
def check_win(game_state : connectfour.ConnectFourGameState) -> bool: ''' Checks if there is a winner and print who it is if ther is one, otherwise it prints whoever's turn it is, returning True if there is a winner and false otherwise. ''' winner = connectfour.winning_player(game_state)#Checks if there is a winner if winner == connectfour.NONE:#If no winner then display current player's turn if game_state[1] == connectfour.RED: print('It is now RED\'s turn.') else: print('It is now YELLOW\'s turn.') return False #return false else: #Otherwise print the winning player's name and return true if winner == connectfour.RED: print('The Winner is RED!') else: print('The Winner is YELLOW!') print('Thank you for playing!') return True
def s_move_drop(state,socket): try: column = input('Which column (0-6) do you want to drop? ') newstate = _drop_piece(state,column) if state != newstate: state = newstate winner = connectfour.winning_player(state) except: print('Error. There is no piece you can pop out.\n' + 'Please look for another column to pop out or you can drop another piece.') try: mode = 'DROP' if state.turn == 'R': wait_player_move(mode, column, socket) elif state.turn == 'Y': wait_server_move(mode,column,socket) finally: return state
def s_move_pop(state,socket): try: column = eval(input('Which column (0-6) do you want to drop? ')) except: print('Invalid input') return s_move_pop(state,socket) try : newstate = _pop_piece(state,column) if state != newstate: state = newstate winner = connectfour.winning_player(state) mode = 'POP' if state.turn == 'R': wait_player_move(mode, column,socket) elif state.turn == 'Y': wait_server_move(mode, column,socket) except: print('\n' + str(column) + ' Not avalid column') s_move_ops(state,socket) finally: return state
def conduct_connectfour_battle(user_host: str, user_port: int, user_id: str) -> None: the_winner = connectfour.NONE the_user = connectfour.RED try: s = connect_socket(user_host, user_port, user_id) setup_game(s) print('Connected! Let the Battle Begin!!!!!') game_state = connectfour.new_game_state() connectfour_consol.display_board(game_state.board) while the_winner == connectfour.NONE: if game_state.turn == the_user: print('%s this is your turn. Please make a move.' % user_id) move = int(input('where will you drop your piece? type 1~7.'))-1 else: game_state = connectfour.drop_piece(game_state, move) display_board(game_state.board) the_winner = connectfour.winning_player(game_state) except: print('Connection failed. Closing the game.') finally: s.close()
def move_drop(gamestate): try: drop = eval(input('please select a row(0-5): ')) except SyntaxError: print('invalid input') return move_drop(gamestate) except NameError: return move_drop(gamestate) try : gamestate = gamestate._replace(board = connectfour.drop_piece(gamestate, drop).board, turn= connectfour._opposite_turn(gamestate.turn)) display_board(gamestate) return move_ops(gamestate) except ValueError: print('\n' + str(drop) + ' Not avalid column') move_drop(gamestate) except connectfour.ConnectFourGameOverError: print('Game Over') print('winner: ' + connectfour.winning_player(gamestate)) return except connectfour.InvalidConnectFourMoveError: print('you can only pop your own peice') move_drop(gamestate)
def play_game(connection:i32cfsp.i32cfconnection, username: str) -> None: '''plays game''' last_state = connectfour.new_game_state() linkui._rotate_board(last_state) while True: print(username) option = linkui._ask_for_option() if option == 'D': try: col = linkui._ask_for_col_drop() except: print("invalid value.") else: last_state = linkui._option_d(last_state, col) if connectfour.winning_player(last_state) != ' ': print("Player " + username[1:] + " (Red) wins!") break print() if i32cfsp.login(connection, username): move = send_read_server(option, col, connection) if move[0] == 'D': col_server = int(move[-1]) last_state = linkui._option_d(last_state, col_server) i32cfsp._read_line(connection) elif move[0] == 'P': col_server = int(move[-1]) last_state = linkui._option_p(last_state, col_server) i32cfsp._read_line(connection) if connectfour.winning_player(last_state) != ' ': print("Computer (Yellow) wins!") break else: print("Connection lost") elif option == 'P': try: col = linkui._ask_for_col_pop() except: print("invalid value.") else: last_state = linkui._option_p(last_state, col) if connectfour.winning_player(last_state) != ' ': print("Player " + username[1:]+ " (Red) wins!") break print() if i32cfsp.login(connection, username): move = send_read_server(option, col, connection) if move[0] == 'D': col_server = int(move[-1]) last_state = linkui._option_d(last_state, col_server) i32cfsp._read_line(connection) elif move[0] == 'P': col_server = int(move[-1]) last_state = linkui._option_p(last_state, col_server) i32cfsp._read_line(connection) if connectfour.winning_player(last_state) != ' ': print("Computer (Yellow) wins!") break else: print("Connection lost") else: print('Invalid command')
def server_game(Start_Game,move_info, socket): player_game_state = convert_gamestate(Start_Game,move_info) display_board(player_game_state) winning_player = connectfour.winning_player(Start_Game) s_move_ops(player_game_state, socket) pass
def main_program(host, port) -> None: username = _P_.confirm_username() game_socket = socket.socket() try: print('\nconnecting to server...\n') game_socket.connect((host, port)) print('Connected successfully.\n') _P_.send_message(game_socket, str('I32CFSP_HELLO ' + username)) reply1 = _P_.receive_message(game_socket) print(reply1, end = '\n\n') _P_.send_message(game_socket, 'AI_GAME') reply2 = _P_.receive_message(game_socket) print(reply2, end = '\n\n') except ConnectionRefusedError: print('Invalid port') return 'Invalid' ## while True: State = _X_.new_game_state() while True: winner = _X_.winning_player(State) _F_.new_board(State.board) if winner != _X_.NONE: break try: _F_.turn(State.turn) command = input(_F_.Menu).upper() if command == 'A': column_number = int(input('please enter the column number: ')) State = _X_.drop_piece(State, column_number - 1) print() AI = _P_.AI(game_socket, 'A', column_number).split() ## print(AI) ## _C_.new_board(State.board) ## print() ## _N_.AI_turn(State.turn) if AI[0] == 'DROP': State = _X_.drop_piece(State, int(AI[1]) - 1) elif AI[0] == 'POP': State = _X_.pop_piece(State, int(AI[1]) - 1) elif command == 'B': column_number = int(input('please enter the column number: ')) State = _X_.pop_piece(State, column_number - 1) print() AI = _P_.AI(game_socket, 'B', column_number).split() ## print(AI) ## _C_.new_board(State.board) ## print() ## _N_.AI_turn(State.turn) if AI[0] == 'DROP': State = _X_.drop_piece(State, int(AI[1]) - 1) elif AI[0] == 'POP': State = _X_.pop_piece(State, int(AI[1]) - 1) else: _F_.invalid_command(command) except _X_.InvalidConnectFourMoveError: print('\nInvaild command. Please try again.\n') except ValueError: print('\nError. Column number must be between 1 and 7.\n') except _X_.ConnectFourGameOverError: print('\nError. Game is over.\n') if winner == _X_.RED: print('Red player wins!') elif winner == _X_.YELLOW: print('Yellow player wins!') ## restart = input('\nPlay again? (Y/N)').upper() ## if restart == 'Y': ## print('game restart!\n\n') ## State = _X_.new_game_state() ## elif restart == 'N': ## print('\nThanks for playing, Bye!') ## break ## else: ## _C_.invalid_command(restart) print('\nGame is over.\nThanks for playing, Bye!')