def __init__(self, mode='i', filename=None, debug_mode=False): self.game_board = None self.mode = mode self.num_moves = 0 self.lower_player = None self.upper_player = None self.is_game_over = False self.game_over_message = None self.debug_mode = debug_mode if mode is 'f' and filename: try: contents = utils.parseTestCase(filename) except: print("There was an error parsing the input file: " + str(filename) + ". Exiting...") sys.exit() initialPieces = contents['initialPieces'] self.moves = contents['moves'] self.lower_player = player.Player('lower', contents['lowerCaptures']) self.upper_player = player.Player('UPPER', contents['upperCaptures']) self.game_board = game_board.GameBoard(False, initialPieces) elif mode is 'i': self.game_board = game_board.GameBoard() self.lower_player = player.Player('lower') self.upper_player = player.Player('UPPER') else: print("Game mode '" + str(mode) + "' not recognized.") sys.exit() self.lower_player.set_pieces(self.game_board.lower_pieces) self.upper_player.set_pieces(self.game_board.upper_pieces) self.game_board.clear_player_pieces() self.game_board = self.game_board.board self.current_player = self.lower_player
def fight(net1, net2): numGame = 10 win_net1 = 0 win_net2 = 0 mcts = MCTS() for color in [BLACK, WHITE]: for e in range(int(numGame / 2)): print ('[FIGHTING] game number ', e) board = game.GameBoard() board.play(randint(0, 360)) # on part d'une position random while not board.gameEnd(): if board.player_turn == color: moves = mcts.pi(board, net1) else: moves = mcts.pi(board, net2) a = moves.index(max(moves)) board.play(a) print ('end, winner = ', "White" if board.reward == -1 else "Black") board.display_board() if board.player_turn == color: #le nouveau réseau a perdu win_net2 += 1 else: win_net1 += 1 print ('bilan de l\'affrontement: ', win_net1, ' / ', win_net2) return win_net1 / numGame
def main(): boardWidth = 15 boardHeight = 40 shape = None gb = GameBoard("Game area", boardWidth, boardHeight) pile = Pile(boardWidth,boardHeight) play = True while play: gb.clear() if shape is not None: if shape.moveDown(): shape.show() else: pile.merge(shape) pile.clearFullLines() shape = generateRandomShape(int(boardWidth / 2), boardHeight - 2) shape.registerGameBoard(gb) shape.registerPile(pile) else: shape = generateRandomShape(int(boardWidth / 2), boardHeight - 2) shape.registerGameBoard(gb) shape.registerPile(pile) pile.show(gb) gb.update() time.sleep(0.3)
def __init__(self): self.gamer = 1 self.gameBoard = GameBoard() self.pyGame = pygame # initialiser l'interface # utiliser la librairie pygame pygame.init() # charger l'image du plateau de jeu self.board_picture = pygame.image.load( os.path.join(GameView.IMAGE_DIRECTORY, "plateau.png")) # obtenir la taille du plateau de jeu taille_plateau_de_jeu = self.board_picture.get_size() # stocker cette taille self.size = (taille_plateau_de_jeu[0] * 1, taille_plateau_de_jeu[1]) # setter la taille de la fenetre jeu au meme dimension que celle du plateau de jeu (image) self.screen = pygame.display.set_mode(self.size) self.screen.blit(self.board_picture, (0, 0)) pygame.display.flip() # charger l'image du pion jaune self.yellowChip = pygame.image.load( os.path.join(GameView.IMAGE_DIRECTORY, "pion_jaune.png")) # charger l'image du pion rouge self.redChip = pygame.image.load( os.path.join(GameView.IMAGE_DIRECTORY, "pion_rouge.png")) # Police pour le jeu self.font = pygame.font.Font("freesansbold.ttf", 15)
def PlayGameAgainstRandom(weights): board = GameBoard.GameBoard() boardHistory = [(board, BoardEvaluator.EvaluateBoard(board, CellState.CS_AI, weights))] isWon = False isFull = False teamToMove = random.choice([CellState.CS_AI, CellState.CS_OPPONENT]) while not isWon and not isFull: if teamToMove == CellState.CS_AI: nextBoard, otherMoves = MakeMove(board, teamToMove, weights, returnOtherOptions=True) else: nextBoard = board.copy() nextBoard.makeRandomMove(CellState.CS_OPPONENT) otherMoves = [] nextBoardScore = BoardEvaluator.EvaluateBoard(nextBoard, CellState.CS_AI, weights) board = nextBoard boardHistory.append((board, nextBoardScore, otherMoves)) teamToMove = CellState.CS_OPPONENT if teamToMove == CellState.CS_AI else CellState.CS_AI isWon = board.isWon() isFull = board.isFull() return board, boardHistory
def PlayGameAgainstSelf(weights): board = GameBoard.GameBoard() boardHistory = [(board, BoardEvaluator.EvaluateBoard(board, CellState.CS_AI, weights))] isWon = False isFull = False teamToMove = random.choice([CellState.CS_AI, CellState.CS_OPPONENT]) while not isWon and not isFull: nextBoard, otherMoves = MakeMove(board, teamToMove, weights, returnOtherOptions=True) nextBoardScore = BoardEvaluator.EvaluateBoard(nextBoard, CellState.CS_AI, weights) if teamToMove == CellState.CS_OPPONENT: # Need to change the otherMoves scores. They're scores for the CS_OPPONENT team. # Training assumes that these scores are for the CS_AI team. for i in range(len(otherMoves)): otherMoves[i] = (otherMoves[i][0], BoardEvaluator.EvaluateBoard( otherMoves[i][0], CellState.CS_AI, weights)) board = nextBoard boardHistory.append((board, nextBoardScore, otherMoves)) teamToMove = CellState.CS_OPPONENT if teamToMove == CellState.CS_AI else CellState.CS_AI isWon = board.isWon() isFull = board.isFull() return board, boardHistory
def __init__(self): self.gamer = 1 self.gameBoard = GameBoard() self.pyGame = pygame pygame.init() pygame.display.set_caption('tic-tac-toe') self.board_picture = pygame.image.load( os.path.join(GameView.IMAGE_DIRECTORY, "board.png")) taille_plateau_de_jeu = self.board_picture.get_size() print('taille plateau de jeu') print(taille_plateau_de_jeu) print(taille_plateau_de_jeu[0]) print(taille_plateau_de_jeu[1]) self.size = (taille_plateau_de_jeu[0] * 1, taille_plateau_de_jeu[1]) self.screen = pygame.display.set_mode(self.size) self.screen.fill((255, 255, 255)) self.screen.blit(self.board_picture, (0, 0)) pygame.display.flip() self.crossChip = pygame.image.load( os.path.join(GameView.IMAGE_DIRECTORY, "cross.png")) self.roundChip = pygame.image.load( os.path.join(GameView.IMAGE_DIRECTORY, "round.png")) self.font = pygame.font.Font("freesansbold.ttf", 15)
def test_playGame(self): print "play game" gb = GameBoard(3,4) gb.setRandomValue() self.assertEqual(gb.displayBoard(),0) self.assertEqual(gb.displayLive(),0) self.assertEqual(gb.playGame(),0)
def initializeGameBoard(self): card1 = Stack(Card(67, 5)) card2 = Stack(Card(87, 4)) card3 = Stack(Card(75, 7)) card4 = Stack(Card(48, 2)) cards = [card1, card2, card3, card4] self.gameBoard = GameBoard(cards)
def prepareBoard(): """Prepare a new game board.""" global theBoard theBoard = GameBoard.GameBoard( ) # 16x15, secret square at 0,0. This is the default
def playGame(self): gameOver = False # runs rounds; will break when setting bullPoints <= 66 or 0 cards remain while not gameOver: # reset board, create four stacks self.deck = Deck(self.bullPoints) stackStarters = [] for card in self.deck.cards[:self.numStacks]: stackStarters.append(Stack(card)) self.deck.cards = self.deck.cards[self.numStacks:] self.board = GameBoard(stackStarters) # deal cards self.dealToEach() # run all turns in a round for i in range(self.cardsPerPlayer): cardsToPlay = [] for player in self.players: cardsToPlay.append((player, player.chooseCard(self.board))) self.board.placeCards(cardsToPlay) winnerIdx = self.findWinner() if winnerIdx >= 0: gameOver = True self.printScoreBoard() return gameOver
def __init__(self): self.drop_piece = False self.move_dir = 0 self.move_sideways_timer = 0 self.move_timer = 500 self.board = GameBoard.GameBoard() self.board.spawn_piece() self.level = 1 self.lines_left = 4 self.score = 0 self.score_to_update = 0 self.instructions = [] self.instructions.append("Left/Right: Move sideways") self.instructions.append("Down: Increase drop speed") self.instructions.append("Up: Rotate Clockwise") self.instructions.append("Z: Rotate Counterclockwise") self.instructions.append("Space: Instant Drop") self.instructions.append("Shift: Store Current Piece") self.instructions.append("Escape: Exit to Menu") self.stored_piece = None Screen.__init__(self)
def run(state, numGhosts, intelligenceLevel, IDS, verbose): # Run with Q Table if not IDS: board = B.GameBoard(state) p = P.PacMan(board.pacManSpawnPt) ghosts = [] for i in range(numGhosts): ghosts.append(G.Ghost(board.ghostSpawnPt)) if verbose: print("\tRunning PacMan with Q Table\n\tTraining Q Table...") Q, scores = p.trainQ(board, 30, 0.5, 0.7, ghosts, intelligenceLevel) if verbose: print("\tDone!\n\tRunning game...") results = PG.startGame(board, p, ghosts, Q, intelligenceLevel, False, False) if verbose: print("\tDone!") ghostInfo = "[" + str(numGhosts) + ", " + str(intelligenceLevel) + "]" print("\t", ghostInfo, "Q Table Results:\t\tTurns:", results[0], "\tScore:", results[1], "\tLives left:", results[2], "\tDots left:", results[3]) # Run with Pacman IDS else: avgResults = [0, 0, 0, 0, 0] if verbose: print("\tRunning PacMan with IDS 30 times") for i in range(30): board = B.GameBoard(state) p = P.PacMan(board.pacManSpawnPt) ghosts = [] for j in range(numGhosts): ghosts.append(G.Ghost(board.ghostSpawnPt)) Q = [] results = PG.startGame(board, p, ghosts, Q, intelligenceLevel, True, False) if verbose: print("\tIDS", (i + 1), "results:\t\tTurns:", results[0], "\tScore:", results[1], "\tLives left:", results[2], "\tMoves explored:", results[3], "\tDots left:", results[4]) for j in range(len(results)): avgResults[j] += results[j] if verbose: print("\tDone!") for i in range(len(avgResults)): avgResults[i] = int(avgResults[i] / 30) ghostInfo = "[" + str(numGhosts) + ", " + str(intelligenceLevel) + "]" print("\t", ghostInfo, "IDS 30-average results:\t\tTurns:", avgResults[0], "\tScore:", avgResults[1], "\tLives left:", avgResults[2], "\tDots left:", avgResults[3])
def test_downward_diag_win(self): b = [["R", None, None, None, None], ["Y", "R", None, None, None], ["Y", "Y", "R", None, None], ["Y", "Y", "Y", "R", None]] gb = GameBoard.GameBoard() gb.board = b assert gb.downward_diag_win(0, 0) is True assert gb.downward_diag_win(1, 1) is True assert gb.downward_diag_win(2, 2) is True assert gb.downward_diag_win(3, 3) is True
def __init__(self, player_one, player_two): self.winner = None self.next_turn = PLAYER_ONE self.is_running = True self.choose_board = True self.last_board = None self.players = [Player.Player(*player_one), Player.Player(*player_two)] self.game_board = GameBoard.GameBoard()
def __init__(self, game_file, players=None): self.board = GameBoard.GameBoard(game_file) self.playerList = [] self.chance = Deck.Deck("Chance.txt") self.community = Deck.Deck("Community_Chest.txt") if players: for player in range(players): self.__add_players(player)
def ready(self): self.isFocused = True self.currScore = 0 self.bindscore.set(self.currScore) self.controller.info["username"] = None self.controller.info["score"] = self.currScore self.play_frame.focus_set() self.game = GameBoard(self) self.refresh()
def __init__(self, createRandomPlayer=False): self.numOfPlayers = 4 self.board = GameBoard(self.numOfPlayers) if (createRandomPlayer): self.players = self.replacePlayersWithRandomPlayer() else: self.players = self.createPlayers(self.board) self.currentPlayerId = 1 # returns random player
def test_upward_diag_win(self): b = [["Y", None, None, "Y", None], ["Y", "R", "Y", "R", None], ["Y", "Y", "R", "R", None], ["Y", "Y", "Y", "R", None]] gb = GameBoard.GameBoard() gb.board = b gb.turn = "Y" assert gb.upward_diag_win(3, 0) is True assert gb.upward_diag_win(2, 1) is True assert gb.upward_diag_win(1, 2) is True assert gb.upward_diag_win(0, 3) is True
def __init__(self, name="Player", GA=None): self.name = name self.game_board = GameBoard() self.total_score = 0 self.weights = GA self.current_piece = None self.round_counter = 0 self.rows_cleared = 0 self.lines_sent = 0 self.game_over = False
def start_game(): """ The main method to start the game :return: Game Board """ print("Starting Tic Tac Toe Game") mode_user_input = collect_mode() char_user_input = collect_char() return GameBoard.GameBoard(mode_user_input, char_user_input)
def _init_server(self): """ 如果是房主模式,初始化服务器再初始化客户端(加入游戏)。 """ player_number = self.input_frame.get() # type: int self.game_board = GameBoard.GameBoard(player_number) self._server_addr = self.game_board.get_server_address() self.game_board.start() messagebox.showinfo( message= f'请将下列地址告诉其他玩家。\n{self._server_addr[0]}:{self._server_addr[1]}') self._join_game()
def __init__(self, player1, player2, gridSize=3): self.gameBoard = GameBoard.GameBoard(gridSize) self.playerOne = player1 self.playerTwo = player2 self.gridSize = gridSize self.maxTurn = int(gridSize) * int(gridSize) self.currentTurn = 0 self.order = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ] self.currentLetter = 0
def prepareBoard(): """Make a simple gameboard for testing purposes""" global theBoard theBoard = GameBoard.GameBoard() # 16x15, secret square at 0,0. This is the default listOne = [1, 1, 100] listTwo = [1, 2, 100] listThree = [1, 3, 100] theBoard.setList(5, 5, listOne) theBoard.setList(6, 6, listTwo) theBoard.setList(7, 7, listThree)
def prepareBoard(): """Make a simple gameboard for testing purposes""" global theBoard theBoard = GameBoard.GameBoard(16, 15, 13, 12) # Magic square in bottom # right for no reason listOne = [1, 1, 100] listTwo = [1, 2, 100] listThree = [2, 3, 100] theBoard.setList(1, 0, listOne) theBoard.setList(2, 1, listTwo) theBoard.setList(3, 2, listThree)
def main(): op1 = OpponentClass.OpponentClass() op2 = OpponentClass.OpponentClass() op3 = OpponentClass.OpponentClass() oppo_list = [op1, op2, op3] round_wind = input('Please input the round wind') self_wind = input('Please input the self wind') dora_indic = input('Please input the dora indicator') board = GameBoard.GameBoard(oppo_list, dora_indic, round_wind, self_wind) agent = MahjongAgent.MahjongAgent(board) while (True): for i in range(14): stdin = int(input('Please input your hand' + '\n')) agent.hand_add(stdin) round_discard = [] opponent1_discard = int( input('Please input the opponent 1 dicard' + '\n')) board.opponent_getter(1).discard_add(opponent1_discard) round_discard.append(opponent1_discard) opponent2_discard = int( input('Please input the opponent 2 discard' + '\n')) board.opponent_getter(2).discard_add(opponent2_discard) round_discard.append(opponent2_discard) opponent3_discard = int( input('Please input the opponent 3 discard' + '\n')) board.opponent_getter(3).discard_add(opponent3_discard) round_discard.append(opponent3_discard) for tile in round_discard: agent.tile_count_update(tile) agent_discard = agent.to_discard_tile() print('Round 1: ') print('Your hand: ', agent.hand_getter()) print('opponent1_discard: ', board.opponent_getter(1).discard_getter(), '\n') print('opponent2_discard: ', board.opponent_getter(2).discard_getter(), '\n') print('opponent3_discard: ', board.opponent_getter(3).discard_getter(), '\n') print('agent_discard: ', agent_discard, '\n')
def __noColor(self, players, gridSize): self.__players = players self.__gridSize = gridSize self.__currentPlayers = players self.__listInWiningOrder = [] try: self.__gameBoard = GameBoard.GameBoard(self.__gridSize) except ValueError as ve: print(ve) for x in players: try: self.__gameBoard.addPlayer(x) except LookupError as le: print(le)
def main(): setup() cls() print("Welcome!") restart = True while restart: while "Asking for map file": board_file = input( "Please enter the name of the board you want to load: ") try: game_board = GameBoard(board_file) break except ValueError as ve: print(str(ve)) except FileNotFoundError as fnf: print("The file %s does not exist!" % fnf.filename) print(str(game_board)) while not game_board.game_over: player_input = get_player_input() cls() update(game_board, player_input) draw(game_board) # Fancy way of writing "while True". while "Asking for re-match": cls() end_message = " ! ! ! YOU WON ! ! !" if game_board.win else " - - - YOU LOST - - -" print(end_message) print("************************") print("* . . . . . . . . . . .*") print("*. .________ [THE END] *") print("* ./[][][][]\\. . . . . *") print("*. \\________/=<<<. . . *") print("* . . . . . . . . . . .*") print("************************") print(end_message) again = input("Play again? (Y/N) ").upper() if again == "N": restart = False print("Goodbye!") break if again == "Y": break else: print("Please type either Y or N.")
def play(self): """ Launchs the game :return: """ self.widget.stackedWidget.setCurrentWidget(self.widget.Game) self.gameBoard = GameBoard.GameBoard(self.player2, self.player1, self.sizeImage, self.nbRows, self.widget) self.gameBoard.setParent(self.widget.boxGame) # Si on enlève le + 1, la taille est trop petite self.widget.boxGame.resize((self.nbRows + 1)*self.sizeImage, (self.nbRows + 1)*self.sizeImage) position = int((self.widthWidget - self.nbRows*self.sizeImage)/2) self.widget.boxGame.move(position, int(self.heightMarge/2)) self.gameBoard.show() QtCore.QTimer.singleShot(500, self.gameBoard.playTurn)
def __init__(self, players, gridSize, colors=None): if (colors != None): self.__players = players self.__gridSize = gridSize self.__currentPlayers = players self.__listInWiningOrder = [] try: self.__gameBoard = GameBoard.GameBoard(self.__gridSize) except ValueError as ve: print(ve) for x in range(0, players.__len__()): try: self.__gameBoard.addPlayer(players[x], colors[x]) except LookupError as le: print(le) else: self.__noColor(players, gridSize)