def test_player_alive_money(): game = Game() game.setPlayers([Player()]) player = game.getPlayers()[0] player.setMoney(0) game.checkMoneyRule(player) assert player.getAlive() == False
def test_White_King_Castle(): """ Tests if White pieces can do king side castle """ myGame = Game() def move(x, moveOne, moveTwo): x.board[x.possibleRow[int( moveOne[0])]][x.possibleCol[moveOne[1]]].move( int(moveTwo[0]), moveTwo[1]) king = myGame.board[7][4] rook = myGame.board[7][7] move(myGame, "7E", "5E") move(myGame, "8F", "7E") move(myGame, "8G", "6H") myGame.attemptKingCastle(not myGame.playerOneTurn) assert king == myGame.board[7][6] assert rook == myGame.board[7][5]
def test_bet(self): game = Game() p = AIPlayer(Game=game) deck = Deck() p.hands.append([deck.draw_card() for i in range(2)]) a, b = p.act(game) self.assertEqual(a, 0) self.assertEqual(b, 20)
def loadTips(self): jogos = np.loadtxt(self.filelocation, dtype='str', delimiter='\t',skiprows=1) lista = list() for jogo in jogos: game = Game(jogo[0], jogo[1:16].astype(int)) lista.append(game) return lista
def test_King_Castle(): """Tests if you can do king side castle """ myGame = Game() def move(x, moveOne, moveTwo): x.board[x.possibleRow[int( moveOne[0])]][x.possibleCol[moveOne[1]]].move( int(moveTwo[0]), moveTwo[1]) king = myGame.board[0][4] rook = myGame.board[0][7] move(myGame, "2E", "4E") move(myGame, "1F", "2E") move(myGame, "1G", "3H") myGame.attemptKingCastle(myGame.playerOneTurn) assert king == myGame.board[0][6] assert rook == myGame.board[0][5]
def test_collectPool(): game = Game(players=[Player()]) sq = FreeParking() game.setPool(100) assert game.getPool() == 100 sq.run(0,game) assert game.getPool() == 0 assert game.getPlayer(0).getMoney() == 100
def test_bet(self): game = Game() p = HumanPlayer(Game=game) p.standing = [False, False] deck = Deck() p.hands.append([deck.draw_card() for i in range(2)]) a, b = p.act(game) self.assertEqual(a, 0) self.assertEqual(b, 50)
def test_Queen_Castle(): """Tests Queen Side Castle """ myGame = Game() def move(x, moveOne, moveTwo): x.board[x.possibleRow[int( moveOne[0])]][x.possibleCol[moveOne[1]]].move( int(moveTwo[0]), moveTwo[1]) king = myGame.board[0][4] rook = myGame.board[0][0] move(myGame, "2D", "4D") move(myGame, "1D", "3D") move(myGame, "1C", "3E") move(myGame, "1B", "3A") myGame.attemptQueenCastle(myGame.playerOneTurn) assert king == myGame.board[0][2] assert rook == myGame.board[0][3]
def test_White_Queen_Castle(): """Tests if White pieces can do Queen side castle """ myGame = Game() def move(x, moveOne, moveTwo): x.board[x.possibleRow[int( moveOne[0])]][x.possibleCol[moveOne[1]]].move( int(moveTwo[0]), moveTwo[1]) king = myGame.board[7][4] rook = myGame.board[7][0] move(myGame, "7D", "5D") move(myGame, "8D", "6D") move(myGame, "8C", "7D") move(myGame, "8B", "6A") myGame.attemptQueenCastle(not myGame.playerOneTurn) assert king == myGame.board[7][2] assert rook == myGame.board[7][3]
class App(QMainWindow): def __init__(self, startX, startY, width, height): super().__init__() self.title = 'WG' self.setGeometry(startX, startY, width, height) self.setFixedSize(width, height) self.setWindowTitle(self.title) self.game = Game(SERVER_ADDR, SERVER_PORT, PLAYER, self) self.game.start() self.game.show() self.show() def initUI(self): pass
def test_actions(self): game = Game() p = AIPlayer(Game=game) deck = Deck() p.hands.append([deck.draw_card() for i in range(2)]) a, b = p.act(game) self.assertEqual(a, 0) self.assertEqual(b, 20) game.state = Game.STATE_ACT a, b, = p.act(game) self.assertEqual(a, 2) self.assertEqual(b, 0) p.hands[0].append(deck.draw_card()) a, b = p.act(game) self.assertEqual(a, 1) self.assertEqual(b, 0)
def test_rollJail_three(): game = Game(players=[Player()]) game.setBoard([null.Null(), jail.Jail()]) rule = Rules(game, jail=3) rule.roll(0, 6, 6) rule.roll(0, 6, 6) rule.roll(0, 6, 6) assert game.getPlayer(0).getDouble() == 3 assert game.getPlayer(0).getJail() == True assert game.getPlayer(0).getPos() == 1
def start_game(): round = 0 playername = input("Enter A player Name: ") wordlist = ["save", "amused"] game = Game(playername, round, wordlist) print(f"Current Player: {game.set_name()}") t.sleep(1) print(f"Current Round: {game.set_round()}") t.sleep(1) print(f"List: {game.set_list()}")
def create_game(): blue_team, yellow_team = create_teams() field = create_field() referee = create_referee() blue_team_strategy = TestStrategy(field, referee, blue_team, yellow_team) yellow_team_strategy = WorstStrategy(field, referee, yellow_team, blue_team) game = Game(field, referee, blue_team, yellow_team, blue_team_strategy, yellow_team_strategy) return game
def read_starting_game_data(self): correct_data = False while not correct_data: try: rows = input( "Please enter the number of rows of the board: ").strip() if not rows.isdigit(): raise Exception("Invalid character for rows!...") columns = input( "Please enter the number of columns of the board: ").strip( ) if not columns.isdigit(): raise Exception("Invalid character for columns!...") if int(rows) > 8 or int(columns) > 8: raise Exception( "Numbers too big for the size of the board!...") user_sign = input( "Please enter the sign you want to play with (X/O): " ).strip() if user_sign not in ['X', 'O']: raise Exception("Invalid sign entered!...") self._rows = int(rows) self._columns = int(columns) self._user_sign = user_sign correct_data = True except Exception as message: print(str(message) + '\n') if self._user_sign == 'X': self._computer_sign = 'O' else: self._computer_sign = 'X' self._game_board = Game(self._rows, self._columns, self._user_sign, self._computer_sign)
def new_game_sequence(): """ Prompt the user with the input necessary to initialize a game. Number of players, player names, and number of standard 52 card decks. """ print("\n-------------------- Welcome to Blackjack --------------------") n_players = input( "How many people are playing? (Enter an integer value): ") # Prompt the user for valid input (Must be an integer > 0) while not n_players.isdigit() or int(n_players) < 1: print("ERROR: Invalid Input") print( "The number of players must be expressed as a positive integer value " ) n_players = input("How many people will be playing?: ") n_players = int(n_players) # Get the player's names print('Please enter each players name') player_names = [] for i in range(n_players): new_player = input("Player " + str(i + 1) + "\'s name: ") while len(new_player) == 0: print('ERROR: Player name must have at least one character') new_player = input("Player " + str(i + 1) + "\'s name: ") player_names.append(new_player) # Get user input dictating the number of decks to use n_decks = input( "How many decks would you like to use? Standard blackjack uses between 1 and 8 decks: " ) # Prompt the user for valid input (Must be an integer > 0) while not n_decks.isdigit() or int(n_decks) < 1: print("ERROR: Invalid Input") print( "The number of decks must be expressed as a positive integer value" ) n_decks = input("How many decks should be included?: ") n_decks = int(n_decks) print("Starting a new game with", n_players, "players and", n_decks, "decks (" + str(n_decks * 52) + " cards)") print(".\n.\n.\n.\n") # Create a blackjack game with this information. blackjack_game = Game(player_names, n_decks)
def __init__(self, debug=False): Game.__init__(self) self.debug = debug self.config = Config() self.event = Event(self) # graphics must be created first because # some other modules need the HWND or D3DDEVICE self.graphics = Graphics() self.io = IO() self.input = cpp.Input() self.sound = Sound() self.physics = Physics() # order that modules will be ticked in the main loop self.AddModule(self.io) self.AddModule(self.input) self.AddModule(self.sound) self.AddModule(self.physics) self.AddModule(self.graphics) if hasattr(cpp, 'TestModule'): self.test = cpp.TestModule(); self.event.Register(self.QuitEvent)
def test_Pawn_Passant(): """Tests if pawns can do a pawn passant capture """ myGame = Game() def move(x, moveOne, moveTwo): x.board[x.possibleRow[int( moveOne[0])]][x.possibleCol[moveOne[1]]].move( int(moveTwo[0]), moveTwo[1]) pawn = myGame.board[1][0] move(myGame, "2A", "4A") move(myGame, "4A", "5A") move(myGame, "7B", "5B") move(myGame, "5A", "6B") assert pawn == myGame.board[5][1]
def test_knight_move(): """Tests if the knight can move """ myGame = Game() playerOnePieces = set() board = [[None] * 8 for i in range(8)] color = "BLACK" myPiece = Knight(board, color, playerOnePieces, 2, 'A', myGame) playerOnePieces.update({myPiece}) possibleRow = {i: i - 1 for i in range(1, 9)} possibleCol = {chr(i): i - ord('A') for i in range(ord('A'), ord('A') + 8)} moveOne = "2A" moveTwo = "4B" # Now I make a move board[possibleRow[int(moveOne[0])]][possibleCol[moveOne[1]]].move( int(moveTwo[0]), moveTwo[1]) assert board[possibleRow[int( moveTwo[0])]][possibleCol[moveTwo[1]]] == myPiece
def test_Check(): """Tests if you can Check King """ myGame = Game() def move(x, moveOne, moveTwo): x.board[x.possibleRow[int( moveOne[0])]][x.possibleCol[moveOne[1]]].move( int(moveTwo[0]), moveTwo[1]) move(myGame, "7E", "5E") move(myGame, "5E", "4E") move(myGame, "4E", "3E") move(myGame, "2D", "4D") move(myGame, "1D", "3D") move(myGame, "8E", "7E") move(myGame, "3D", "3E") myGame.updateCheckBoard(False) assert myGame.isCheck(False) myGame.updateCheckBoard(True) assert myGame.isCheck(True) == False
import sys import json from Game.Game import Game from Maze.Maze import Maze data_path = "../data/mazes/" policy_path = "./Resolution/data/" + sys.argv[2] + "IterationRes_" + sys.argv[1] with open(policy_path) as file: policy = json.load(file) # print(policy['(0 0 0 0)']) m = Maze() m.load_maze(data_path + sys.argv[1]) g = Game(m) g.play_a_game(policy)
def onLaunchButtonClicked( self ): game = Game(self.levelOptions) game.run() print ( "Launch Button Clicked" )
class Server: """ All of the resolved message comes here. It is the bridge between game logic and websockets communication system """ def __init__(self): self.players = [] self.writer = None self.game = None def set_writer(self, writer): self.writer = writer def join_game(self, message): response = {'type': 'set_username'} if len(self.players) == 4: # Prevent user from connecting response['freeSeats'] = False self.writer.sendMessage(response) self.writer.closeConnection() else: self.players.append(Player(message['user'])) response['user'] = message['user'] response['message'] = "Connected" response['time'] = datetime.datetime.now().strftime('[%H:%M:%S]') response['freeSeats'] = True self.writer.emitMessage(response) if len(self.players) == 4: self.start_game() def start_game(self): self.game = Game(self.players) response = {'type': 'init_score_table'} response['score_table'] = self.game.score_table self.writer.emitMessage(response) self.init_round_game() """ Rozpoczynanie nowego rozdania """ def init_round_game(self): response = {'type': 'start_game'} response['musik'] = 4 response['hide'] = True self.writer.emitMessage(response) response = {'type': 'init_hand'} for player, connection in enumerate(self.writer.socket.connections): response['hand'] = self.players[player].hand self.set_writer(MessageWriter(connection)) self.writer.sendMessage(response) response = {"type": "init_round"} print(self.game.round.CONTRACTS) response['pots'] = self.game.round.CONTRACTS self.writer.sendDirectMessage(response, self.game.current_player) def ask_for_cards(self, message): response = {'type': 'init_hand'} for player, connection in enumerate(self.writer.socket.connections): response['hand'] = self.players[player].hand self.set_writer(MessageWriter(connection)) self.writer.sendMessage(response) def init_pots(self): response = {"type": "init_round"} response["pots"] = tuple(self.game.round.get_contracts()) self.writer.sendDirectMessage(response, self.game.round.current_player) def show_musik(self): response = {"type": "show_musik"} response["musik"] = self.game.deck.create_musik() self.writer.sendDirectMessage(response, self.game.round.current_player) def clear_musik(self): response = {"type": "clear_musik"} self.writer.emitMessage(response) def set_cards_from_musik(self, message): print(message["musik"]) print(f'self.game.current_player') print(self.game.round.current_player) self.clear_musik() self.game.give_cards(message["musik"]) response = {"type": "give_card_to_next_player"} response["nextPlayer"] = self.game.round.musik_current_player self.writer.sendDirectMessage(response, self.game.round.current_player) self.game.round.next_musik_player() def give_away_card(self, message): print(message) self.game.transfer_card(self.game.round.current_player, message["for_player"], message["choosen_card"]) response = {"type": "init_hand"} response["hand"] = self.game.round.players[message["for_player"]].hand self.writer.sendDirectMessage(response, message["for_player"]) if (self.game.round.musik_current_player <= 3): print("Musik current player", self.game.round.musik_current_player) response = {"type": "give_card_to_next_player"} response["nextPlayer"] = self.game.round.musik_current_player self.writer.sendDirectMessage(response, self.game.round.current_player) self.game.round.next_musik_player() else: print("Start a game...") self.init_round() def init_round(self): print("Choosing a card") self.game.round.playing_current_player = self.game.round.current_player response = {"type": "choose_card_to_play"} self.writer.sendDirectMessage(response, self.game.round.playing_current_player) def put_card_on_table(self, message): chosen_card = self.game.round.players[ self.game.round.playing_current_player].get_card_from_hand( message["choosen_card"]) is_finished = self.game.round.add_to_card_table(chosen_card) response = {"type": "show_card"} response["card"] = chosen_card self.writer.emitMessage(response) if is_finished: self.clear_card_table() if self.game.round.is_round_finished(): self.game.score_table.update_score_table( self.game.round.score_table) if self.game.score_table.winner: self.finish_game() self.update_score_table() self.game.init_round() # Nowe rozdanie self.init_round_game() else: self.init_round() return self.game.round.next_playing_player() response = {"type": "choose_card_to_play"} self.writer.sendDirectMessage(response, self.game.round.playing_current_player) def update_score_table(self): response = {"type": "update_score_table"} response["score_table"] = self.game.score_table self.writer.emitMessage(response) def clear_card_table(self): response = {"type": "clear_table"} response["time_to_clear"] = 3000 self.writer.emitMessage(response) def set_pot(self, message): is_pot_finished = self.game.round.set_pot(message["pot_value"]) if not is_pot_finished: self.init_pots() else: self.show_musik() def finish_game(self): response = {"type": "finish_game"} response["winner"] = self.game.score_table.winner self.writer.emitMessage(response) def update_chat(self, message): print(message) now = datetime.datetime.now() message["time"] = now.strftime('[%H:%M:%S]') self.writer.emitMessage(message)
from UI.UI import UI from Game.Game import Game g = Game() ui = UI(g) ui.Start()
class GameWindow: def __init__(self, players): self.window = QtWidgets.QWidget() self.grid_layout = QtWidgets.QGridLayout() self.window.setLayout(self.grid_layout) self.players_names = players self.game = Game(players) self.common_view_items = {} self.players_view = {} self.info_viewer = None def setup_window(self): self.window.setWindowTitle('Farmer Game') self.configure_common_widget() self.configure_player_widget() self.configure_info_widget() self.update_view() self.set_game_callbacks() self.update_info("{} starts the game".format(self.players_names[0])) def configure_common_widget(self): common_widget = QtWidgets.QWidget() self.grid_layout.addWidget(common_widget, 0, 0, 1, 1) inside_grid = QtWidgets.QGridLayout() common_widget.setLayout(inside_grid) self.fill_herd_owner(name='common herd', widget=inside_grid) animals = self.game.get_common_herd() self.common_view_items = { animal: QtWidgets.QLabel(common_widget) for animal in animals.keys() } self.fill_herd_view(herd=self.common_view_items, widget=inside_grid) def configure_player_widget(self): for i, name in enumerate(self.players_names): player_widget = QtWidgets.QWidget() self.grid_layout.addWidget(player_widget, 1, i, 1, 1) inside_grid = QtWidgets.QGridLayout() player_widget.setLayout(inside_grid) self.fill_herd_owner(name=name, widget=inside_grid) animals = self.game.get_player_herd(name) self.players_view.update({ name: {animal: QtWidgets.QLabel() for animal in animals.keys()} }) self.fill_herd_view(herd=self.players_view[name], widget=inside_grid) self.add_action_buttons(widget=inside_grid, name=name) if i > 0: self.players_view[name]['roll'].setEnabled(False) self.players_view[name]['exchange'].setEnabled(False) def configure_info_widget(self): info_widget = QtWidgets.QWidget() self.grid_layout.addWidget(info_widget, 2, 0, 1, len(self.players_names)) self.info_viewer = QtWidgets.QTextBrowser() inside_grid = QtWidgets.QGridLayout() info_widget.setLayout(inside_grid) inside_grid.addWidget(self.info_viewer, 0, 0, 1, 1) self.info_viewer.append('game start') def add_action_buttons(self, widget, name): roll_btn = QtWidgets.QPushButton() roll_btn.setText('Roll') widget.addWidget(roll_btn, 8, 0, 1, 1) exchange_btn = QtWidgets.QPushButton() exchange_btn.setText('Exchange') widget.addWidget(exchange_btn, 8, 1, 1, 1) roll_btn.clicked.connect(self.make_user_roll(name)) exchange_btn.clicked.connect(self.make_user_exchange(name)) self.players_view[name].update({ 'roll': roll_btn, 'exchange': exchange_btn }) def make_user_roll(self, name): def user_roll(): self.game.make_roll(name) return user_roll def make_user_exchange(self, name): def user_exchange(): self.make_exchange(name) return user_exchange @staticmethod def fill_herd_owner(name, widget): lbl = QtWidgets.QLabel() lbl.setText(name) widget.addWidget(lbl, 0, 0, 1, 2) @staticmethod def fill_herd_view(herd, widget): for i, item in enumerate(herd.items()): lbl = QtWidgets.QLabel() lbl.setText(item[0]) widget.addWidget(lbl, i + 1, 0, 1, 1) widget.addWidget(item[1], i + 1, 1, 1, 1) def show_window(self): self.window.show() def update_view(self): animals = self.game.get_common_herd() for animal, value in animals.items(): self.common_view_items[animal].setText(str(value)) for name, view in self.players_view.items(): animals = self.game.get_player_herd(name) for animal, value in animals.items(): view[animal].setText(str(value)) def set_game_callbacks(self): self.game.set_info_callback(self.update_info) self.game.set_end_turn_callback(self.change_active_player) def update_info(self, msg): self.info_viewer.append(msg) def change_active_player(self, current_player_name): index_of_next_player = (self.players_names.index(current_player_name) + 1) % len(self.players_names) for i, name in enumerate(self.players_names): if i == index_of_next_player: self.players_view[name]['roll'].setEnabled(True) self.players_view[name]['exchange'].setEnabled(True) self.update_info("{}'s turn".format(name)) else: self.players_view[name]['roll'].setEnabled(False) self.players_view[name]['exchange'].setEnabled(False) self.update_view() def make_exchange(self, name): exchange_window = ExchangeWindow() exchange_window.set_exchange_callback(self.animals_exchanged) exchange_window.setup_window(name, self.game.get_player_herd(name)) result = exchange_window.show_window() def animals_exchanged(self, name, animals_to_sell, animals_to_buy): self.game.sell_animals(name, animals_to_sell) self.game.buy_animals(name, animals_to_buy) self.update_view()
class Trainer: def __init__(self, player, opponents): self.game = None self.player = player self.opponents = opponents # Collection of AI opponents to train against self.player.automated = False # Override the automatic action behaviour when training self.memory = None self.logger = logging.getLogger() self.actions_selected = 0 self.optimizer_count = 0 self.reference_model = None self._cumulative_loss = 0 self.__create_game_vs_random_opponent() mock_inputs = IOHelpers.create_input_from_game_state( self.game, self.player) input_size = len(mock_inputs) output_size = len(IOHelpers.output_actions) # Define simple NN layers self.model = LinearModule(input_size, HIDDEN_LAYER_SIZE, output_size) self.player.model = self.model self.reference_model = LinearModule(input_size, HIDDEN_LAYER_SIZE, output_size) self.__update_reference_model() self.optimizer = torch.optim.Adam(self.model.parameters(), lr=LEARNING_RATE) def initialise_with_players_model(self): self.model = self.player.model self.__update_reference_model() def __create_game_vs_random_opponent(self): self.game = Game(self.player, random.choice(self.opponents)) def __player_reward(self, prior_game_points, prior_match_points, game_points, match_points): return torch.tensor( REWARD_COST_OF_LIVING + (match_points - prior_match_points) + (game_points - prior_game_points) / self.game.game_point_limit, dtype=torch.float) def __optimize(self, batch_size): if len(self.memory) < batch_size: return # Prepare batch replay transitions = self.memory.sample(batch_size) batch = Transition(*zip(*transitions)) state_batch = torch.cat(batch.state).view(batch_size, -1) action_batch = torch.cat(batch.action).view(batch_size, -1) next_state_batch = torch.cat(batch.next_state).view(batch_size, -1) next_legal_actions_batch = torch.cat(batch.next_legal_actions).view( batch_size, -1) reward_batch = torch.tensor(batch.reward) # Build Q(S,A) map state_action_values = self.model(state_batch).gather(1, action_batch) # Use the reference model to decide future state value (for stability apparently...) next_state_q_values = self.reference_model(next_state_batch) next_state_values = IOHelpers.policy_batch(next_state_q_values, next_legal_actions_batch) expected_state_action_values = (next_state_values * GAMMA) + reward_batch # Compute Huber loss loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1)) self._cumulative_loss += float(loss) # Optimize the model self.optimizer.zero_grad() loss.backward() for param in self.model.parameters(): param.grad.data.clamp_(-1, 1) self.optimizer.step() self.optimizer_count += 1 def start_new_match(self): self.__create_game_vs_random_opponent() self.game.new_match() self.start_new_game() def start_new_game(self): self.game.new_game() # Increment state if action not on NN player self.game.progress_automated_actions() def __update_reference_model(self): self.reference_model.load_state_dict(self.model.state_dict()) def train(self, number_actions=10000, training_time=0, memory_size=1000, batch_size=100, update_reference_model=1000): self.memory = ReplayMemory(memory_size) self.start_new_match() if training_time > 0: now = time.time() while time.time() - now < training_time: self.single_training_loop(batch_size) else: for i in range(number_actions): self.single_training_loop(batch_size) # Every few thousand epochs save out the trained model to disk # (so we can break the program without losing progress) if i % update_reference_model == 0: self.__update_reference_model() logging.info( str(i) + ' actions run. Optimizer count: ' + str(self.optimizer_count) + '. loss: ' + str(self._cumulative_loss / update_reference_model)) self._cumulative_loss = 0 self.player.save_model() self.start_new_match() self.player.automated = True GameHelpers.play_automated_games(self.game, 100) self.player.automated = False self.start_new_match() def select_action(self, state): # Call NN to give me next move sample = random.random() eps_threshold = EPS_END + (EPS_START - EPS_END) * math.exp( -1. * self.actions_selected / EPS_DECAY) self.actions_selected += 1 if sample > eps_threshold: return IOHelpers.get_random_legal_action(self.game, self.player) else: with torch.no_grad(): q_values = self.model(state) return IOHelpers.policy(q_values, self.game, self.player) def single_training_loop(self, batch_size): prior_game_points = self.player.game_points prior_match_points = self.player.match_points state = IOHelpers.create_input_from_game_state(self.game, self.player) action_id, action = self.select_action(state) # Apply action an perform any opponent actions. I.e. continue game until out turn to act self.game.do_next_action(self.player, action) self.game.progress_automated_actions() next_state = IOHelpers.create_input_from_game_state( self.game, self.player) reward = self.__player_reward(prior_game_points, prior_match_points, self.player.game_points, self.player.match_points) next_legal_actions, _ = IOHelpers.get_legal_actions( self.game, self.player) self.memory.push(state, action_id, next_state, next_legal_actions.unsqueeze(0), reward) self.__optimize(batch_size) # Update game state as necessary if self.game.have_match_winner: self.start_new_match() if self.game.have_game_winner: self.start_new_game()
from Board.Board import Board from Game.Game import Game from UI.UI import UI board = Board() game = Game(board) ui = UI(game, board) ui.startUI()
#---------- # Devin Suy #---------- from Game.Game import Game from Algorithm.GameState import GameState from Algorithm.MiniMax import MiniMax from pathlib import Path import pickle # load_path = Path("saved_states") game = Game() # (Pre-processing) Example usage for importing an opening game state # State 0 # game.import_board(["X", " ", " ", " ", " ", " ", " ", " ", " "]) # state_num = 0 # State 1 # game.import_board([" ", "X", " ", " ", " ", " ", " ", " ", " "]) # state_num = 1 # State 2 # game.import_board([" ", " ", "X", " ", " ", " ", " ", " ", " "]) # state_num = 2 # State 3 # game.import_board([" ", " ", " ", "X", " ", " ", " ", " ", " "]) # state_num = 3 # State 4
def main(): g = Game() g.play_game()
class GUI: """ The design ideas we're taken from http://www.papg.com/show?2XMX """ @staticmethod def insert_empty_space(frame, row, column): """ This function is used to insert empty spaces to make the GUI prettier because I hate Tkinter :param frame: the frame in which the empty space is inserted :param row: the row on which we will grid :param column: the column on which we will grid """ empty_label = Label(frame, text="") empty_label.grid(row=row, column=column) @staticmethod def open_database_connection(): connection_string = psycopg2.connect( "host=localhost dbname=postgres user=postgres password=polopolo") current_connector = connection_string.cursor() return connection_string, current_connector @staticmethod def close_database_connection(connection_string, current_connector): connection_string.commit() connection_string.close() current_connector.close() def __init__(self): self.button_cells = [ ] # This will keep all the buttons in form of a matrix self.frame_gameplay = None # This will be the gameplay frame which will be initialised in start_game function self.game = None # This will be a Game type variable, It will be initialised in start_game because we need the rows/colums of the board self.user_score = 0 # This will keep the user score self.cpu_score = 0 # This will keep the cpu score self.row = 0 # This will keep the number of rows of the board self.column = 0 # This will keep the number of columns of the board self.user_symbol = None # This will keep the user symbol self.cpu_symbol = None # This will keep the cpu symbol self.human_turn = None # This will be True if it is human's turn/False otherwise self.root = Tk() self.root.title("Play obstruction!") self.root.geometry("700x400") self.root.iconbitmap( 'C:/Users/georg/OneDrive/Desktop/Informatica/Facultate/a11-912-Danicico-George/obstruction_icon.ico' ) self.frame_game_entry = Frame(self.root, bd=4, highlightbackground="black", height=400, width=700) self.frame_game_entry.pack() # Implementation of the entry frame for the game welcome_label = Label(self.frame_game_entry, text="Play obstruction!") welcome_label.grid(row=0, column=0) GUI.insert_empty_space(self.frame_game_entry, 1, 0) name_label = Label(self.frame_game_entry, text="Your name: ") name_label.grid(row=2, column=0) # The Entry user_name will be needed when the user will press the New Game button in order to make # the connection with the data base self.user_name = Entry(self.frame_game_entry) self.user_name.grid(row=2, column=1) GUI.insert_empty_space(self.frame_game_entry, 3, 0) grid_label = Label(self.frame_game_entry, text="Size of grid: ") grid_label.grid(row=4, column=0) # Implementation for the checkbuttons for the first frame # Important! For the size of the grid only one checkbutton can be checked at a time. # The same goes for the choice if the user wants to start the game. # - This is done by the an auxiliary function, which check the variable for the checkbutton and deselect # deselect its state if necessary self.var1 = IntVar() self.var2 = IntVar() self.var3 = IntVar() self.var4 = IntVar() self.size_one = Checkbutton(self.frame_game_entry, text="6x6", command=lambda x=1: self.check_button(x), variable=self.var1) self.size_one.deselect() self.size_one.grid(row=4, column=1) self.size_two = Checkbutton(self.frame_game_entry, text="7x6", command=lambda x=2: self.check_button(x), variable=self.var2) self.size_two.deselect() self.size_two.grid(row=4, column=2) self.size_three = Checkbutton(self.frame_game_entry, text="7x7", command=lambda x=3: self.check_button(x), variable=self.var3) self.size_three.deselect() self.size_three.grid(row=4, column=3) self.size_four = Checkbutton(self.frame_game_entry, text="8x8", command=lambda x=4: self.check_button(x), variable=self.var4) self.size_four.deselect() self.size_four.grid(row=4, column=4) # -------- GUI.insert_empty_space(self.frame_game_entry, 5, 0) side_label = Label(self.frame_game_entry, text="Do you want to play first? ") side_label.grid(row=6, column=0) # Set the checkboxes for YES/NO # These checkboxes will be needed in order to establish the symbol for the user/computer # Always in the game, 'O' will be the symbol for the one who starts, and 'X' for the other self.var_yes = IntVar() self.var_no = IntVar() self.yes_box = Checkbutton(self.frame_game_entry, text="Yes", command=lambda x=5: self.check_button(x), variable=self.var_yes) self.yes_box.deselect() self.yes_box.grid(row=6, column=1) self.no_box = Checkbutton(self.frame_game_entry, text="No", command=lambda x=6: self.check_button(x), variable=self.var_no) self.no_box.deselect() self.no_box.grid(row=6, column=2) GUI.insert_empty_space(self.frame_game_entry, 7, 0) self.new_game = Button(self.frame_game_entry, text="New Game", command=self.start_game) self.new_game.grid(row=8, column=0) self.root.mainloop() def check_button(self, button): """ This is the auxiliary function we mentioned above. It checks, depending on the button value which correspond to a checkbutton, if it was selected to deselect the others. :param button: a certain value which is unique for every checkbutton """ if button == 1: if int(self.var1.get()) == 1: self.size_two.deselect() self.size_three.deselect() self.size_four.deselect() if button == 2: if int(self.var2.get()) == 1: self.size_one.deselect() self.size_three.deselect() self.size_four.deselect() if button == 3: if int(self.var3.get()) == 1: self.size_two.deselect() self.size_one.deselect() self.size_four.deselect() if button == 4: if int(self.var4.get()) == 1: self.size_two.deselect() self.size_three.deselect() self.size_one.deselect() if button == 5: if int(self.var_yes.get()) == 1: self.no_box.deselect() if button == 6: if int(self.var_no.get()) == 1: self.yes_box.deselect() def get_size_of_grid(self): """ Based on the value of the checkbuttons variables, we will return the row/columns for the board which will be generated in the gameplay Frame :return: row and column of the board """ row = 0 column = 0 if int(self.var1.get()) == 1: row, column = 6, 6 if int(self.var2.get()) == 1: row, column = 7, 6 if int(self.var3.get()) == 1: row, column = 7, 7 if int(self.var4.get()) == 1: row, column = 8, 8 return row, column def get_symbols(self): """ This function will return the symbols for the user and the cpu :return: user symbol and cpu symbol NB! Always 'O' does the first move. """ user_symbol, cpu_symbol = None, None if int(self.var_yes.get()) == 1: user_symbol, cpu_symbol = 'O', 'X' elif int(self.var_no.get()) == 1: user_symbol, cpu_symbol = 'X', 'O' return user_symbol, cpu_symbol def start_game(self): """ Below it is initialised the gameplay frame - We get from the entry frame: - the user name to make the connection with the database - the size of the board - the symbol for user and cpu / who starts first the game """ user_name = self.user_name.get() self.row, self.column = self.get_size_of_grid() self.user_symbol, self.cpu_symbol = self.get_symbols() if user_name == "" or self.row == 0 or self.user_symbol is None: messagebox.showwarning("Warning!", "Please complete all the fields!") return # The connection to the database in order to rtetrieve the data is done. is_registered = False connection, cursor = GUI.open_database_connection() cursor.execute("select * from player") for row in cursor: if row[0] == user_name: is_registered = True self.user_score = int(row[1]) self.cpu_score = int(row[2]) if is_registered is False: cursor.execute("insert into player values (%s, %s, %s)", (user_name, 0, 0)) GUI.close_database_connection(connection, cursor) # After checking the case if the current user hadn't played the game before, it is added to the database self.frame_gameplay = Frame(self.root, bd=4) self.frame_game_entry.pack_forget() self.frame_gameplay.pack() GUI.insert_empty_space(self.frame_gameplay, 0, 10) # The purpose of the below labels is for "design score_label = Label(self.frame_gameplay, text="Score:") score_label.grid(row=0, column=11) label_user = Label(self.frame_gameplay, text=user_name) label_cpu = Label(self.frame_gameplay, text="CPU") label_cpu.grid(row=1, column=12) label_user.grid(row=0, column=12) lbl_user_score = Label(self.frame_gameplay, text=str(self.user_score)) lbl_cpu_score = Label(self.frame_gameplay, text=str(self.cpu_score)) lbl_user_score.grid(row=0, column=13) lbl_cpu_score.grid(row=1, column=13) funny_label = Label(self.frame_gameplay, text="Play Obstruction!") funny_label.grid(row=0, column=0, columnspan=3) GUI.insert_empty_space(self.frame_gameplay, 1, 0) # The true gameplay starts now! self.upload_board() def upload_board(self): # We clear the buttons list to prevent errors when the user will press the 'play again' button # Then, the program generates in form of a matrix with 'row' rows and 'column' colums the buttons self.button_cells.clear() for i in range(self.row): row_cells = [] for j in range(self.column): cell = Button(self.frame_gameplay, bg="white", command=lambda x=i, y=j, z=self.user_symbol: self .prepare_move(x, y, z), padx=12, pady=5) row_cells.append(cell) cell.grid(row=i + 2, column=j) self.button_cells.append(row_cells) GUI.insert_empty_space(self.frame_gameplay, self.row + 2, 0) # the Game variable is created in order to make the moves on the board # because behind the scenes lies a simple matrix with ' ', '-', 'X', 'O' symbols self.game = Game(self.row, self.column, self.user_symbol, self.cpu_symbol) # Because always 'O' starts, we check who starts the game. self.human_turn = False if self.user_symbol == 'X' else True if self.human_turn is False: label_turn = Label(self.frame_gameplay, text="Thinking...") label_turn.grid(row=10, column=0, columnspan=2) self.prepare_move(None, None, self.user_symbol) else: label_turn = Label(self.frame_gameplay, text="Your turn...") label_turn.grid(row=10, column=0, columnspan=2) def prepare_move(self, row, column, symbol): """ This function does a move for the cpu, if it is the cpu's turn Othewise it will check if the clicked cell is a valid one by calling "move" and "gui_move" function :param row: The row of the clicked cell if it is the human turn/ Otherwise None :param column: The column of the clicked cell if it is the human turn/ Otherwise None :param symbol: Always the symbol of the user """ if self.human_turn is True: # It tries to make the move try: self.game.board.move(row, column, symbol) self.game.board.gui_move(row, column, symbol, self.button_cells) self.human_turn = False label_turn = Label(self.frame_gameplay, text="Thinking...") label_turn.grid(row=10, column=0, columnspan=2) except Exception: pass else: cpu_symbol = 'X' if symbol == 'O' else 'O' # it generates a random move for the cpu correct_move = False while not correct_move: try: bot_row, bot_column = self.game.computer_move() self.game.board.gui_move(bot_row, bot_column, cpu_symbol, self.button_cells) correct_move = True label_turn = Label(self.frame_gameplay, text="Your turn...") label_turn.grid(row=10, column=0, columnspan=2) except Exception: pass self.human_turn = True # If there are no empty space/ white buttons it means that the game has ended # And the winner is the user if human turn is False because the last move was done bu the user # Otherwise is the cpu. # And also the score labels are updated correspondingly if self.game.board.number_empty_spaces == 0: if self.human_turn is True: messagebox.showinfo("Sorry...", "You cannot defeat a god!") label_turn = Label(self.frame_gameplay, text="CPU wins...") label_turn.grid(row=10, column=0, columnspan=2) self.cpu_score += 1 else: messagebox.showinfo("Congratulations!", "You just won against a god!") label_turn = Label(self.frame_gameplay, text="You win :)") label_turn.grid(row=10, column=0, columnspan=2) self.user_score += 1 lbl_user_score = Label(self.frame_gameplay, text=str(self.user_score)) lbl_cpu_score = Label(self.frame_gameplay, text=str(self.cpu_score)) lbl_user_score.grid(row=0, column=13) lbl_cpu_score.grid(row=1, column=13) # The database must be with the new scores connection, cursor = GUI.open_database_connection() cursor.execute( "update player set player_score = %s where player_name = %s", (self.user_score, self.user_name.get())) cursor.execute( "update player set computer_score = %s where player_name = %s", (self.cpu_score, self.user_name.get())) GUI.close_database_connection(connection, cursor) # After updating the data base, we close the connection GUI.insert_empty_space(self.frame_gameplay, 11, 0) play_again_button = Button(self.frame_gameplay, text="Play again", command=self.upload_board) play_again_button.grid(row=12, column=0, columnspan=2) else: if self.human_turn is False: self.prepare_move(None, None, symbol)
def __create_game_vs_random_opponent(self): self.game = Game(self.player, random.choice(self.opponents))
from random import randint from Game.Game import Game from Card.OriginalPackage.Unit import * game = Game() whoFirst = randint(0, 1) #test↓ for i in range(10): game.Players[0].RawPile.append(Goblin()) game.Players[0].RawPile.append(ImperialSoldier()) game.Players[0].RawPile.append(Wolf()) game.Players[1].RawPile.append(Goblin()) game.Players[1].RawPile.append(ImperialSoldier()) game.Players[1].RawPile.append(Wolf()) #test↑ while (game.NumberOfBoard < 3): whoSec = (whoFirst + 1) % 2 fstPlayer = game.Players[whoFirst] secPlayer = game.Players[whoSec] while ((not fstPlayer.IsAbstain) or (not secPlayer.IsAbstain)): if (not fstPlayer.IsAbstain): game.PrintScreen(fstPlayer.NO) game.GetAndCROInstructions(fstPlayer.NO) fstPlayer.SettlementOnCourtSkill() game.DeathDetection() game.CalculateCombat() if (not secPlayer.IsAbstain):