def handle_cheater(self, game_result, current_matchup): """ game_result is in the format [[winner_player_object, score], [cheating_player_object, score], cheating_flag] current_matchup is a tuple containing the two indicies of the self.players objects that are playing each other """ # Generate the new default player that will be taking the place # of the cheating player for the remaining games new_player = PlayerFactory(path=self.default_player).create() new_player.register() cheating_player = game_result[1][0] winning_player = game_result[0][0] self.player_score[cheating_player] = -1 self.player_score[new_player] = 0 self.player_score[winning_player] += 1 if cheating_player == self.players[current_matchup[0]]: self.players[current_matchup[0]] = new_player self.game_results[current_matchup] = current_matchup[1] cheating_player = current_matchup[0] else: self.players[current_matchup[1]] = new_player self.game_results[current_matchup] = current_matchup[0] cheating_player = current_matchup[1] self.fix_history(cheating_player)
def parse_command(self, command): if command[0] == "register": if self.player: return CRAZY_GO self.player = PlayerFactory(remote=True).create() self.player.register() return self.player.get_name() elif command[0] == "receive-stones": try: self.player.set_stone(command[1]) return 'RECEIVE' except (StoneException, AttributeError): return CRAZY_GO elif command[0] == "make-a-move": try: if not self.player or self.player.get_stone() == "": return CRAZY_GO if not checkhistory(command[1], self.player.get_stone()): return ILLEGAL_HISTORY_MESSAGE return self.player.make_move(command[1]) except (StoneException, BoardException, IndexError): #print("2") return CRAZY_GO else: return CRAZY_GO
def __init__(self, player_list, timed): self.factory = PlayerFactory() self.players = [self.factory.get_player_type(player, index+1) for index, player in enumerate(player_list) ] self.game = TimedGameProxy(TimedProxy(Game(self.players, Die()))) self.game.set_time(timed) self.CLI = True self.game_num = 0 self.timed = timed
def create_server_conn(self): self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((self.host, self.port)) self.server_socket.listen(1) self.started = False self.conn, self.addr = self.server_socket.accept() self.proxy_player = PlayerFactory(connection=self.conn).create() self.default_player = PlayerFactory( path=self.default_player_path).create() self.start_game()
def register_players(self): #print("registering") for p in range(len(self.players)): resp = self.players[p].register() print(resp) if not resp: #Replace player that doesn't register with a default player print("replacing player") self.players[p] = PlayerFactory( path=self.default_player_path).create() self.players[p].register()
def make_players(self): #self.players = [] self.num_players = nextPowerOf2(self.num_players) #for conn in connection_list: #proxy_player = PlayerFactory(connection=conn).create() #self.players.append(proxy_player) while self.num_players != len(self.players): default_player = PlayerFactory( path=self.default_player_path).create() self.players.append(default_player) print("made a new player") self.register_players()
def get_connections(self): connections = [] self.players = [] print("getting players") self.server_socket.listen(self.num_players) while self.num_players != len(self.players): #print("started loop") conn, addr = self.server_socket.accept() proxy_player = PlayerFactory(connection=conn).create() self.players.append(proxy_player) print("new player on conn: ", conn) #connections.append(conn) #print(self.players) self.make_players() self.server_socket.close()
class Administrator: def __init__(self): self.load_config() self.create_server_conn() def load_config(self): config_file = open(GO_CONFIG_PATH, 'r') config_file = config_file.read() netData = readJSON(config_file) netData = netData[0] self.host = netData['IP'] self.port = netData['port'] self.default_player_path = netData['default-player'] def create_server_conn(self): self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((self.host, self.port)) self.server_socket.listen(1) self.started = False self.conn, self.addr = self.server_socket.accept() self.proxy_player = PlayerFactory(connection=self.conn).create() self.default_player = PlayerFactory( path=self.default_player_path).create() self.start_game() def start_game(self): choice = random.randint(0, 1) if choice: referee = Referee(self.proxy_player, self.default_player) else: referee = Referee(self.default_player, self.proxy_player) # referee = Referee(self.proxy_player, self.default_player) if choice else Referee(self.default_player, self.proxy_player) print(json.dumps(referee.get_winner())) self.close_connection() def close_connection(self): if self.proxy_player.is_connected(): self.conn.shutdown(1) self.conn.close() else: self.conn.close()
def __init__(self): #, gui=True,path=netData['default-player'] netData = readConfig(GO_CONFIG_PATH)[0] self.player = PlayerFactory(remote=True).create() self.connect_socket(netData) self.start_client()
class RemoteReferee: buffer = 131072 def __init__(self): #, gui=True,path=netData['default-player'] netData = readConfig(GO_CONFIG_PATH)[0] self.player = PlayerFactory(remote=True).create() self.connect_socket(netData) self.start_client() def connect_socket(self, data: dict): host = data['IP'] port = data['port'] #print(host) #print(port) connected = False #Connect iter = 0 #print("trying to connect") while not connected: try: #print("Trying to connect") self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client_socket.connect((host, port)) #print("connected") connected = True except ConnectionRefusedError: iter += 1 if iter == 20: #see here break self.client_socket.close() time.sleep(2) continue def start_client(self): #print("starting client") #### USE FACTORY while True: try: resp = self.client_socket.recv(self.buffer) resp = resp.decode("UTF-8") except ConnectionResetError: self.client_socket.close() break #there is nothing coming from the server, so it has disconnected if not resp: #self.client_socket.shutdown(socket.SHUT_WR) self.client_socket.close() #print("Client closed") break elif resp: resp_json = readJSON(resp) output = self.parse_command(resp_json[0]) print(output) if not output: continue if output == "close": self.client_socket.shutdown(1) self.client_socket.close() break output = '"' + output + '"' self.client_socket.send(output.encode('utf-8')) def parse_command(self, command): print(command) if not isinstance(command, list): return "close" if command[0] == "register": try: return self.player.register() except (PlayerStateViolation, PlayerTypeError) as e: print( "REGISTER: Remote Player proxies found a problem with error: {} in register" .format(e)) return "close" elif command[0] == "receive-stones": try: self.player.receive_stones(command[1]) return except (StoneException, PlayerStateViolation, PlayerTypeError) as e: print( "RECEIVE: Remote Player proxies found a problem with error: {} in receive" .format(e)) return "close" elif command[0] == "make-a-move": try: if not self.player or self.player.get_stone() == "": return CRAZY_GO if not checkhistory(command[1], self.player.get_stone()): return ILLEGAL_HISTORY_MESSAGE return self.player.make_move(command[1]) except (StoneException, BoardException, IndexError, PlayerStateViolation, PlayerTypeError) as e: print( "MAKE MOVE: Remote Player proxies found a problem with error: {} in make move" .format(e)) return "close" elif command[0] == "end-game": try: return self.player.end_game() except (PlayerTypeError, PlayerStateViolation) as e: print( "END GAME: Remote Player proxies found a problem with error: {}" .format(e)) return "close"
class RemoteReferee: buffer = 131072 def __init__(self): netData = readConfig(GO_CONFIG_PATH)[0] self.player = None self.connect_socket(netData) self.start_client() def connect_socket(self, data: dict): host = data['IP'] port = data['port'] #print(host) #print(port) connected = False #Connect iter = 0 while not connected: try: #print("Trying to connect") self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client_socket.connect((host, port)) connected = True except ConnectionRefusedError: iter += 1 if iter == 20: sys.exit() self.client_socket.close() time.sleep(2) continue def start_client(self): #### USE FACTORY while True: resp = self.client_socket.recv(self.buffer) resp = resp.decode("UTF-8") #there is nothing coming from the server, so it has disconnected if not resp: #self.client_socket.shutdown(socket.SHUT_WR) self.client_socket.close() #print("Client closed") break elif resp: resp_json = readJSON(resp) output = self.parse_command(resp_json[0]) #print(output) if output == "close": self.client_socket.shutdown(1) self.client_socket.close() break self.client_socket.send(str.encode(output)) def parse_command(self, command): if command[0] == "register": if self.player: return CRAZY_GO self.player = PlayerFactory(remote=True).create() self.player.register() return self.player.get_name() elif command[0] == "receive-stones": try: self.player.set_stone(command[1]) return 'RECEIVE' except (StoneException, AttributeError): return CRAZY_GO elif command[0] == "make-a-move": try: if not self.player or self.player.get_stone() == "": return CRAZY_GO if not checkhistory(command[1], self.player.get_stone()): return ILLEGAL_HISTORY_MESSAGE return self.player.make_move(command[1]) except (StoneException, BoardException, IndexError): #print("2") return CRAZY_GO else: return CRAZY_GO
class Play: def __init__(self, player_list, timed): self.factory = PlayerFactory() self.players = [ self.factory.get_player_type(player, index + 1) for index, player in enumerate(player_list) ] self.game = TimedGameProxy(TimedProxy(Game(self.players, Die()))) self.game.set_time(timed) self.CLI = True self.game_num = 0 self.timed = timed def timed_game(self, current_game, game_players): start_time = time.time() time_elapsed = 0 while self.CLI: while current_game.check_highest_score( ) < 100 or time_elapsed > self.game.get_time(): time_elapsed = time.time() - start_time for player in game_players: player.set_player_rolling_state(True) while player.get_player_rolling_state( ) and current_game.check_highest_score( ) < 100 and time_elapsed < self.game.get_time(): time_elapsed = time.time() - start_time if time_elapsed > self.game.get_time(): self.end_game(current_game) return else: self.check_player_input(player, current_game) if current_game.check_highest_score( ) >= 100 or time_elapsed > self.game.get_time(): self.end_game(current_game) def play_reg_game(self, current_game, game_players): while self.CLI: while current_game.check_highest_score() < 100: for player in game_players: player.set_player_rolling_state(True) while player.get_player_rolling_state( ) and current_game.check_highest_score() < 100: self.check_player_input(player, current_game) if current_game.check_highest_score() >= 100: self.end_game(current_game) def start(self): """ The start function of the play class that encapsulates the rules of the game. Parameters: None """ current_game = self.game game_players = current_game.get_players() self.play_reg_game( current_game, game_players) if self.timed == 0 else self.timed_game( current_game, game_players) def check_player_input(self, player, current_game): """ A function that checks the key input entered by a player on their turn. Parameters: player(<Player>) current_game(<Game>) Logs: An error if a key is entered that isn't an 'h' or 'r' """ if player.factory_type == 'computer': tally = current_game.sum_tally(player) cpu_score = player.get_player_score() cpu_input = player.execute_strategy(tally, cpu_score) self.hold_action( player, current_game) if cpu_input == 'h' else self.roll_action( player, current_game) return player_input = input( f'Player {player.get_player_name()} would you like to ("r") roll or ("h") hold?\n' ) if player_input.lower() == 'h': self.hold_action(player, current_game) elif player_input.lower() == 'r': self.roll_action(player, current_game) else: print_unintended_keystroke() logging.error( f'unintended_keystroke for Player: {player.get_player_name()} typed in: {player_input}' ) def hold_action(self, player, current_game): current_game.hold(player) score_list = current_game.get_score_list() print_current_score(score_list, self.game_num + 1, player) def roll_action(self, player, current_game): num_rolled = current_game.roll_die(player) score_list = current_game.get_score_list() print_die_roll_message(num_rolled, player.get_player_name(), player.factory_type) print_current_score(score_list, self.game_num + 1, player) def retreive_winner(self, current_game): """ A function that retrieves the winner of a game and prints it. Parameters: current_game(<Game>) """ high_scorer = get_winner(current_game.get_score_list()) print_game_winner(high_scorer, self.game_num + 1) def end_game(self, current_game): """ A function that resets a game ends it and moves onto the next game if present. Parameters: current_game(<Game>) """ self.retreive_winner(current_game) self.game_num = self.game_num + 1 current_game.reset_game() self.CLI = False
import os os.environ['SDL_VIDEO_WINDOW_POS'] = '1000, 400' surface = pygame.display.set_mode( (3 * Grid.TILE_WIDTH, Grid.TOP_PANEL_HEIGHT + 3 * Grid.TILE_HEIGHT)) pygame.display.set_caption('Tic Tac Toe') pygame.font.init() clock = pygame.time.Clock() clock.tick(60) game_manager = GameManager() grid = Grid() factory = PlayerFactory(surface) player_one, player_two = factory.get_players() active_player = player_one game_over = False valid_hit = True while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if not game_over and event.type == pygame.MOUSEBUTTONDOWN: if pygame.mouse.get_pressed()[0]: pos = pygame.mouse.get_pos() tile = (pos[0] // Grid.TILE_WIDTH,
def __init__(self): netData = readConfig(GO_CONFIG_PATH)[0] self.player = PlayerFactory(remote=True).create() self.connect_socket(netData) self.start_client()