def takeMove(self, move): legalMovesList.takeTileByIndex(move, self.marker) self.bestMoveX = legalMovesList.prevX self.bestMoveY = legalMovesList.prevY if isDebugMode == True: if freeTiles[self.bestMoveX][self.bestMoveY] == 0: #print "Tile [%d,%d]" % (legalMovesList.prevX, legalMovesList.prevY) #print i freeTiles[self.bestMoveX][self.bestMoveY] = self.marker else: print "Fail! Tile [%d,%d] is already taken!" % (legalMovesList.prevX, legalMovesList.prevY) #Log the move into the gameboard GameBoard.takeTile(self.bestMoveX, self.bestMoveY, self.marker)
def __init__(self, parent = None): """ Constructor """ QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.mousePosition = [0, 0] self.setupUi(self) self.show() self.glFrame.setTitle( " " ) self.board = GameBoard(MainWindow, self) self.vLayout.addWidget(self.board) self.gameLog.keyPressEvent = self.test self.keyPressEvent = self.test self.board.wheelEvent = self.zoomMap self.board.mouseMoveEvent = self.moveMap self.board.mouseDoubleClickEvent = self.doubleClickMap self.board.mousePressEvent = self.clickMap self.board.mouseReleaseEvent = self.stopMoving self.lastX = False self.lastY = False self.mode = "team" self.myActiveClix = False self.theirActiveClix = False self.chooseMapDialog = None self.activeObject = False self.myDial.setMouseTracking(True) self.currentFigure.setMouseTracking(True) self.currentSet = None self.sets = {} setlistFile = os.path.join(sys.path[0], 'sets', 'setlist') if os.path.exists( setlistFile ): sets = open(setlistFile).readlines() for setname in sets: set, filesize, setname = setname.split(":") if os.path.getsize( set ) != filesize: self.generateSetList( setlistFile ) break else: self.sets[setname] = set else: self.generateSetList( setlistFile ) self.populateSetsDropdown() self.currentSelectedFigure = None self.myDial.mouseMoveEvent = self.hoverMyDial self.currentFigure.mouseMoveEvent = self.hoverCurrentFigure
def playGame(): gameBoard= GameBoard() firstMove = getFirstMove() print "\n" + "\n" print "Let's play a game of tic-tac-toe!" print "We randomly chose who gets to go first, and %s goes first" % firstMove ##if the first move is the player get their move then we can start regular play ##if the first move is the computer determine the best move then start regular play ##Winner is used to keep track of win/lose/tie winner = False if firstMove == "you": while winner == False: ##check for a winner game_over = gameBoard.check_for_winner() if ( game_over != False ): ##Print the winner out printWinner(game_over) winner = True else: ##We need to make sure the game isnt over before any more is made if ( gameBoard.check_for_winner() == False ): gameBoard.draw_board() getPlayersMove(gameBoard) if ( gameBoard.check_for_winner() == False ): cpuMove(gameBoard) else: while winner == False: ##check for a winner game_over = gameBoard.check_for_winner() ##TODO check for a tie if ( game_over != False ): ##Print the winner out printWinner(game_over) winner = True else: ##We need to make sure the game isnt over before any more is made if ( gameBoard.check_for_winner() == False ): cpuMove(gameBoard) if ( gameBoard.check_for_winner() == False ): getPlayersMove(gameBoard)
def __init__(self, ui, MainWindow): self.mousePosition = [0, 0] self.MainWindow = MainWindow self.ui = ui ui.glFrame.setTitle( " " ) self.board = GameBoard(MainWindow, ui) ui.vLayout.addWidget(self.board) ui.gameLog.keyPressEvent = self.test MainWindow.keyPressEvent = self.test self.board.wheelEvent = self.zoomMap self.board.mouseMoveEvent = self.moveMap self.board.mouseDoubleClickEvent = self.doubleClickMap self.board.mousePressEvent = self.clickMap self.board.mouseReleaseEvent = self.stopMoving self.lastX = False self.lastY = False ui.cmdHeal.mousePressEvent = self.healClix ui.cmdDamage.mousePressEvent = self.damageClix ui.cmdTokenRed.mousePressEvent = self.tokenRed ui.cmdTokenBlue.mousePressEvent = self.tokenBlue ui.rollOne.mousePressEvent = self.rollOne ui.rollTwo.mousePressEvent = self.rollTwo ui.cmdBarrier.mousePressEvent = self.barrier ui.cmdSmokeCloud.mousePressEvent = self.smokeCloud ui.cmdDebris.mousePressEvent = self.debris ui.cmdSpecial.mousePressEvent = self.special ui.cmdLOF.mousePressEvent = self.changeLOF ui.cmdObj.mousePressEvent = self.changeObjectMode self.myActiveClix = False self.theirActiveClix = False self.activeObject = False ui.myDial.setMouseTracking(True) ui.myDial.mouseMoveEvent = self.hoverMyDial
class GameView: IMAGE_DIRECTORY = "images" 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 determine_column(self, x): column = x + 8.75 column /= 97 if column < GameBoard.BOARD_WIDTH: return int(column) else: return GameBoard.BOARD_WIDTH - 1 def determine_line(self, y): line = y + 8.4 line /= 97 if line < GameBoard.BOARD_LENGTH: return int(line) else: return GameBoard.BOARD_LENGTH - 1 def render(self): self.screen.fill((255, 255, 255)) self.screen.blit(self.board_picture, (0, 0)) game_board_game_state = self.gameBoard.board self.gameBoard.display() for i in range(len(game_board_game_state)): for j in range(len(game_board_game_state[i])): if game_board_game_state[i][j] == GameBoard.ROUND_CHIP: self.screen.blit(self.roundChip, (8.75 + 97 * j, 8.4 + 97.5 * i)) pygame.display.flip() if game_board_game_state[i][j] == GameBoard.CROSS_CHIP: self.screen.blit(self.crossChip, (8.75 + 97 * j, 8.4 + 97.5 * i + 1)) pygame.display.flip()
def train_phase1(self, num_boards, num_epochs): # The first phase of training - this will be done entirely inside the class. # Requires that we first create the network. # Generate num_boards random, but valid, boards, along with targets print("Generating boards...") training_boards_list = [] boards0 = [] boards1 = [] boards2 = [] boards3 = [] boards4 = [] boards5 = [] while len(boards0) < num_boards / 6: num_moves = random.randint(2,7) board = GameBoard.GameBoard() for _ in range(num_moves): try: board.make_move(random.randint(0,6), suppress_won_message=True) except: pass if board.won or board.tied or board.count < 2: continue boards0.append(board) while len(boards1) < num_boards / 6: num_moves = random.randint(8,14) board = GameBoard.GameBoard() for _ in range(num_moves): try: board.make_move(random.randint(0,6), suppress_won_message=True) except: pass if board.won or board.tied or board.count < 2: continue boards1.append(board) while len(boards2) < num_boards / 6: num_moves = random.randint(15,21) board = GameBoard.GameBoard() for _ in range(num_moves): try: board.make_move(random.randint(0,6), suppress_won_message=True) except: pass if board.won or board.tied or board.count < 2: continue boards2.append(board) while len(boards3) < num_boards / 6: num_moves = random.randint(22,28) board = GameBoard.GameBoard() for _ in range(num_moves): try: board.make_move(random.randint(0,6), suppress_won_message=True) except: pass if board.won or board.tied or board.count < 2: continue boards3.append(board) while len(boards4) < num_boards / 6: num_moves = random.randint(29, 35) board = GameBoard.GameBoard() for _ in range(num_moves): try: board.make_move(random.randint(0,6), suppress_won_message=True) except: pass if board.won or board.tied or board.count < 15: continue boards4.append(board) while len(boards5) < num_boards / 6: num_moves = random.randint(36,42) board = GameBoard.GameBoard() for _ in range(num_moves): try: board.make_move(random.randint(0,6), suppress_won_message=True) except: pass if board.won or board.tied or board.count < 29: continue boards5.append(board) training_boards_list = boards0 + boards1 + boards2 + boards3 + boards4 + boards5 print("Generated boards...") board_vector_list = [] targets_list = [] print("Creating data...") for training_board in training_boards_list: next_boards = self.get_next_boards(training_board) + self.get_next_boards(training_board, True) board_vector = self.board_to_vector(training_board, training_board.whoseTurn() - 1) board_vector_list.append(board_vector) targets = [] for i in range(14): if next_boards[i] is None: targets.append(0) continue pieces_in_a_row = self.get_board_pieces_in_a_row(next_boards[i]) red = pieces_in_a_row[0] black = pieces_in_a_row[1] priority = 0.99 if i <= 6: color = training_board.whoseTurn() priority = 1 else: color = (training_board.whoseTurn() - 1.5) * -1 + 1.5 if color == 1: # targets.append(((red/black - 0.25) / 3.75) * priority) targets.append((red[0] * 4 + red[1] + 9 + red[2] * 16) / (black[0] * 4 + black[1] + 9 + black[2] * 16)) elif color == 2: # targets.append(((black/red - 0.25) / 3.75) * priority) targets.append((black[0] * 4 + black[1] + 9 + black[2] * 16) / (red[0] * 4 + red[1] + 9 + red[2] * 16)) else: raise Exception("You got a color that doesn't exist!") n_targets = [] for i in range(14): n_targets.append(targets[i] / np.sum(targets)) targets_list.append(n_targets) # for i in range(len(training_boards_list)): # training_boards_list[i].print() # print(training_boards_list[i].whoseTurn()) # print(targets_list[i]) # formatted_prediction = [] # for j in range(7): # formatted_prediction.append((targets_list[i][j] + targets_list[i][j + 7]) / 2) # print(formatted_prediction) print("Created data...") x_train, x_test, y_train, y_test = train_test_split(board_vector_list, targets_list, test_size=0.3) plot_data = self.net.fit(x_train, y_train, x_test, y_test, num_epochs=num_epochs) plt.plot(plot_data[0], plot_data[1], label="Train") plt.plot(plot_data[0], plot_data[2], label="Test") plt.legend() plt.show()
from GameBoard import * board = GameBoard() board.addRoad(4,12,0) corner1 = board.corners[12] corner1.addBuilding(0,"settlement") board.addRoad(12,13,0) board.addRoad(13,23,0) board.addRoad(23,24,0) board.addRoad(24,25,0) board.addRoad(24,35,0) board.addRoad(35,36,0) board.addRoad(35,34,0) corner2 = board.corners[34] corner2.addBuilding(0,"settlement") board.addRoad(34,33,0) board.addRoad(33,32,1) board.addRoad(32,31,1) board.addRoad(31,20,1) board.addRoad(20,21,1) board.addRoad(21,22,1) board.addRoad(22,23,1) corner3 = board.corners[23] corner3.addBuilding(1,"settlement") board.getLongestRoad() print len(board.edges)
def loadSave(): load_dict = pickle.load(open("save.p", "rb")) # --- Player --- # # First reset old position to -> " " GameBoard.theBoard[PlayerClass.char.position] = " " # Now the position is updated PlayerClass.char.position = load_dict['player_pos'] # Now place the player GameBoard.theBoard[PlayerClass.char.position] = PlayerClass.char.name PlayerClass.char.inventory = load_dict['player_inventory'] PlayerClass.char.equipped_items = load_dict['player_eq'] PlayerClass.char.hp = load_dict['player_hp'] PlayerClass.char.gold = load_dict['player_gold'] PlayerClass.char.xp = load_dict['player_xp'] PlayerClass.char.lvl = load_dict['player_lvl'] PlayerClass.char.defence = load_dict['player_def'] PlayerClass.char.strength = load_dict['player_str'] # --- NPC --- # # Set Found NPCClass.the_trader.found = load_dict['trader_found'] # Now the position is updated NPCClass.the_trader.position = load_dict['trader_pos'] NPCClass.the_healer.found = load_dict['healer_found'] NPCClass.the_healer.position = load_dict['healer_pos'] # --- Monsters --- # MonsterClass.army_of_orcs = [] # Separate all monsters monster1 = load_dict['monster1'] monster2 = load_dict['monster2'] monster3 = load_dict['monster3'] monster4 = load_dict['monster4'] monster5 = load_dict['monster5'] monster6 = load_dict['monster6'] monster7 = load_dict['monster7'] monster8 = load_dict['monster8'] monster9 = load_dict['monster9'] new_monster1 = MonsterClass.Monster("Bald Orc", "m", monster1.position, " ", monster1.found, monster1.hp, 32, 2, monster1.defeated, MonsterClass.gen_orc_gold(), 49) new_monster2 = MonsterClass.Monster("Bald Orc", "m", monster2.position, " ", monster2.found, monster2.hp, 32, 2, monster1.defeated, MonsterClass.gen_orc_gold(), 49) new_monster3 = MonsterClass.Monster("Bald Orc", "m", monster3.position, " ", monster3.found, monster3.hp, 32, 2, monster1.defeated, MonsterClass.gen_orc_gold(), 49) new_monster4 = MonsterClass.Monster("Bald Orc", "m", monster4.position, " ", monster4.found, monster4.hp, 32, 2, monster1.defeated, MonsterClass.gen_orc_gold(), 49) new_monster5 = MonsterClass.Monster("Bald Orc", "m", monster5.position, " ", monster5.found, monster5.hp, 32, 2, monster1.defeated, MonsterClass.gen_orc_gold(), 49) new_monster6 = MonsterClass.Monster("Bald Orc", "m", monster6.position, " ", monster6.found, monster6.hp, 32, 2, monster1.defeated, MonsterClass.gen_orc_gold(), 49) new_monster7 = MonsterClass.Monster("Bald Orc", "m", monster7.position, " ", monster7.found, monster7.hp, 32, 2, monster1.defeated, MonsterClass.gen_orc_gold(), 49) new_monster8 = MonsterClass.Monster("Bald Orc", "m", monster8.position, " ", monster8.found, monster8.hp, 32, 2, monster1.defeated, MonsterClass.gen_orc_gold(), 49) new_monster9 = MonsterClass.Monster("Bald Orc", "m", monster9.position, " ", monster9.found, monster9.hp, 32, 2, monster1.defeated, MonsterClass.gen_orc_gold(), 49) MonsterClass.army_of_orcs.append(new_monster1) MonsterClass.army_of_orcs.append(new_monster2) MonsterClass.army_of_orcs.append(new_monster3) MonsterClass.army_of_orcs.append(new_monster4) MonsterClass.army_of_orcs.append(new_monster5) MonsterClass.army_of_orcs.append(new_monster6) MonsterClass.army_of_orcs.append(new_monster7) MonsterClass.army_of_orcs.append(new_monster8) MonsterClass.army_of_orcs.append(new_monster9) # Place saved monsters on the board for monster in MonsterClass.army_of_orcs: if monster.found: GameBoard.theBoard[monster.position] = monster.symbol else: GameBoard.theBoard[monster.position] = monster.hidden # --- Items --- # # First reset on_board_items ItemClass.on_board_items = [] GameBoard.theBoard[ItemClass.leather_cap.position] = " " # If item is already found, pass, else add the item to on_board_items, replace on the board and make hidden for i in load_dict['board_items']: if i.found: pass else: ItemClass.on_board_items.append(i) GameBoard.theBoard[i.position] = i.hidden checkEncounters() # Finally draw the board GameBoard.draw_board(GameBoard.theBoard)
#Module imports required. from GameBoard import * import socket #Define our game. These values need to be read in from the byte stream. Game = GameBoard("X", "magenta", "O", "orange") #Define constants to connect to server. #HOST = "143.60.76.32" HOST = "127.0.0.1" PORT = 61001 #Define the client socket. ClientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #def read_packet: Function reads in one packet sent from the server. def read_packet(): receivedData = "" byte = "" #Iterate byte by byte to determine if we have reached the delimiter. while byte != "?": receivedData = receivedData + byte byte = ClientSocket.recv(1).decode() #return our data from server. return receivedData
def _max(self, previous_board, board, previous_action, depth, alpha, beta): # check history table encoded_board = self._encode_state(board) check = self._check_encoded_state(encoded_board, self.piece_type) if check: return check # check game result """ if game_board.game_end(previous_board, board, previous_action): result = game_board.judge_winner(board) if result == self.piece_type: # win return float("inf"), None elif result == 0: # will not happen return DRAW_REWARD, None else: # lose return float("-inf"), None """ valid_moves = self._get_valid_moves(previous_board, board, self.piece_type) if not valid_moves: # TODO: handle no valid move, or pass return 0, "PASS" # random.shuffle(valid_moves) if depth < 1: # TODO: replace with evaluation function and best move score = self._evaluate_board(previous_board, board, self.piece_type, debug=self.debug) if self.debug: print(" in max end") print(self._visualize_evaluation(board, self.piece_type)) print(" give min with score {}".format(score)) return score, None best_value, action = float("-inf"), None chosen_board = None for i, j in valid_moves: new_previous_board = deepcopy(board) # impossible to be unsuccessful new_board, success = GameBoard.place_chess(previous_board, board, i, j, self.piece_type) value, a = self._min(new_previous_board, new_board, previous_action, depth - 1, alpha, beta) if value > best_value or action is None: # first action or find bigger value best_value, action = value, (i, j) # self.history[self._encode_state(board)] = (best_value, action) chosen_board = new_board # best_value = max(value, best_value) alpha = max(alpha, best_value) if beta <= alpha: break if self.debug: print(" in max") print(self._visualize_evaluation(board, self.piece_type)) print(" give min {} with score {}".format(action, best_value)) # write to history dictionary self._store_encoded_state(encoded_board, self.piece_type, best_value, action) return best_value, action
#!/usr/bin/python #-*- coding: utf-8 -*- from __future__ import print_function import GameBoard import GreedyAgent import SmartAgent import IAgent import sys import JAgent import GeniusAgent #import FAgent # 建立 GameBoard gb = GameBoard.GameBoard() #gb.debug = True print("Please enter loop:(1~100):") #loop = 1000 loop = sys.stdin.readline() log = open("game.log", "w") if int(loop) > 0: # 建立 Agent a1 = GreedyAgent.Agent('A', gb) a2 = SmartAgent.Agent('S', gb) a3 = GeniusAgent.Agent('G', gb) a4 = JAgent.JAgent('J', gb) for i in range(int(loop)): print("\t[Info] Round {0}:".format(i + 1)) gb.play() if gb.win_agent:
def test_initGameBoard(self): #initialize GameBaord gb = GameBoard(1,1) self.assertEqual(gb.board[0,0], 0)
def reset_game(self): self.board = GameBoard()
def test_numLive(self): #calculate the number of lives from the neibor gb = GameBoard(1,1) self.assertEqual(gb.numLive(0,0), 0)
def test_setValue(self): gb = GameBoard(3,4) gb.setValue(1,2,1) self.assertEqual(gb.board[1,2], 1) self.assertEqual(gb.board[1,1], 0)
def test_setRandomValue(self): print "set Random Value for GameBaord" gb = GameBoard(3,4) self.assertEqual(gb.setRandomValue(),0) self.assertEqual(gb.displayBoard(),0)
def _max(self, previous_board, board, previous_action, depth, alpha, beta): # check history table if self._encode_state(board) in self.history: return self.history[self._encode_state(board)] # check game result """ if game_board.game_end(previous_board, board, previous_action): result = game_board.judge_winner(board) if result == self.piece_type: # win return float("inf"), None elif result == 0: # will not happen return DRAW_REWARD, None else: # lose return float("-inf"), None """ valid_moves = [] for i in range(5): for j in range(5): if GameBoard.valid_place_check(previous_board, board, i, j, self.piece_type, test_check=True): valid_moves.append((i, j)) if not valid_moves: # TODO: handle no valid move, or pass return 0, "PASS" # random.shuffle(valid_moves) if depth < 1: # TODO: replace with evaluation function and best move # print(board) # print("max end of depth") best_value, action = float("-inf"), None for move in valid_moves: value = self._evaluate(board, self.piece_type, move) if value > best_value: best_value, action = value, move self.history[self._encode_state(board)] = (best_value, action) return best_value, action best_value, action = float("-inf"), None for i, j in valid_moves: new_previous_board = deepcopy(board) # impossible to be unsuccessful new_board, success = GameBoard.place_chess(previous_board, board, i, j, self.piece_type) value, a = self._min(new_previous_board, new_board, previous_action, depth - 1, alpha, beta) if value > best_value or action is None: # first action or find bigger value best_value, action = value, (i, j) self.history[self._encode_state(board)] = (best_value, action) # best_value = max(value, best_value) alpha = max(alpha, best_value) if beta <= alpha: break return best_value, action
def main_pygame(file_name): pygame.init() #print(" x/c/v = move/wait/cancel, wasd=camera movement, '+/-' control the volume of the background music") myfont = pygame.font.Font("press-start-2p/PressStart2P.ttf", 11) worldMap = tiledtmxloader.tmxreader.TileMapParser().parse_decode(file_name) assert worldMap.orientation == "orthogonal" screen_width = min(1024, worldMap.pixel_width) screen_height = min(768, worldMap.pixel_height) screen = pygame.display.set_mode((screen_width, screen_height)) Characters = pygame.sprite.RenderUpdates() GameBoard = Board(worldMap, Characters, tileSize, screen) pygame.display.set_caption("Ancient Juan") #UI sprite container menuItems = ["Attack", "Move" ,"Wait", "Cancel"]#thse will be changed later myMenu = Menu("Action:", menuItems, myfont, 50, 150, 200, 200) #CHARACTERS! DeathImageSet=sprites.load_sliced_sprites(64,64,'images/skeleton/skeleton_death.png') KnightDeathImageSet = sprites.load_sliced_sprites(64, 64, 'images/knight/knight_death.png') KnightImageSet = sprites.load_sliced_sprites(64, 64, 'images/knight/knight_walk.png') KnightAttackImageSet = sprites.load_sliced_sprites(64, 64, 'images/knight/knight_attack.png') KnightSprite = Actor((14-.5)*tileSize, (4-1)*tileSize, KnightImageSet[0], KnightImageSet[1], KnightImageSet[2], KnightImageSet[3], \ KnightDeathImageSet[0], KnightAttackImageSet[0], KnightAttackImageSet[1], KnightAttackImageSet[2], KnightAttackImageSet[3], \ "Buster", FRIENDLY ,8, 8, 4, 6, 20)#movement is usually 6 KnightSprite.RegisterAction(ATTACK, 'The character makes a powerful slash against an --adjacent target.',[],[]) KnightSprite.RegisterAction(WHIRLWIND, 'the character spins in a flurry hitting all enemies up to two tiles away.', [],[]) Characters.add(KnightSprite) ArcherDeathImageSet=sprites.load_sliced_sprites(64,64,'images/archer/archer_death.png') ArcherImageSet = sprites.load_sliced_sprites(64, 64, 'images/archer/archer_walk.png') ArcherAttackImageSet = sprites.load_sliced_sprites(64, 64, 'images/archer/archer_attack.png') ArcherSprite = Actor((15-.5)*tileSize, (4-1)*tileSize, ArcherImageSet[0], ArcherImageSet[1], ArcherImageSet[2], ArcherImageSet[3], \ DeathImageSet[0], ArcherAttackImageSet[0], ArcherAttackImageSet[1], ArcherAttackImageSet[2], ArcherAttackImageSet[3], \ "Archie", FRIENDLY ,5, 6, 5, 5, 17)#movement is usually 5 ArcherSprite.RegisterAction(RANGED, 'The character fires an arrow!', [],[]) ArcherSprite.RegisterAction(CRIPPLESTRIKE, 'The character aims for a sensitive area, postponing the targets next turn.', [],[]) Characters.add(ArcherSprite) ForestMageDeathImageSet=sprites.load_sliced_sprites(64,64,'images/forestmage/forestmage_death.png') ForestMageImageSet = sprites.load_sliced_sprites(64, 64, 'images/forestmage/forestmage_walk.png') ForestMageAttackImageSet = sprites.load_sliced_sprites(64, 64, 'images/forestmage/forestmage_spell.png') ForestMageSprite = Actor((16-.5)*tileSize, (4-1)*tileSize, ForestMageImageSet[0], ForestMageImageSet[1], ForestMageImageSet[2], ForestMageImageSet[3], \ ForestMageDeathImageSet[0], ForestMageAttackImageSet[0], ForestMageAttackImageSet[1], ForestMageAttackImageSet[2], ForestMageAttackImageSet[3], \ "Terra", FRIENDLY ,5, 4, 4, 5, 15) ForestMageSprite.RegisterAction(AOE, 'The character conjures Feline Flames!', [],[]) ForestMageSprite.RegisterAction(HEAL, 'Restores the health of yourself or an ally.', [], []) Characters.add(ForestMageSprite) # mainloop variables for gameplay frames_per_sec = 60.0 clock = pygame.time.Clock() running = True paused=True #start the game paused grid=False #Debugging boolean to draw a grid #these are triggers for text in the game gameStart=True scriptCounter=0 AlignmentCounter={} AlignmentCounter[FRIENDLY]=0 AlignmentCounter[HOSTILE]=0 gameOver=False AncientAwoken=False #Game Turns Controller PlayTurn=Turn(GameBoard) mode=PlayTurn.Mode()#used to detect when the mode changes for updating purposes #the Bad gusys PlayTurn.SpawnSkeleton(16,9,1) PlayTurn.SpawnSkeleton(22,13,1) PlayTurn.SpawnSkeleton(21,12, 1) PlayTurn.SpawnMage(15,16,1) PlayTurn.SpawnMage(17,20,1) PlayTurn.SpawnPig(12,19,1) PlayTurn.SpawnPig(13,18,1) PlayTurn.SpawnSkeleton(4,6,2) PlayTurn.SpawnMage(5,6,1) PlayTurn.SpawnMage(22,31,2) PlayTurn.SpawnPig(26,24,1) PlayTurn.SpawnPig(20,37,2) PlayTurn.SpawnPig(20,39,2) PlayTurn.SpawnPortal(2,6, 1) PlayTurn.SpawnPortal(7,18, 1) PlayTurn.SpawnPortal(28,25, 1) PlayTurn.SpawnPortal(34,38, 1) PlayTurn.SpawnPortal(18,47, 1) PlayTurn.SpawnPortal(9,42, 1) #PlayTurn.SpawnPortal(17,3,1) #PlayTurn.SpawnSpecial(18,38,level=5) #Picks the first character CurrentSprite=PlayTurn.Next() CurrentSpriteInfo = CharacterInfo(PlayTurn.CurrentSprite(), myfont, screen_height) myMenu = Menu("Turn:"+PlayTurn.CurrentSprite().Name(), PlayTurn.CurrentActions(), myfont, 50, 150, 200, 220, ActionItems = PlayTurn.CurrentSprite().GetActions()) starttext="ARCHIE, BUSTER and TERRA have been following a disturbance in arcane energies to the edge of a deep fissure in the earth."+ \ "Just beyond the fissure they find what appears to be a green portal. Before they can investigate they are ambushed by dark agents!" pausetext = ["Control the players using the mouse.", "WASD keys move the camera." , "+/- control the volume of the background music."] triggerText = ["These portals must be how the creatures are passing to this realm!", "We must destroy all of the portals!", "There is another one in the graveyard!", "Up ahead is a strange altar!"] PauseWindow = Menu("Defeat of the Ancient One", [CONTINUEGAME], myfont, 100,100, 600,int(len(starttext)/3), text=starttext) #Music BGvolume=.15#.05 #this is a number between 0 and 1 BackgroundMusic =pygame.mixer.Sound("sound/wandering_around.wav") BackgroundMusic.play(loops=-1) BackgroundMusic.set_volume(BGvolume) LevelUpMusic = pygame.mixer.Sound("sound/levelup.wav") ##The Main Game Loop while running: clock.tick(frames_per_sec) time = pygame.time.get_ticks() mouse_pos_x, mouse_pos_y = pygame.mouse.get_pos() #mouse coordinates tile_x, tile_y = mouse_pos_x// tileSize, mouse_pos_y // tileSize #note the board translates coordinates depending on the location of the camera #used these if you want to be able to hold down the mouse/keys pressedKeys=pygame.key.get_pressed() #actions that come from the keyboard This is for holding down pressedMouse = pygame.mouse.get_pressed() # mouse pressed event 3 booleans [button1, button2, button3] #counts the number of actors of each alignment AlignmentCounter[FRIENDLY]=0 AlignmentCounter[HOSTILE]=0 for actor in Characters: AlignmentCounter[actor.Alignment()] +=1 #checks for levelups, if PlayTurn.Mode()==LEVELUP and paused==False:# we are between turns if PlayTurn.CurrentSprite().LevelUp():#this is redundant #print 'levelup!' paused=True LevelUpMusic.play(loops=0) CurrentSpriteInfo = CharacterInfo(PlayTurn.CurrentSprite(), myfont, screen_height) LevelUpWindow = Menu(PlayTurn.CurrentSprite().Name()+' levels up!', PlayTurn.LevelUpActions() ,myfont, 100,100,200,200, ActionItems= PlayTurn.CurrentSprite().GetActions(), text="Choose a skill to improve.") continue #update the UI if (CurrentSprite != PlayTurn.CurrentSprite() or mode != PlayTurn.Mode() ) and PlayTurn.CurrentSprite !=[] and paused==False: CurrentSprite = PlayTurn.CurrentSprite() mode= PlayTurn.Mode() myMenu = Menu("Turn:"+PlayTurn.CurrentSprite().Name(), PlayTurn.CurrentActions(), myfont, 50, 150, 200, 220, ActionItems = PlayTurn.CurrentSprite().GetActions()) #CurrentActions is a list removing unavailable actions CurrentSpriteInfo = CharacterInfo(PlayTurn.CurrentSprite(), myfont, screen_height) #Move the camera manually with "wasd" ###Special Script section!! if scriptCounter==0 and PlayTurn.CurrentSprite().Alignment()==FRIENDLY and PlayTurn.CurrentSprite().tile_y>13 and PlayTurn._moves==[] and GameBoard.Animating()==False: paused=True currentText=PlayTurn.CurrentSprite().Name()+": "+triggerText[scriptCounter] PauseWindow = Menu("Defeat of the Ancient One", [CONTINUEGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText) GameBoard.PanCamera((25 + GameBoard._screenTileOffset_x)*GameBoard._tileSize, \ (22+ GameBoard._screenTileOffset_y)*GameBoard._tileSize) scriptCounter+=1 elif scriptCounter==1 and PlayTurn.CurrentSprite().Alignment()==FRIENDLY and PlayTurn.CurrentSprite().tile_y>17 and GameBoard.Animating()==False: paused=True currentText=PlayTurn.CurrentSprite().Name()+": "+triggerText[scriptCounter] PauseWindow = Menu("Defeat of the Ancient One", [CONTINUEGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText) scriptCounter+=1 if GameBoard.getTile(28,24,tiled=True)[0]!="Collision": PortalMusic =pygame.mixer.Sound("sound/portal.wav") PortalMusic.play(loops=0) PlayTurn.SpawnSkeleton(28,24,2) elif scriptCounter==2 and PlayTurn.CurrentSprite().Alignment()==FRIENDLY and PlayTurn.CurrentSprite().tile_x<10 and GameBoard.Animating()==False: paused=True currentText=PlayTurn.CurrentSprite().Name()+": "+triggerText[scriptCounter] PauseWindow = Menu("Defeat of the Ancient One", [CONTINUEGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText) scriptCounter+=1 elif scriptCounter==3 and PlayTurn.CurrentSprite().Alignment()==FRIENDLY and PlayTurn.CurrentSprite().tile_y>29 and GameBoard.Animating()==False: paused=True currentText=PlayTurn.CurrentSprite().Name()+": "+triggerText[scriptCounter] PauseWindow = Menu("Defeat of the Ancient One", [CONTINUEGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText) scriptCounter+=1 elif AlignmentCounter[HOSTILE]==0 and gameOver==False and AncientAwoken==False: AncientAwoken=True paused=True currentText="You have disturbed an ancient villain, behold the ANCIENT ONE!!!!" PauseWindow = Menu("Defeat of the Ancient One", [CONTINUEGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText) PlayTurn.SpawnSpecial(18,38,4) #print("won the game") elif AlignmentCounter[HOSTILE]==0 and gameOver==False and AncientAwoken==True: gameOver=True paused=True currentText="Congratulations on completing the abbreviated version of DEFEAT OF THE ANCIENT ONE. Someday we'll actually add in more to the game. Thank you for playing!!!!" PauseWindow = Menu("Defeat of the Ancient One", [RESTART, QUITGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText) #print("won the game") elif AlignmentCounter[FRIENDLY]==0 and gameOver==False: gameOver=True paused=True currentText="Your party has been defeated. Without you to prevent the return of the Ancient One, the world was destroyed!!" PauseWindow = Menu("Defeat of the Ancient One", [RESTART, QUITGAME], myfont, 100,100, 600,int(len(currentText)/3)+30, text=currentText) for event in pygame.event.get(): if event.type == QUIT or event.type == pygame.QUIT or (pressedKeys[K_w] and pressedKeys[K_LMETA]): running = False pygame.quit() sys.exit() if PlayTurn.Mode()==LEVELUP and paused: action = LevelUpWindow.input(event) elif paused: action = PauseWindow.input(event) else: action = myMenu.input(event) #actions that come from the menu if not (hasattr(event, 'key') or event.type==KEYDOWN or hasattr(event, 'button') or event.type==MOUSEBUTTONUP): continue #print(action) #UI or turn events if (action == CONTINUEGAME or pressedKeys[K_ESCAPE]): if gameStart==True: PauseWindow = Menu("Defeat of the Ancient One", pausetext+[CONTINUEGAME], myfont, 100,100, 600,100, text="This game can be paused at any time, bringing up this window by pressing ESC.") gameStart=False else: paused= not paused PauseWindow = Menu("Defeat of the Ancient One", pausetext+[CONTINUEGAME], myfont, 100,100, 600,100, text="") GameBoard.PanCamera((PlayTurn.CurrentSprite().tile_x + GameBoard._screenTileOffset_x)*GameBoard._tileSize, \ (PlayTurn.CurrentSprite().tile_y + GameBoard._screenTileOffset_y)*GameBoard._tileSize) elif action == QUITGAME: running = False pygame.quit() sys.exit() elif action == RESTART: #print("restart called") restart_program() #the level up parts elif PlayTurn.Mode()==LEVELUP and (action in actionList): CurrentSprite.LevelUpAction(action) PlayTurn._currentSprite=[] PlayTurn._mode=[] PlayTurn.Next() paused=False elif paused==False and (action == MOVE or pressedKeys[K_x]) and PlayTurn.Mode()==[] and PlayTurn.CurrentSprite().Alignment() != HOSTILE : PlayTurn.MoveMode() elif paused==False and (action == WAIT or pressedKeys[K_c]) and PlayTurn.CurrentSprite().Alignment() != HOSTILE: #note right now this overrides whatever mode you were in, a back button might be nice PlayTurn.EndTurn() elif paused==False and (action == CANCEL or pressedKeys[K_v]) and PlayTurn.CurrentSprite().Alignment() != HOSTILE: PlayTurn.CancelMode() elif paused==False and (action in actionList or pressedKeys[K_z]) and PlayTurn.Mode()==[] and PlayTurn.CurrentSprite().Alignment() != HOSTILE:#right now it brings up a target list #print("Entering Mode", action) PlayTurn.ActionMode(action) ''' #single keystroke type inputs if event.key ==K_RIGHT: pygame.mouse.set_pos([mouse_pos_x+tileSize, mouse_pos_y]) elif event.key == K_LEFT: pygame.mouse.set_pos([mouse_pos_x-tileSize, mouse_pos_y]) elif event.key == K_UP: pygame.mouse.set_pos([mouse_pos_x, mouse_pos_y-tileSize]) elif event.key == K_DOWN: pygame.mouse.set_pos([mouse_pos_x, mouse_pos_y+tileSize]) ''' #Debug if pressedKeys[K_g]: grid= not grid #DEBUG: this toggles the grid if pressedKeys[K_d]: GameBoard.MoveCamera(tileSize,0, relative=True) #right elif pressedKeys[K_a]: GameBoard.MoveCamera(-tileSize,0, relative=True)#left elif pressedKeys[K_w]: GameBoard.MoveCamera(0,-tileSize, relative=True) #up elif pressedKeys[K_s]: GameBoard.MoveCamera(0,tileSize, relative=True) #down elif pressedKeys[K_PLUS] or pressedKeys[K_EQUALS]: if BGvolume<1: BGvolume+=.05 elif pressedKeys[K_MINUS] or pressedKeys[K_UNDERSCORE]: if BGvolume>0: BGvolume-=.05 BackgroundMusic.set_volume(BGvolume) if pressedMouse[0]: myMenu = Menu("Turn:"+PlayTurn.CurrentSprite().Name(), PlayTurn.CurrentActions(), myfont, 50, 150, 200, 220, ActionItems = PlayTurn.CurrentSprite().GetActions()) #print(GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2]) #Seed what you clicked on and what turn mode you are in, then determins what to do if (PlayTurn.Mode()==ATTACK or PlayTurn.Mode()==RANGED or PlayTurn.Mode()==CRIPPLESTRIKE) and GameBoard.getTile(mouse_pos_x, mouse_pos_y)[0]=="Actor": PlayTurn.Attack(GameBoard.getTile(mouse_pos_x, mouse_pos_y)[1]) CurrentSpriteInfo = CharacterInfo(PlayTurn.CurrentSprite(), myfont, screen_height) elif PlayTurn.Mode()==MOVE: #asks the game controller if the CurrentSprite can move there PlayTurn.Move(GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2][0],GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2][1] ) elif PlayTurn.Mode()==AOE: PlayTurn.AOEAttack(GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2][0],GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2][1]) CurrentSpriteInfo = CharacterInfo(PlayTurn.CurrentSprite(), myfont, screen_height) elif PlayTurn.Mode()==HEAL: #and GameBoard.getTile(mouse_pos_x, mouse_pos_y)[0]=="Actor": #print("heal called") PlayTurn.HealAction(GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2][0],GameBoard.getTile(mouse_pos_x, mouse_pos_y)[2][1]) CurrentSpriteInfo = CharacterInfo(PlayTurn.CurrentSprite(), myfont, screen_height) Characters.update(time) GameBoard.update(time) if GameBoard.Animating() or paused: #print('Gameboard is animating or paused! Please be patient!', GameBoard.Animating(), paused) pass else: PlayTurn.update(time) #DEBUGGING: Grid if grid:#on a press of "g" the grid will be toggled for i in range(GameBoard._tileWidth):#draw vertical lines pygame.draw.line(screen, (0,0,0), (i*tileSize,0),(i*tileSize,GameBoard._width)) for j in range(GameBoard._tileHeight):#draw horizontal lines pygame.draw.line(screen, (20,0,20), (0,j*tileSize),(GameBoard._height,j*tileSize)) #moves the menu to the right if the camera is to the far left. if GameBoard.camTile()[0] < (myMenu.rect[2])// tileSize: myMenu.rect[0]=screen_width-myMenu.rect[2]-50 CurrentSpriteInfo.rect[0]=screen_width-CurrentSpriteInfo.rect[2] else: myMenu.rect[0]=50 CurrentSpriteInfo.rect[0]=0 #brings up info for a sprite you are hovering over if GameBoard.getTile(mouse_pos_x, mouse_pos_y)[0]=="Actor" and paused==False: actor = GameBoard.getTile(mouse_pos_x, mouse_pos_y)[1] HoverWindow = CharacterInfo(actor, myfont, screen_height-150) screen.blit(HoverWindow.surface, HoverWindow.rect) screen.blit(CurrentSpriteInfo.surface, CurrentSpriteInfo.rect) if PlayTurn.CurrentSprite().Alignment()==FRIENDLY and paused==False: screen.blit(myMenu.surface, myMenu.rect) elif paused and PlayTurn.Mode()==LEVELUP: #print("Level up window for", CurrentSprite.Name()) screen.blit(LevelUpWindow.surface, LevelUpWindow.rect) elif paused: screen.blit(PauseWindow.surface, PauseWindow.rect) pygame.display.flip()
class MainWindow(QMainWindow, Ui_MainWindow): """ Class documentation goes here. """ def __init__(self, parent = None): """ Constructor """ QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.mousePosition = [0, 0] self.setupUi(self) self.show() self.glFrame.setTitle( " " ) self.board = GameBoard(MainWindow, self) self.vLayout.addWidget(self.board) self.gameLog.keyPressEvent = self.test self.keyPressEvent = self.test self.board.wheelEvent = self.zoomMap self.board.mouseMoveEvent = self.moveMap self.board.mouseDoubleClickEvent = self.doubleClickMap self.board.mousePressEvent = self.clickMap self.board.mouseReleaseEvent = self.stopMoving self.lastX = False self.lastY = False self.mode = "team" self.myActiveClix = False self.theirActiveClix = False self.chooseMapDialog = None self.activeObject = False self.myDial.setMouseTracking(True) self.currentFigure.setMouseTracking(True) self.currentSet = None self.sets = {} setlistFile = os.path.join(sys.path[0], 'sets', 'setlist') if os.path.exists( setlistFile ): sets = open(setlistFile).readlines() for setname in sets: set, filesize, setname = setname.split(":") if os.path.getsize( set ) != filesize: self.generateSetList( setlistFile ) break else: self.sets[setname] = set else: self.generateSetList( setlistFile ) self.populateSetsDropdown() self.currentSelectedFigure = None self.myDial.mouseMoveEvent = self.hoverMyDial self.currentFigure.mouseMoveEvent = self.hoverCurrentFigure def populateSetsDropdown(self): self.cmbSet.addItem( "- Choose a Set -" ) for key, value in self.sets.items(): self.cmbSet.addItem( key ) return def generateSetList(self, setlistFile): self.sets = {} f = open( setlistFile, 'w' ) for infile in glob.glob( os.path.join(sys.path[0], 'sets', '*.xml' ) ): setXml = etree.parse( infile ) setname = setXml.getroot().get("name") line = infile+":"+str(os.path.getsize( infile ))+":"+setname self.sets[setname] = infile f.write( line ) f.close() @pyqtSignature("") def on_cmdBarrier_clicked(self): """ Slot documentation goes here. """ if self.cmdBarrier.isChecked(): self.clearOtherToggles( self.cmdBarrier ) self.glFrame.setTitle( "Click a square with no figure in it to add a barrier token" ) else: self.glFrame.setTitle( " " ) def test(self,event): if self.mode == "team": return #print event.key() if event.key() == QtCore.Qt.Key_Up and self.board.view_angle_x < 90: self.board.view_angle_x += 5.0 self.board.updateGL() elif event.key() == QtCore.Qt.Key_Down and self.board.view_angle_x > 20: self.board.view_angle_x -= 5.0 self.board.updateGL() elif event.key() == QtCore.Qt.Key_Left: self.board.view_angle_y += 5.0 self.board.updateGL() elif event.key() == QtCore.Qt.Key_Right: self.board.view_angle_y -= 5.0 self.board.updateGL() elif event.key() == 87: self.board.y_pos -= 1.0 self.board.updateGL() elif event.key() == 83: self.board.y_pos += 1.0 self.board.updateGL() elif event.key() == 65: self.board.x_pos += 1.0 self.board.updateGL() elif event.key() == 68: self.board.x_pos -= 1.0 self.board.updateGL() elif event.key() == 81: self.board.z_pos -= 1.0 self.board.updateGL() elif event.key() == 69: self.board.z_pos += 1.0 self.board.updateGL() elif event.key() == 48: self.board.z_pos = 0.0 self.board.y_pos = 0.0 self.board.x_pos = 0.0 self.board.view_angle_x = 90 self.board.view_angle_y = 0 self.board.view_distance = 1 self.board.updateGL() ''' if keystate[K_UP] and view_angle_x < 90: view_angle_x += 1.0 if keystate[K_DOWN] and view_angle_x > 0: view_angle_x -= 1.0 if keystate[K_LEFT]: view_angle_y += 1.0 if keystate[K_RIGHT]: view_angle_y -= 1.0 if keystate[K_PAGEUP] and view_distance < 2.0: view_distance += .03 if keystate[K_PAGEDOWN] and view_distance > 0.5: view_distance -= .03 if keystate[K_END]: view_distance = 1.0; view_angle_y = 0.0; view_angle_x = 90.0 ''' else: return QtGui.QMainWindow.keyPressEvent(self, event) @pyqtSignature("") def on_cmdLOF_clicked(self): if self.cmdLOF.isChecked(): self.board.modeLOF = True self.clearOtherToggles( self.cmdLOF ) else: self.board.modeLOF = False self.glFrame.setTitle( " " ) self.board.moving = False self.board.updateGL() @pyqtSignature("") def on_cmdObj_clicked(self): if self.cmdObj.isChecked(): self.board.modeObject = True self.clearOtherToggles( self.cmdObj ) else: self.board.modeObject = False self.glFrame.setTitle( " " ) self.board.moving = False self.board.updateGL() @pyqtSignature("") def on_cmdStandies_clicked(self): """ Slot documentation goes here. """ # TODO: not implemented yet raise NotImplementedError @pyqtSignature("") def on_cmdRemoveObject_clicked(self): """ Slot documentation goes here. """ # TODO: not implemented yet raise NotImplementedError @pyqtSignature("") def on_cmdSmokeCloud_clicked(self): if self.cmdSmokeCloud.isChecked(): self.clearOtherToggles( self.cmdSmokeCloud ) self.glFrame.setTitle( "Click a square with no figure in it to add a smoke cloud token" ) else: self.glFrame.setTitle( " " ) @pyqtSignature("") def on_cmdDebris_clicked(self): if self.cmdDebris.isChecked(): self.clearOtherToggles( self.cmdDebris ) self.glFrame.setTitle( "Click a square with no figure in it to add a debris token" ) else: self.glFrame.setTitle( " " ) @pyqtSignature("") def on_cmdSpecial_clicked(self): if not self.cmdSpecial.isChecked(): self.clearOtherToggles( self.cmdSpecial ) self.glFrame.setTitle( "Click a square with no figure in it to add a special token" ) else: self.glFrame.setTitle( " " ) @pyqtSignature("") def on_rollTwo_clicked(self): v = random.randint( 2, 12 ) s = "Rolled a "+str(v)+" on two dice." if v == 2: s += " <b>Crit miss!</b>" elif v == 12: s += " <b>Critical hit!</b>" self.board.log( "Me", s ) @pyqtSignature("") def on_rollOne_clicked(self): v = random.randint( 1, 6 ) self.board.log( "Me", "Rolled a "+str(v)+" on one die.") @pyqtSignature("") def on_cmdHeal_clicked(self): f = self.getMyActiveClix() if f: f.heal() self.redrawMyDial() @pyqtSignature("") def on_cmdTokenBlue_clicked(self): f = self.getMyActiveClix() if f: f.token( "blue" ) self.board.updateGL() @pyqtSignature("") def on_cmdTokenRed_clicked(self): f = self.getMyActiveClix() if f: f.token( "red" ) self.board.updateGL() @pyqtSignature("") def on_cmdDamage_clicked(self): f = self.getMyActiveClix() if f: f.damage() self.redrawMyDial() def getMyActiveClix(self): c = self.myActiveClix if c: x, y = c f = self.board.boardFigures[x][y] if f: return f return False def getBoardXY(self, event): v = self.board.viewport() winY = v[3] - event.y() winX = event.x() winZ = self.board.getMouseZ(winX, winY) posX, posY, posZ = gluUnProject(winX, winY, winZ) x = int(math.ceil(posX)+11) y = int(math.ceil(posZ)+11) return [x, y] def hoverCurrentFigure(self, event): if self.currentSelectedFigure is not None: print event.pos() return def hoverMyDial(self, event): if self.myActiveClix: f = self.board.boardFigures[self.myActiveClix[0]][self.myActiveClix[1]] if f: t = f.getToolTip(event.pos()) if t: QtGui.QToolTip.showText( event.globalPos(), "<p>"+t+"</p>", self.myDial ) else: QtGui.QToolTip.hideText() def clickMap(self, event): x, y = self.getBoardXY(event) if ( x >= 0 and x <= 23 and y >= 0 and y <= 23 ): if event.button() == QtCore.Qt.RightButton and self.board.boardObjects[x][y]: #Picking up an object o = self.board.boardObjects[x][y] f = False if self.myActiveClix: f = self.board.boardFigures[self.myActiveClix[0]][self.myActiveClix[1]] if o and o.canBePickedUp() and f: b = f.takeObject(o) if b: self.board.updateGL() elif isinstance(o, ObjectSimpleSquare): if o.type == "barrier": o.type = "debris" if f: self.board.log( "Me", f.getName() + " destroys a square of blocking terrain." ) else: self.board.log( "Me", "Destroyed a square of blocking terrain.") else: self.board.boardObjects[x][y] = False self.board.log( "Me", "Removed a square of "+o.type+" terrain.") self.board.updateGL() elif event.button() == QtCore.Qt.RightButton and self.board.boardFigures[x][y] and self.board.boardFigures[x][y].hasObject() and self.board.boardFigures[x][y].mine: #Dropping an object f = self.board.boardFigures[x][y] f.dropObject() self.myActiveClix = (x, y) self.board.updateGL() elif (self.cmdBarrier.isChecked() or self.cmdSmokeCloud.isChecked() or self.cmdDebris.isChecked() or self.cmdSpecial.isChecked()) and not self.board.boardObjects[x][y]: if self.cmdBarrier.isChecked(): type = "barrier" elif self.cmdSmokeCloud.isChecked(): type = "smoke cloud" elif self.cmdDebris.isChecked(): type = "debris" elif self.cmdSpecial.isChecked(): type = "special" b = ObjectSimpleSquare(self.board, type) self.board.boardObjects[x][y] = b b.x = x b.y = y self.board.log( "Me", "Placed a "+type+" token." ) self.board.updateGL() else: if ( self.board.boardFigures[x][y] and not self.board.modeObject ): f = self.board.boardFigures[x][y] self.board.moving = True self.board.moveOriginX = self.board.moveDestinationX = x self.board.moveOriginY = self.board.moveDestinationY = y #self.board.clearMyActive() if f.mine: self.board.clearActive(1) self.myActiveClix = (x, y) f.active = 1 self.redrawMyDial() else: self.board.clearActive(2) self.theirActiveClix = (x, y) f.active = 2 self.redrawTheirDial() elif self.board.boardObjects[x][y]: self.board.moving = True self.board.modeObject = True self.board.moveOriginX = self.board.moveDestinationX = x self.board.moveOriginY = self.board.moveDestinationY = y self.activeObject = (x, y) self.redrawMyDial() elif self.cmdLOF.isChecked(): self.board.moving = True self.board.moveOriginX = self.board.moveDestinationX = x self.board.moveOriginY = self.board.moveDestinationY = y def redrawMyDial(self): if self.board.modeObject: f = self.board.boardObjects[self.activeObject[0]][self.activeObject[1]] else: f = self.board.boardFigures[self.myActiveClix[0]][self.myActiveClix[1]] if f: png = f.drawDial() if png: pixmap = QtGui.QPixmap() pixmap.loadFromData(png, "PNG") self.myDial.setPixmap( pixmap ) self.myDial.update() def redrawTheirDial(self): f = self.board.boardFigures[self.theirActiveClix[0]][self.theirActiveClix[1]] pixmap = QtGui.QPixmap() pixmap.loadFromData(f.drawDial(), "PNG") self.theirDial.setPixmap( pixmap ) self.theirDial.update() def doubleClickMap(self, event): x, y = self.getBoardXY(event) #print "X %s Y %s aX %s aY %s vD %s Xoffset %s Yoffset %s Zoffset %s" % ( x, y, self.board.view_angle_x, self.board.view_angle_y, self.board.view_distance, self.board.x_pos, self.board.y_pos, self.board.z_pos ) # if ( x >= 0 and x <= 23 and y >= 0 and y <= 23 ): # f = self.board.boardFigures[x][y] # if f: # f.damage() # self.redrawMyDial() return def moveMap(self, event): x, y = self.getBoardXY(event) if ( x >= 0 and x <= 23 and y >= 0 and y <= 23 ): if self.board.moving and ( (self.lastX == False and self.lastY == False ) or (self.lastX != x or self.lastY != y ) ) and event.x() > 0 and event.y() > 0: self.board.moveDestinationX = x self.board.moveDestinationY = y self.lastX = x self.lastY = y if self.board.modeObject: f = self.board.boardObjects[self.board.moveOriginX][self.board.moveOriginY] else: f = self.board.boardFigures[self.board.moveOriginX][self.board.moveOriginY] delta = abs( x - self.board.moveOriginX ) dY = abs( y - self.board.moveOriginY ) if dY > delta: delta = dY if self.board.modeLOF: self.glFrame.setTitle( "LOF "+str(delta)+" space(s)..." ) else: self.glFrame.setTitle( "Moving "+f.getName()+" "+str(delta)+" space(s)..." ) #print self.board.moveDestinationX, self.board.moveDestinationY self.board.updateGL() def stopMoving(self, event): if self.board.moving and not self.cmdLOF.isChecked(): x, y = self.getBoardXY(event) doMove = True if not self.board.modeObject: f = self.board.boardFigures[self.board.moveOriginX][self.board.moveOriginY] if self.board.boardFigures[self.board.moveDestinationX][self.board.moveDestinationY]: doMove = False if f and not f.mine: doMove = False else: if self.board.boardObjects[self.board.moveDestinationX][self.board.moveDestinationY]: doMove = False f = self.board.boardObjects[self.board.moveOriginX][self.board.moveOriginY] if doMove: f.x = self.board.moveDestinationX f.y = self.board.moveDestinationY if f and f.mine: self.myActiveClix = (self.board.moveDestinationX, self.board.moveDestinationY) self.board.moveSelectedFigure() self.glFrame.setTitle( " " ) self.board.moving = False if self.board.modeObject: if not self.cmdObj.isChecked(): self.board.modeObject = False self.board.updateGL() def zoomMap(self, event): if (event.orientation() == QtCore.Qt.Vertical): #new_distance = self.board.view_distance + (float(event.delta()) / 8 / 15) #if ( new_distance > 0.05 and new_distance < 1 ): # self.board.view_distance = new_distance # self.board.updateGL() new_distance = self.board.z_pos + float(event.delta()) / 8 if new_distance >= 0 and new_distance <= 40: self.board.z_pos = new_distance self.board.updateGL() return QtGui.QMainWindow.wheelEvent(self, event) def clearOtherToggles(self, button): if button != self.cmdBarrier: self.cmdBarrier.setChecked( False ) if button != self.cmdSmokeCloud: self.cmdSmokeCloud.setChecked( False ) if button != self.cmdDebris: self.cmdDebris.setChecked( False ) if button != self.cmdSpecial: self.cmdSpecial.setChecked( False ) if button != self.cmdLOF: self.cmdLOF.setChecked( False ) self.board.modeLOF = False self.board.moving = False self.board.updateGL() if button != self.cmdObj: self.cmdObj.setChecked( False ) self.board.modeObject = False @pyqtSignature("") def on_actionTeam_Builder_activated(self): self.wStack.setCurrentIndex(0) self.mode = "team" @pyqtSignature("") def on_actionBattle_Map_activated(self): self.wStack.setCurrentIndex(1) self.mode = "map" @pyqtSignature("") def on_actionChoose_Map_activated(self): if self.chooseMapDialog is None: self.chooseMapDialog = dlgChooseMap(self) self.chooseMapDialog.setMap( self.board.currentMap ) self.chooseMapDialog.show() @pyqtSignature("") def on_txtSearch_returnPressed(self): #print self.txtSearch.text() mnm = etree.parse(os.path.join(sys.path[0], 'sets', 'mnm.xml')) search = str( self.txtSearch.text() ) conditions = [] if search is not None: parts = search.lower().split( " " ) for part in parts: x = part.split(":") if len(x) == 2: conditions.append( ( x[0], x[1] ) ) if len(conditions): for c in conditions: op, val = c print op, val if op == "points": return @pyqtSignature("QString") def on_cmbSet_currentIndexChanged(self, p0): print p0 chosenSet = str(p0) if chosenSet == "- Choose a Set -": return False if self.currentSet and chosenSet == self.currentSet.getroot().get("name"): return False self.currentSet = setXml = etree.parse( self.sets[chosenSet] ) figures = setXml.find("figures") for figure in figures: self.lstFigures.addItem( figure.get("id") + " " + figure.get("name") ) @pyqtSignature("QString") def on_lstFigures_currentTextChanged(self, currentText): ex = str(currentText).split(" ") id = ex[0] figures = self.currentSet.xpath("//figure[@id='"+id+"']") if len(figures): figure = figures[0] self.currentSelectedFigure = figure dial = figure.find("dial") if dial: dialLength = int(dial.get("length")) if dialLength < 11: dialLength = 11 ko_click = "<td width='20'><table border='1' style='border-style: solid;border-color: white' cellspacing='0' cellpadding='0'><tr><td width='20' align='center' style='color:red'>KO</td></tr></table></td>" spd_clicks = dial.xpath("click/spd") atk_clicks = dial.xpath("click/atk") def_clicks = dial.xpath("click/def") dmg_clicks = dial.xpath("click/dmg") text = "<p><b>"+figure.get("name")+"</b></p>" text += "<table bgcolor='white' border='0'>" # text += "<tr><td bgcolor='red'>Doom</td></tr>" text += "<tr>" text += "<td width='20'><table border='1' bgcolor='black' style='border-style: solid;border-color: black' cellspacing='0' cellpadding='0'><tr><td width='20' align='center'><img src='images/units-m-normal.gif'></td></tr></table></td>" for i in range(0, dialLength): i = int(i) if len(spd_clicks)<=i: text += ko_click else: p = spd_clicks[i].get("power") value = spd_clicks[i].text border_color = "white" bg_color = 'white' fg_color = 'black' if p: if p == "SPC": bg_color = "white" border_color = "black" fg_color = 'black' else: c = self.board.PAC.getColors(spd_clicks[i].get("power")) bg_color = c[0] fg_color = "color:"+c[1] text += "<td width='20'><table border='1' style='border-style: solid;border-color: "+border_color+"' cellspacing='0' cellpadding='0'><tr><td width='20' align='center' bgcolor='"+bg_color+"' style='"+fg_color+"'>"+value+"</td></tr></table></td>" text += "</tr>" text += "</table>" self.currentFigure.setText( text )
class Game: def __init__(self): self.board = GameBoard() self.nn = NeuralNetwork([15, 200, 6], 0.3) def turn(self, player, pit): next_player = self.board.move_marbles(player, pit) if self.board.check_end_condition(): # print("end") return -1 return next_player def text_play(self): player = 0 print("Welcome to the game of Mancala! Player 0 will go first") while player >= 0: self.board.text_display_board() pit = int(input("Player {}, please enter which pit (1-6) you would like to shift from:".format(player))) player = self.turn(player, pit) score = self.board.get_score() final_marbles = self.board.get_sum_rows() score = [score[i] + final_marbles[i] for i in range(len(score))] winner = max(enumerate(score), key=lambda x: x[1])[0] self.board.text_display_board() print("Congratulations Player {}! You are the winner. " "The final score was Player 0: {} Player 1: {}".format(winner, score[0], score[1])) self.reset_game() def reset_game(self): self.board = GameBoard() def test_against_random_agent(self, agent, num_games): player = 0 reset_counter = 0 turn_counter = 0 agent_win_counter = 0 agent_player = 0 next_player = 1 while reset_counter < num_games: # initial_score = self.board.get_score() turn_counter += 1 # print(self.board.text_display_board()) if player == agent_player: agent_input = self.board.get_board() agent_input.append(agent_player) agent_decision = agent.query(agent_input) sorted_decision = list(enumerate(agent_decision.flatten())) sorted_decision.sort(key=lambda x: x[1]) for i in range(len(sorted_decision)): pit = sorted_decision[-(i + 1)][0] + 1 next_player = self.turn(player, pit) if next_player == 2: next_player = agent_player # print(self.board.get_score()) else: break # post_turn_score = self.board.get_score() # score_diff = [post_turn_score[i] - initial_score[i] for i in range(len(initial_score))] else: pit = Game.random_agent() next_player = self.turn(player, pit) if next_player == 2: next_player = -agent_player + 1 if next_player == -1: score = self.board.get_score() final_marbles = self.board.get_sum_rows() score = [score[i] + final_marbles[i] for i in range(len(score))] winner = max(enumerate(score), key=lambda x: x[1])[0] if winner == agent_player: agent_win_counter += 1 self.reset_game() reset_counter += 1 turn_counter = 0 agent_player = -agent_player + 1 next_player = 0 player = next_player return agent_win_counter / num_games @staticmethod def random_agent(): return random.randint(1, 6) @staticmethod def discount_rewards(reward_history, d_rate): discounted_rewards = [] accumulated_reward = 0 for i in range(1, len(reward_history) + 1): accumulated_reward = reward_history[-i] + accumulated_reward * d_rate discounted_rewards.insert(0, accumulated_reward) # print(accumulated_reward) # normalize rewards before returning # print(discounted_rewards) discounted_rewards -= np.mean(discounted_rewards) std_dev = np.std(discounted_rewards) if std_dev != 0: discounted_rewards /= std_dev # print(discounted_rewards) return discounted_rewards def train_neural_network(self, game_runs): game_input_history = [] game_target_history = [] reward_history = [] player = 0 reset_counter = 0 turn_counter = 0 ai_win_counter = 0 ai_player = 0 print("Welcome to the game of Mancala! this training session will continue for {} runs.".format(game_runs)) while reset_counter < game_runs: initial_score = self.board.get_score() turn_counter += 1 if player == ai_player: ai_input = self.board.get_board() ai_input.append(ai_player) game_input_history.append(ai_input) ai_decision = self.nn.query(ai_input) sorted_decision = list(enumerate(ai_decision.flatten())) sorted_decision.sort(key=lambda x: x[1]) for i in range(len(sorted_decision)): pit = sorted_decision[-(i + 1)][0] + 1 next_player = self.turn(player, pit) if next_player == 2: next_player = ai_player #print(self.board.get_score()) else: break post_turn_score = self.board.get_score() score_diff = [post_turn_score[i] - initial_score[i] for i in range(len(initial_score))] # Converting the numpy array returned by query into a python list with integer elements (rather than # numpy array elements as defaulted to by running list[ai_decision ai_decision = [x[0] for x in list(ai_decision)] target_list = ai_decision # target_list = np.zeros(6) if score_diff[player] > 0: target_list[pit - 1] = 0.99 reward_history.append(0.5 * score_diff[player]) else: target_list[pit - 1] = 0.01 reward_history.append(-1) game_target_history.append(target_list) # self.nn.train(ai_input, target_list) # print("Turn {} has passed. NN scores {} points this round.".format(turn_counter, score_diff[player])) else: pit = Game.random_agent() next_player = self.turn(player, pit) if next_player == 2: next_player = -ai_player + 1 if next_player == -1: score = self.board.get_score() final_marbles = self.board.get_sum_rows() score = [score[i] + final_marbles[i] for i in range(len(score))] winner = max(enumerate(score), key=lambda x: x[1])[0] # print("NN: Player {} Random AI: Player {}".format(ai_player, -ai_player + 1)) # print("Player {} won!".format(winner)) if winner == ai_player: ai_win_counter += 1 reward_history = [reward * 1.5 for reward in reward_history] discounted_rewards = Game.discount_rewards(reward_history, 0.5) for i in range(len(game_input_history)): self.nn.train(game_input_history[i], [target * discounted_rewards[i] for target in game_target_history[i]]) game_target_history = [] game_input_history = [] reward_history = [] self.reset_game() reset_counter += 1 turn_counter = 0 ai_player = -ai_player + 1 next_player = 0 if reset_counter > 0 and reset_counter * 100 / game_runs % 10 == 0: print("Training is {}% finished!".format(reset_counter * 100 / game_runs)) player = next_player print("AI has completed this training session.") print("AI has won {} percentage of games".format(ai_win_counter/game_runs)) def test_neural_network(self, game_runs): player = 0 reset_counter = 0 turn_counter = 0 ai_win_counter = 0 ai_player = 0 next_player = 1 print("Welcome to the game of Mancala! AI will start first") while reset_counter < game_runs: initial_score = self.board.get_score() turn_counter += 1 # print(self.board.text_display_board()) if player == ai_player: ai_input = self.board.get_board() ai_input.append(ai_player) ai_decision = self.nn.query(ai_input) sorted_decision = list(enumerate(ai_decision.flatten())) sorted_decision.sort(key=lambda x: x[1]) for i in range(len(sorted_decision)): pit = sorted_decision[-(i + 1)][0] + 1 next_player = self.turn(player, pit) if next_player == 2: next_player = ai_player # print(self.board.get_score()) else: break post_turn_score = self.board.get_score() score_diff = [post_turn_score[i] - initial_score[i] for i in range(len(initial_score))] # print(post_turn_score) print("Turn {} has passed. NN scores {} points this round.".format(turn_counter, score_diff[player])) else: pit = Game.random_agent() next_player = self.turn(player, pit) if next_player == 2: next_player = -ai_player + 1 if next_player == -1: score = self.board.get_score() final_marbles = self.board.get_sum_rows() score = [score[i] + final_marbles[i] for i in range(len(score))] winner = max(enumerate(score), key=lambda x: x[1])[0] print("NN: Player {} Random AI: Player {}".format(ai_player, -ai_player + 1)) print("Player {} won!".format(winner)) print("Final Score is {}!".format(score)) if winner == ai_player: ai_win_counter += 1 self.reset_game() reset_counter += 1 turn_counter = 0 ai_player = -ai_player + 1 next_player = 0 player = next_player print("AI has won {} percentage of games".format(ai_win_counter / game_runs))
def process(self, pos, event, screen, dal): # this is the login button for player 2. This allows the second player to login only when the gamemode is against an opponent if event.type == pygame.MOUSEBUTTONDOWN: if self._current_selected == Button.OPPONENT: if self._login_button_pos.collidepoint(pos) == True: #This is used to login player 2 login = LoginScreen.Login(0, 0, 1280, 1024, dal, 2) retval = login.display() screen1, background1, clock1 = self._facade.initialise_screen( "battleships", "battleship_Options_leftbar.png", self._screen_size) self.draw(screen, Button.OPPONENT, Button.OPPONENT, dal) if retval == Navigate.SPLASHSCREEN: return retval # this calls the game board for the opponent when the play button is pressed if event.type == pygame.MOUSEBUTTONDOWN: if self._current_selected == Button.OPPONENT: if self._play_button_pos.collidepoint(pos) == True: game = GameScreen.GameBoard(0, 0, 1280, 1024, dal) retval = game.display() screen1, background1, clock1 = self._facade.initialise_screen( "battleships", "battleship_Options_leftbar.png", self._screen_size) self.draw(screen, Button.OPPONENT, Button.OPPONENT, dal) if retval == Navigate.SPLASHSCREEN: return retval # this calls the game board for the simulation when the play button is pressed if event.type == pygame.MOUSEBUTTONDOWN: if self._current_selected == Button.SIMULATION: if self._play_button_pos.collidepoint(pos) == True: #here we need to auto login CPU as player 2 dal.is_user_valid("CPU", "CPU", self._PLAYER2) game = GameScreen.GameBoard(0, 0, 1280, 1024, dal) retval = game.display() screen1, background1, clock1 = self._facade.initialise_screen( "battleships", "battleship_Options_leftbar.png", self._screen_size) self.draw(screen, Button.SIMULATION, Button.SIMULATION, dal) if retval == Navigate.SPLASHSCREEN: return retval if event.type == pygame.MOUSEBUTTONDOWN: if self._current_selected == Button.PROFILE: if self._edit_button_pos.collidepoint(pos) == True: register = RegisterScreen.Register(0, 0, 1280, 1024, dal, True) retval = register.display() screen1, background1, clock1 = self._facade.initialise_screen( "battleships", "battleship_Options_leftbar.png", self._screen_size) self.draw(screen, Button.PROFILE, Button.PROFILE, dal) if retval == Navigate.SPLASHSCREEN: return retval # this calls the game board for the simulation when the play button is pressed if event.type == pygame.MOUSEBUTTONDOWN: if self._current_selected == Button.SHIPS_LOG: if self._play_button_pos.collidepoint(pos) == True: #here we need to auto login CPU as player 2 ships_log = ShipsLogScreen.ShipsLog(0, 0, 1280, 1024, dal) retval = ships_log.display() screen1, background1, clock1 = self._facade.initialise_screen( "battleships", "battleship_Options_leftbar.png", self._screen_size) self.draw(screen, Button.SIMULATION, Button.SIMULATION, dal) if retval == Navigate.SPLASHSCREEN: return retval # this calls the game board for the simulation when the play button is pressed if event.type == pygame.MOUSEBUTTONDOWN: if self._current_selected == Button.HELP: if self._play_button_pos.collidepoint(pos) == True: self._facade.launch_help() # this tells the players who is against who only displayed for the opponent and also if another player is logged in. if self._current_selected == Button.OPPONENT: if dal.is_player_two_logged_in() == True: message = "Player {} v Player {}".format( dal.get_logged_user_player_1().username, dal.get_logged_user_player_2().username) self._facade.DrawStringArchivoNarrow(screen, message, 436, 700, self._login_color, False, 60) # displays player 1 vs CPU and will only display for the simulation section if self._current_selected == Button.SIMULATION: message = "Player {} v Computer".format( dal.get_logged_user_player_1().username) self._facade.DrawStringArchivoNarrow(screen, message, 436, 700, self._login_color, False, 60) # while the mouse is moving this decides if the mouse hovered on a button and if it did it tells it to highlight it. if event.type == pygame.MOUSEMOTION: if self._btn_simulation_pos.collidepoint(pos) == True: self._current_button = Button.SIMULATION if self._btn_opponent_pos.collidepoint(pos) == True: self._current_button = Button.OPPONENT if self._btn_ships_log_pos.collidepoint(pos) == True: self._current_button = Button.SHIPS_LOG if self._btn_profile_pos.collidepoint(pos) == True: self._current_button = Button.PROFILE if self._btn_help_pos.collidepoint(pos) == True: self._current_button = Button.HELP if self._btn_quit_pos.collidepoint(pos) == True: self._current_button = Button.QUIT # this is for when a person clicks a button this keeps track of the currnetly selected button if event.type == pygame.MOUSEBUTTONDOWN: if self._btn_simulation_pos.collidepoint(pos) == True: self._current_selected = Button.SIMULATION if self._btn_opponent_pos.collidepoint(pos) == True: self._current_selected = Button.OPPONENT if self._btn_ships_log_pos.collidepoint(pos) == True: self._current_selected = Button.SHIPS_LOG if self._btn_profile_pos.collidepoint(pos) == True: self._current_selected = Button.PROFILE if self._btn_help_pos.collidepoint(pos) == True: self._current_selected = Button.HELP if self._btn_quit_pos.collidepoint(pos) == True: self._current_selected = Button.QUIT if self._current_selected == Button.QUIT: return Button.QUIT #draws the buttons according to the current state self.draw(screen, self._current_button, self._current_selected, dal) return Button.CONTINUE
def __init__(self): self.board = GameBoard() self.nn = NeuralNetwork([15, 200, 6], 0.3)
#!usr/bin/env python from GameBoard import * from Agent import * import time if __name__ == "__main__": p1 = 0 p2 = 0 is_print = True for i in range(1): g = GameBoard() if is_print: g.print_board() players = [NStepAgent("COM1", 1, g, 12), UCTAgent("COM2", 2, g, 15000)] while len(g.get_choices()) > 0: p = players[g.player - 1] bt = time.time() c = p.get_choice() g.move(c, g.player) if is_print: print("Spend time: %.2fs" % (time.time() - bt)) g.print_board() print() if g.is_winner(c, g.player): print(p.name + " is WINNER!") if p.player == 1: p1 += 1
def testIsSmallerThanAllTopCards(self): someCards = [Stack(Card(25, 6)), Stack(Card(30, 7)), Stack(Card(7, 3)), Stack(Card(66, 2))] board = GameBoard(someCards) self.assertTrue(board.isSmallerThanAllTopCards(Card(3, 3))) self.assertFalse(board.isSmallerThanAllTopCards(Card(88, 3))) self.assertFalse(board.isSmallerThanAllTopCards(Card(50, 3)))
def setStartingBoard (self): self.board = GameBoard.gameBoard()
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 human_game_history = [] human_board = GameBoard.GameBoard() def StartNewGameAgainstHuman(weights, ai_starts=False): global human_board global human_game_history human_board = GameBoard.GameBoard() human_game_history = [ (human_board, BoardEvaluator.EvaluateBoard(human_board, CellState.CS_AI, weights)) ] if ai_starts: nextBoard, otherMoves = MakeMove(human_board, CellState.CS_AI, weights,
def __init__(self, Sec, LblTimer, gameBoard): threading.Thread.__init__(self) self.MGB = GameBoard.WindowGameBoard(gameBoard) self.seconds = Sec self.lblTimer = LblTimer print("TTTTTTTTTTTTTTTTTTTTTTTT")
def __init__(self): self.board = GameBoard.Board(CheckerBoard.BOARD_SIZE, CheckerBoard.BOARD_SIZE) self.place_starting_pieces()
def prepareBoard(): """Prepare a new game board.""" global theBoard theBoard = GameBoard.GameBoard() # 16x15, secret square at 0,0. This is the default
def _minmax(self, is_max, previous_board_int, board_int, previous_action, depth, alpha, beta, debug=False): if is_max: piece_type = self.piece_type else: piece_type = 3 - self.piece_type # TODO: check if end of game (both don't have valid moves), return +inf or -inf # check history table encoded_board = board_int check = self._check_encoded_state(encoded_board, piece_type) if check: return check valid_moves = self._get_valid_moves(previous_board_int, board_int, piece_type) if not valid_moves: # TODO: handle no valid move return 0 best_value = float("-inf") if is_max else float("inf") if depth < 1: for move in self._get_valid_moves(previous_board_int, board_int, self.piece_type): score = GameBoard.evaluate_move(board_int, self.piece_type, move) if is_max: best_value = max(score, best_value) else: best_value = min(score, best_value) if debug: print(" in {} end".format("max" if is_max else "min")) print( GameBoard.visualize_evaluation(board_int, self.piece_type)) print(" give {} with score {}".format( "max" if is_max else "min", best_value)) return best_value for i, j in valid_moves: new_previous_board_int = board_int # impossible to be unsuccessful new_board_int, success = GameBoard.place_chess( previous_board_int, board_int, i, j, piece_type) score = self._minmax(not is_max, new_previous_board_int, new_board_int, previous_action, depth - 1, alpha, beta) if is_max: best_value = max(score, best_value) alpha = max(alpha, best_value) else: best_value = min(score, best_value) beta = min(best_value, beta) if beta <= alpha: break if debug: print(" in {}".format("max" if is_max else "min")) print(GameBoard.visualize_evaluation(board_int, self.piece_type)) print(" give {} with score {}".format( "max" if is_max else "min", best_value)) # write to history dictionary self._store_encoded_state(encoded_board, piece_type, best_value) return best_value
import GameBoard import Display mainBoard = GameBoard.GameBoard() mainDisplay = Display.Display(mainBoard) isWhiteTurn = False while mainDisplay.ContinueGame(): if mainDisplay.UpdateDisplay(isWhiteTurn): isWhiteTurn = not isWhiteTurn
class PyHC(Ui_MainWindow): ''' Example class for using SpiralWidget''' def __init__(self, ui, MainWindow): self.mousePosition = [0, 0] self.MainWindow = MainWindow self.ui = ui ui.glFrame.setTitle( " " ) self.board = GameBoard(MainWindow, ui) ui.vLayout.addWidget(self.board) ui.gameLog.keyPressEvent = self.test MainWindow.keyPressEvent = self.test self.board.wheelEvent = self.zoomMap self.board.mouseMoveEvent = self.moveMap self.board.mouseDoubleClickEvent = self.doubleClickMap self.board.mousePressEvent = self.clickMap self.board.mouseReleaseEvent = self.stopMoving self.lastX = False self.lastY = False ui.cmdHeal.mousePressEvent = self.healClix ui.cmdDamage.mousePressEvent = self.damageClix ui.cmdTokenRed.mousePressEvent = self.tokenRed ui.cmdTokenBlue.mousePressEvent = self.tokenBlue ui.rollOne.mousePressEvent = self.rollOne ui.rollTwo.mousePressEvent = self.rollTwo ui.cmdBarrier.mousePressEvent = self.barrier ui.cmdSmokeCloud.mousePressEvent = self.smokeCloud ui.cmdDebris.mousePressEvent = self.debris ui.cmdSpecial.mousePressEvent = self.special ui.cmdLOF.mousePressEvent = self.changeLOF ui.cmdObj.mousePressEvent = self.changeObjectMode self.myActiveClix = False self.theirActiveClix = False self.activeObject = False ui.myDial.setMouseTracking(True) ui.myDial.mouseMoveEvent = self.hoverMyDial def getMyActiveClix(self): c = self.myActiveClix if c: x, y = c f = self.board.boardFigures[x][y] if f: return f return False def changeLOF(self, event): if not self.ui.cmdLOF.isChecked(): self.board.modeLOF = True self.clearOtherToggles( self.ui.cmdLOF ) else: self.board.modeLOF = False self.ui.glFrame.setTitle( " " ) self.board.moving = False self.board.updateGL() return QtGui.QPushButton.mousePressEvent(self.ui.cmdLOF, event) def changeObjectMode(self, event): if not self.ui.cmdObj.isChecked(): self.board.modeObject = True self.clearOtherToggles( self.ui.cmdObj ) else: self.board.modeObject = False self.ui.glFrame.setTitle( " " ) self.board.moving = False self.board.updateGL() return QtGui.QPushButton.mousePressEvent(self.ui.cmdObj, event) def rollOne(self, event): v = random.randint( 1, 6 ) self.board.log( "Me", "Rolled a "+str(v)+" on one die.") return QtGui.QPushButton.mousePressEvent(self.ui.rollOne, event) def rollTwo(self, event): v = random.randint( 2, 12 ) s = "Rolled a "+str(v)+" on two dice." if v == 2: s += " <b>Crit miss!</b>" elif v == 12: s += " <b>Critical hit!</b>" self.board.log( "Me", s ) return QtGui.QPushButton.mousePressEvent(self.ui.rollTwo, event) def healClix(self, event): f = self.getMyActiveClix() if f: f.heal() self.redrawMyDial() return QtGui.QPushButton.mousePressEvent(self.ui.cmdHeal, event) def damageClix(self, event): f = self.getMyActiveClix() if f: f.damage() self.redrawMyDial() return QtGui.QPushButton.mousePressEvent(self.ui.cmdDamage, event) def tokenRed(self, event): f = self.getMyActiveClix() if f: f.token( "red" ) self.board.updateGL() return QtGui.QPushButton.mousePressEvent(self.ui.cmdTokenRed, event) def tokenBlue(self, event): f = self.getMyActiveClix() if f: f.token( "blue" ) self.board.updateGL() return QtGui.QPushButton.mousePressEvent(self.ui.cmdTokenBlue, event) def getBoardXY(self, event): v = self.board.viewport() winY = v[3] - event.y() winX = event.x() winZ = self.board.getMouseZ(winX, winY) posX, posY, posZ = gluUnProject(winX, winY, winZ) x = int(math.ceil(posX)+11) y = int(math.ceil(posZ)+11) return [x, y] def hoverMyDial(self, event): if self.myActiveClix: f = self.board.boardFigures[self.myActiveClix[0]][self.myActiveClix[1]] if f: t = f.getToolTip(event.pos()) if t: QtGui.QToolTip.showText( event.globalPos(), "<p>"+t+"</p>", self.ui.myDial ) else: QtGui.QToolTip.hideText() def clickMap(self, event): x, y = self.getBoardXY(event) if ( x >= 0 and x <= 23 and y >= 0 and y <= 23 ): if event.button() == QtCore.Qt.RightButton and self.board.boardObjects[x][y]: #Picking up an object o = self.board.boardObjects[x][y] f = False if self.myActiveClix: f = self.board.boardFigures[self.myActiveClix[0]][self.myActiveClix[1]] if o and o.canBePickedUp() and f: b = f.takeObject(o) if b: self.board.updateGL() elif isinstance(o, ObjectSimpleSquare): if o.type == "barrier": o.type = "debris" if f: self.board.log( "Me", f.getName() + " destroys a square of blocking terrain." ) else: self.board.log( "Me", "Destroyed a square of blocking terrain.") else: self.board.boardObjects[x][y] = False self.board.log( "Me", "Removed a square of "+o.type+" terrain.") self.board.updateGL() elif event.button() == QtCore.Qt.RightButton and self.board.boardFigures[x][y] and self.board.boardFigures[x][y].hasObject() and self.board.boardFigures[x][y].mine: #Dropping an object f = self.board.boardFigures[x][y] f.dropObject() self.myActiveClix = (x, y) self.board.updateGL() elif (self.ui.cmdBarrier.isChecked() or self.ui.cmdSmokeCloud.isChecked() or self.ui.cmdDebris.isChecked() or self.ui.cmdSpecial.isChecked()) and not self.board.boardObjects[x][y]: if self.ui.cmdBarrier.isChecked(): type = "barrier" elif self.ui.cmdSmokeCloud.isChecked(): type = "smoke cloud" elif self.ui.cmdDebris.isChecked(): type = "debris" elif self.ui.cmdSpecial.isChecked(): type = "special" b = ObjectSimpleSquare(self.board, type) self.board.boardObjects[x][y] = b b.x = x b.y = y self.board.log( "Me", "Placed a "+type+" token." ) self.board.updateGL() else: if ( self.board.boardFigures[x][y] and not self.board.modeObject ): f = self.board.boardFigures[x][y] self.board.moving = True self.board.moveOriginX = self.board.moveDestinationX = x self.board.moveOriginY = self.board.moveDestinationY = y #self.board.clearMyActive() if f.mine: self.board.clearActive(1) self.myActiveClix = (x, y) f.active = 1 self.redrawMyDial() else: self.board.clearActive(2) self.theirActiveClix = (x, y) f.active = 2 self.redrawTheirDial() elif self.board.boardObjects[x][y]: self.board.moving = True self.board.modeObject = True self.board.moveOriginX = self.board.moveDestinationX = x self.board.moveOriginY = self.board.moveDestinationY = y self.activeObject = (x, y) self.redrawMyDial() elif self.ui.cmdLOF.isChecked(): self.board.moving = True self.board.moveOriginX = self.board.moveDestinationX = x self.board.moveOriginY = self.board.moveDestinationY = y def redrawMyDial(self): if self.board.modeObject: f = self.board.boardObjects[self.activeObject[0]][self.activeObject[1]] else: f = self.board.boardFigures[self.myActiveClix[0]][self.myActiveClix[1]] if f: png = f.drawDial() if png: pixmap = QtGui.QPixmap() pixmap.loadFromData(png, "PNG") ui.myDial.setPixmap( pixmap ) ui.myDial.update() def redrawTheirDial(self): f = self.board.boardFigures[self.theirActiveClix[0]][self.theirActiveClix[1]] pixmap = QtGui.QPixmap() pixmap.loadFromData(f.drawDial(), "PNG") ui.theirDial.setPixmap( pixmap ) ui.theirDial.update() def doubleClickMap(self, event): x, y = self.getBoardXY(event) #print "X %s Y %s aX %s aY %s vD %s Xoffset %s Yoffset %s Zoffset %s" % ( x, y, self.board.view_angle_x, self.board.view_angle_y, self.board.view_distance, self.board.x_pos, self.board.y_pos, self.board.z_pos ) # if ( x >= 0 and x <= 23 and y >= 0 and y <= 23 ): # f = self.board.boardFigures[x][y] # if f: # f.damage() # self.redrawMyDial() return def moveMap(self, event): x, y = self.getBoardXY(event) if ( x >= 0 and x <= 23 and y >= 0 and y <= 23 ): if self.board.moving and ( (self.lastX == False and self.lastY == False ) or (self.lastX != x or self.lastY != y ) ) and event.x() > 0 and event.y() > 0: self.board.moveDestinationX = x self.board.moveDestinationY = y self.lastX = x self.lastY = y if self.board.modeObject: f = self.board.boardObjects[self.board.moveOriginX][self.board.moveOriginY] else: f = self.board.boardFigures[self.board.moveOriginX][self.board.moveOriginY] delta = abs( x - self.board.moveOriginX ) dY = abs( y - self.board.moveOriginY ) if dY > delta: delta = dY if self.board.modeLOF: self.ui.glFrame.setTitle( "LOF "+str(delta)+" space(s)..." ) else: self.ui.glFrame.setTitle( "Moving "+f.getName()+" "+str(delta)+" space(s)..." ) #print self.board.moveDestinationX, self.board.moveDestinationY self.board.updateGL() def stopMoving(self, event): if self.board.moving and not self.ui.cmdLOF.isChecked(): x, y = self.getBoardXY(event) doMove = True if not self.board.modeObject: f = self.board.boardFigures[self.board.moveOriginX][self.board.moveOriginY] if self.board.boardFigures[self.board.moveDestinationX][self.board.moveDestinationY]: doMove = False if f and not f.mine: doMove = False else: if self.board.boardObjects[self.board.moveDestinationX][self.board.moveDestinationY]: doMove = False f = self.board.boardObjects[self.board.moveOriginX][self.board.moveOriginY] if doMove: f.x = self.board.moveDestinationX f.y = self.board.moveDestinationY if f and f.mine: self.myActiveClix = (self.board.moveDestinationX, self.board.moveDestinationY) self.board.moveSelectedFigure() self.ui.glFrame.setTitle( " " ) self.board.moving = False if self.board.modeObject: if not self.ui.cmdObj.isChecked(): self.board.modeObject = False self.board.updateGL() def zoomMap(self, event): if (event.orientation() == QtCore.Qt.Vertical): #new_distance = self.board.view_distance + (float(event.delta()) / 8 / 15) #if ( new_distance > 0.05 and new_distance < 1 ): # self.board.view_distance = new_distance # self.board.updateGL() new_distance = self.board.z_pos + float(event.delta()) / 8 if new_distance >= 0 and new_distance <= 40: self.board.z_pos = new_distance self.board.updateGL() return QtGui.QMainWindow.wheelEvent(self.MainWindow, event) def test(self,event): #print event.key() if event.key() == QtCore.Qt.Key_Up and self.board.view_angle_x < 90: self.board.view_angle_x += 1.0 self.board.updateGL() elif event.key() == QtCore.Qt.Key_Down and self.board.view_angle_x > 20: self.board.view_angle_x -= 1.0 self.board.updateGL() elif event.key() == QtCore.Qt.Key_Left: self.board.view_angle_y += 1.0 self.board.updateGL() elif event.key() == QtCore.Qt.Key_Right: self.board.view_angle_y -= 1.0 self.board.updateGL() elif event.key() == 87: self.board.y_pos += 1.0 self.board.updateGL() elif event.key() == 83: self.board.y_pos -= 1.0 self.board.updateGL() elif event.key() == 65: self.board.x_pos -= 1.0 self.board.updateGL() elif event.key() == 68: self.board.x_pos += 1.0 self.board.updateGL() elif event.key() == 81: self.board.z_pos -= 1.0 self.board.updateGL() elif event.key() == 69: self.board.z_pos += 1.0 self.board.updateGL() elif event.key() == 48: self.board.z_pos = 0.0 self.board.y_pos = 0.0 self.board.x_pos = 0.0 self.board.view_angle_x = 90 self.board.view_angle_y = 0 self.board.view_distance = 1 self.board.updateGL() ''' if keystate[K_UP] and view_angle_x < 90: view_angle_x += 1.0 if keystate[K_DOWN] and view_angle_x > 0: view_angle_x -= 1.0 if keystate[K_LEFT]: view_angle_y += 1.0 if keystate[K_RIGHT]: view_angle_y -= 1.0 if keystate[K_PAGEUP] and view_distance < 2.0: view_distance += .03 if keystate[K_PAGEDOWN] and view_distance > 0.5: view_distance -= .03 if keystate[K_END]: view_distance = 1.0; view_angle_y = 0.0; view_angle_x = 90.0 ''' else: return QtGui.QMainWindow.keyPressEvent(self.MainWindow, event) def barrier(self, event): if not self.ui.cmdBarrier.isChecked(): self.clearOtherToggles( self.ui.cmdBarrier ) self.ui.glFrame.setTitle( "Click a square with no figure in it to add a barrier token" ) else: self.ui.glFrame.setTitle( " " ) return QtGui.QPushButton.mousePressEvent(self.ui.cmdBarrier, event) def smokeCloud(self, event): if not self.ui.cmdSmokeCloud.isChecked(): self.clearOtherToggles( self.ui.cmdSmokeCloud ) self.ui.glFrame.setTitle( "Click a square with no figure in it to add a smoke cloud token" ) else: self.ui.glFrame.setTitle( " " ) return QtGui.QPushButton.mousePressEvent(self.ui.cmdSmokeCloud, event) def debris(self, event): if not self.ui.cmdDebris.isChecked(): self.clearOtherToggles( self.ui.cmdDebris ) self.ui.glFrame.setTitle( "Click a square with no figure in it to add a debris token" ) else: self.ui.glFrame.setTitle( " " ) return QtGui.QPushButton.mousePressEvent(self.ui.cmdDebris, event) def special(self, event): if not self.ui.cmdSpecial.isChecked(): self.clearOtherToggles( self.ui.cmdSpecial ) self.ui.glFrame.setTitle( "Click a square with no figure in it to add a special token" ) else: self.ui.glFrame.setTitle( " " ) return QtGui.QPushButton.mousePressEvent(self.ui.cmdSpecial, event) #print self.board.x_pos, self.board.y_pos, self.board.z_pos, self.board.view_angle_x, self.board.view_angle_y, self.board.view_distance def clearOtherToggles(self, button): if button != self.ui.cmdBarrier: self.ui.cmdBarrier.setChecked( False ) if button != self.ui.cmdSmokeCloud: self.ui.cmdSmokeCloud.setChecked( False ) if button != self.ui.cmdDebris: self.ui.cmdDebris.setChecked( False ) if button != self.ui.cmdSpecial: self.ui.cmdSpecial.setChecked( False ) if button != self.ui.cmdLOF: self.ui.cmdLOF.setChecked( False ) self.board.modeLOF = False self.board.moving = False self.board.updateGL() if button != self.ui.cmdObj: self.ui.cmdObj.setChecked( False ) self.board.modeObject = False
def loadSave(): load_dict = pickle.load(open("save.p", "rb")) # --- Player --- # # First reset old position to -> " " GameBoard.theBoard[PlayerClass.char.position] = " " # Now the position is updated PlayerClass.char.position = load_dict['player_pos'] # Now place the player GameBoard.theBoard[PlayerClass.char.position] = PlayerClass.char.name PlayerClass.char.inventory = load_dict['player_inventory'] PlayerClass.char.equipped_items = load_dict['player_eq'] PlayerClass.char.hp = load_dict['player_hp'] PlayerClass.char.gold = load_dict['player_gold'] PlayerClass.char.xp = load_dict['player_xp'] PlayerClass.char.lvl = load_dict['player_lvl'] PlayerClass.char.defence = load_dict['player_def'] PlayerClass.char.strength = load_dict['player_str'] PlayerClass.char.dexterity = load_dict['player_dex'] PlayerClass.char.intelligence = load_dict['player_int'] PlayerClass.char.magic = load_dict['player_mag'] PlayerClass.char.race = load_dict['player_race'] PlayerClass.char.race_type = load_dict['player_type'] # --- NPC --- # # Set Found NPCClass.the_trader.found = load_dict['trader_found'] NPCClass.the_healer.found = load_dict['healer_found'] NPCClass.the_blacksmith.found = load_dict['blacksmith_found'] NPCClass.the_wizard.found = load_dict['wizard_found'] # Now the position is updated NPCClass.the_trader.position = load_dict['trader_pos'] NPCClass.the_wizard.position = load_dict['wizard_pos'] NPCClass.the_blacksmith.position = load_dict['blacksmith_pos'] NPCClass.the_healer.position = load_dict['healer_pos'] NPCClass.the_wizard.found = load_dict['wizard_found'] NPCClass.the_wizard.position = load_dict['wizard_pos'] # --- Monsters --- # MonsterClass.army_of_orcs = [] # Separate all monsters for i in range(1, 10): loaded = load_dict[f'monster{i}'] MonsterClass.army_of_orcs += [ MonsterClass.Monster("Bald Orc", "m", loaded.position, " ", loaded.found, loaded.hp, 32, 2, loaded.defeated, MonsterClass.gen_orc_gold(), 49) ] # Place saved monsters on the board for monster in MonsterClass.army_of_orcs: if monster.found: GameBoard.theBoard[monster.position] = monster.symbol else: GameBoard.theBoard[monster.position] = monster.hidden # --- Items --- # # First reset on_board_items ItemClass.on_board_items = [] GameBoard.theBoard[ItemClass.leather_cap.position] = " " # If item is already found, pass, else add the item to on_board_items, replace on the board and make hidden for i in load_dict['board_items']: if not i.found: ItemClass.on_board_items.append(i) GameBoard.theBoard[i.position] = i.hidden # First check encounters, then draw the board accordingly and finally run gameAction for the player to start. checkEncounters() GameBoard.draw_board(GameBoard.theBoard) gameAction()
class Test(unittest.TestCase): ### STACK TESTS def testAddToStack(self): someCards = [Card(25, 6), Card(30, 7), Card(7, 3), Card(66, 2)] aStack = Stack(Card(25, 6)) aStack.addToStack(Card(30, 7)) aStack.addToStack(Card(7, 3)) aStack.addToStack(Card(66, 2)) self.assertEqual(someCards[3].faceValue, aStack.cards[3].faceValue) def testGetBullPoints(self): aStack = Stack(Card(25, 6)) aStack.addToStack(Card(30, 7)) aStack.addToStack(Card(7, 3)) aStack.addToStack(Card(66, 2)) self.assertEqual(18, aStack.getBullPoints()) def testGetNumCards(self): aStack = Stack(Card(25, 6)) aStack.addToStack(Card(30, 7)) aStack.addToStack(Card(7, 3)) aStack.addToStack(Card(66, 2)) self.assertEqual(4, aStack.getNumCards()) def testGetTopCard(self): aStack = Stack(Card(25, 6)) aStack.addToStack(Card(30, 7)) aStack.addToStack(Card(7, 3)) aStack.addToStack(Card(66, 2)) self.assertEqual(66, aStack.getTopCard().faceValue) ### GAMEBOARD TESTS 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 testPlaceCards(self): player0 = Player(0) player1 = Player(1) player2 = Player(2) player3 = Player(3) selections = [(player0, Card(7, 3)), (player1, Card(20, 4)), (player2, Card(18, 1)), (player3, Card(3, 6))] # First test round for this function self.initializeGameBoard() self.gameBoard.placeCards(selections) self.assertEquals(self.gameBoard.stacks[0], Stack(Card(67, 5))) self.assertEquals(self.gameBoard.stacks[1], Stack(Card(87, 4))) self.assertEquals(self.gameBoard.stacks[2], Stack(Card(75, 7))) self.assertEquals(self.gameBoard.stacks[3].getTopCard(), Card(20, 4)) # Second test round secondSelections = [(player0, Card(62, 3)), (player1, Card(63, 4)), (player2, Card(69, 1)), (player3, Card(70, 6))] self.gameBoard.placeCards(secondSelections) self.assertEquals(self.gameBoard.stacks[0].getTopCard(), Card(70, 6)) self.assertEquals(self.gameBoard.stacks[0].getNumCards(), 3) self.assertEquals(self.gameBoard.stacks[1].getTopCard(), Card(87, 4)) self.assertEquals(self.gameBoard.stacks[1].getNumCards(), 1) self.assertEquals(self.gameBoard.stacks[2].getTopCard(), Card(75, 7)) self.assertEquals(self.gameBoard.stacks[2].getNumCards(), 1) self.assertEquals(self.gameBoard.stacks[3].getTopCard(), Card(63, 4)) # A patch that allows stacks to have 6 cards will cause this test to # change if the patch is applied, so we leave it out. # self.assertEquals(self.gameBoard.stacks[3].getNumCards(), 1) def testClearStack(self): self.initializeGameBoard() self.gameBoard.stacks[0].addToStack(Card(30, 7)) self.gameBoard.stacks[0].addToStack(Card(7, 3)) self.gameBoard.stacks[0].addToStack(Card(66, 2)) player1 = Player(1) self.gameBoard.clearStack(player1, Card(32, 3), 0) stackResult = Stack(Card(32, 3)) self.assertEquals(stackResult, self.gameBoard.stacks[0]) self.assertEquals(player1.bullPoints, 17) def testIsSmallerThanAllTopCards(self): someCards = [Stack(Card(25, 6)), Stack(Card(30, 7)), Stack(Card(7, 3)), Stack(Card(66, 2))] board = GameBoard(someCards) self.assertTrue(board.isSmallerThanAllTopCards(Card(3, 3))) self.assertFalse(board.isSmallerThanAllTopCards(Card(88, 3))) self.assertFalse(board.isSmallerThanAllTopCards(Card(50, 3))) def testFindClosestTopCard(self): someCards = [Stack(Card(25, 6)), Stack(Card(30, 7)), Stack(Card(7, 3)), Stack(Card(66, 2))] board = GameBoard(someCards) self.assertEqual(0, board.findClosestTopCard(Card(29, 3))) self.assertEqual(-1, board.findClosestTopCard(Card(6, 3))) # should never be smaller # PLAYER TESTS def testChooseCard(self): self.initializeGameBoard() player1 = Player(1) player1.cards = [Card(25, 2), Card(54, 5), Card(79, 1), Card(17, 6), Card(20, 3)] bestCard = player1.chooseCard(self.gameBoard) # Since a Player's strategy can can be altered with a patch, we leave this test out for now # until we abstract a strategy # self.assertEquals(bestCard, Card(79, 1)) self.assertEquals(len(player1.cards), 4) def testChooseStack(self): self.initializeGameBoard() self.gameBoard.stacks[0].addToStack(Card(25, 4)) self.gameBoard.stacks[0].addToStack(Card(25, 3)) self.gameBoard.stacks[0].addToStack(Card(25, 2)) self.gameBoard.stacks[1].addToStack(Card(25, 6)) self.gameBoard.stacks[2].addToStack(Card(25, 5)) self.gameBoard.stacks[2].addToStack(Card(25, 7)) player1 = Player(1) self.assertEquals(player1.chooseStack(self.gameBoard.stacks), 3) def testAddBullPoints(self): player1 = Player(1) player1.bullPoints = 7 player1.addBullPoints(8) self.assertEquals(15, player1.bullPoints) # DEALER TESTS def testDealTenToEach(self): dealer = Dealer([Player(0), Player(1), Player(2), Player(3)]) # A patch changes function name, so when patch is applied, test needs to change # dealer.dealTenToEach([0, 1, 2, 3]) # for player in dealer.players: # self.assertEquals(len(player.cards), 10) def testFindWinner(self): dealer = Dealer([Player(0), Player(1), Player(2), Player(3)]) self.assertEquals(dealer.findWinner(), -1) dealer.players[1].addBullPoints(66) self.assertEquals(dealer.findWinner(), 1) dealer.players[1].addBullPoints(-1) self.assertEquals(dealer.findWinner(), -1) dealer.players[3].addBullPoints(71) self.assertEquals(dealer.findWinner(), 3)
def main(): pygame.init() height = 620 width = height / 16 * 9 screen = pygame.display.set_mode((width, height)) font = pygame.font.Font(pygame.font.get_default_font(), 30) running = True elapsed_time = 0 clock = pygame.time.Clock() current_block = Block(0, 5, 10) board = GameBoard(width, height) while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False break if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: current_block.y_pos += 1 if event.key == pygame.K_LEFT: if current_block.x_pos > 0: current_block.x_pos -= 1 if event.key == pygame.K_RIGHT: if current_block.x_pos + current_block.block_width < board.grid_width: current_block.x_pos += 1 if event.key == pygame.K_UP: current_block.rotate() if current_block.finished: board.add_block(current_block) current_block = Block(random.randint(0, 3), 0, 0) dt = clock.tick() elapsed_time += dt if elapsed_time > 500: elapsed_time = 0 if current_block.frozen: current_block.finished = True current_block.y_pos += 1 board.check_if_scored() board.update_board() board.update_block(current_block) board.render() screen.blit(board.display, (0, 0)) screen.blit(font.render(str(board.score), True, (255, 255, 255)), (280, 30)) pygame.display.flip()
def _get_valid_moves(self, previous_board_int, board_int, piece_type): moves = GameBoard.get_valid_moves(previous_board_int, board_int, piece_type) return moves
def setupGame(characterPicked, data): data.time = 0 data.numOfPlayers = 6 data.characterPicked = characterPicked #todo data.current = data.numOfPlayers-1 #index in player order of current player data.currentSuggestion = None #todo data.disproveCount = None #who is disproving data.humanCanDisprove = False #if the human can disprove it data.shown = None data.nextTurn = False #wait before going to next turn data.selectedToShow = None data.tellHumanToShow = False data.humanMoved = False data.pBeingMoved = False #person moved to another room data.winner = None data.disproved = True #initial locations: (by index in player order) data.locations = [(23,7), (17,0), (0,9), (0,14), (6,23), (19,23)] data.checklist = Checklist(data) data.board = GameBoard(data) data.boardMap = BoardMap(data) data.buttons = Buttons(data) data.roll = 6 data.rolled = False #hooman hasn't rolled yet data.moved = False data.gameStarted = False data.losers = [] data.selectedCharac = None #for accusations data.selectedWeapon = None data.selectedRoom = None numCardsPerPlayer = data.numOfCards//data.numOfPlayers usedCards = [] #cards that have been assigned #places cards in envelope: 'solution' envelope = placingInEnvelope(data) data.solution = envelope usedCards += envelope print(data.solution) data.human = Human(data, characterPicked) #initializing 5 AI players: data.p1 = AIPlayer(data, 1) data.p2 = AIPlayer(data, 2) data.p3 = AIPlayer(data, 3) data.p4 = AIPlayer(data, 4) data.p5 = AIPlayer(data, 5) order = [data.p1, data.p2, data.p3, data.p4, data.p5] data.playerOrder = order[:characterPicked] + [data.human] + order[characterPicked:] #they go in that order for player in data.playerOrder: Cards = randomAssignment(usedCards,numCardsPerPlayer,data.numOfCards) usedCards += Cards[0] player.inputInitialInfo(data, Cards[1]) i = data.playerOrder.index(player) player.setInitialLocation(data, data.locations[i][0], data.locations[i][1]) #gives different cards to each one data.img1 = PhotoImage(file = "imagesGIF\%d.gif" %data.human.cards[0]) data.img2 = PhotoImage(file = "imagesGIF\%d.gif" %data.human.cards[1]) data.img3 = PhotoImage(file = "imagesGIF\%d.gif" %data.human.cards[2]) data.cardImgs = [data.img1, data.img2, data.img3]
import random import GameBoard import Player import Computer #GAMEPLAY DESIGN Continue_Game = True Game = GameBoard.Generate_Game() #Loop Till Winner Is Found while (Continue_Game == True): #Player Move Player.Player_Move(Game) #Constant Check For Winning Condition if (GameBoard.If_Win(Game) == True): print("Player Wins!") break #Computer Move Computer.Computer_Move(Game, Computer.NimSum_Cal(Game)) #Constant Check For Winning Condition if (GameBoard.If_Win(Game) == True): print("Computer Wins!") break
def _min(self, previous_board, board, previous_action, depth, alpha, beta): opponent = 3 - self.piece_type # check history table if self._encode_state(board) in self.history: return self.history[self._encode_state(board)] # check game result """ if game_board.game_end(previous_board, board, previous_action): result = game_board.judge_winner(board) if result == opponent: # win return float("inf"), None elif result == 0: # will not happen return DRAW_REWARD, None else: # lose return float("-inf"), None """ valid_moves = [] for i in range(5): for j in range(5): if GameBoard.valid_place_check(previous_board, board, i, j, opponent, test_check=True): valid_moves.append((i, j)) if not valid_moves: # TODO: handle no valid move, or pass return 0, "PASS" # random.shuffle(valid_moves) if depth < 1: best_value, action = float("-inf"), None for move in valid_moves: value = self._evaluate(board, opponent, move) if value > best_value: best_value, action = value, move self.history[self._encode_state(board)] = (best_value, action) if self.debug: print(" in min end") print(self._visualize_evaluation(board, opponent)) print(" give max {} with score {}".format( action, best_value)) return best_value, action best_value, action = float("inf"), None chosen_board = None for i, j in valid_moves: new_previous_board = deepcopy(board) # impossible to be unsuccessful new_board, success = GameBoard.place_chess(previous_board, board, i, j, opponent) value, a = self._max(new_previous_board, new_board, previous_action, depth - 1, alpha, beta) if value < best_value or action is None: # first action or find smaller value best_value, action = value, (i, j) self.history[self._encode_state(board)] = (best_value, action) chosen_board = new_board # best_value = min(beta, best_value) beta = min(beta, best_value) if beta <= alpha: break if self.debug: print(" in min") print(self._visualize_evaluation(board, opponent)) print(" give max {} with score {}".format(action, best_value)) return best_value, action
print "Fail! Tile [%d,%d] is already taken!" % (legalMovesList.prevX, legalMovesList.prevY) #Log the move into the gameboard GameBoard.takeTile(self.bestMoveX, self.bestMoveY, self.marker) class RandomAi(Ai): #======================================================================= # Functions #======================================================================= def takeDumbMove(self): move = random.randint(0, legalMovesList.legalMovesAvailable - 1) self.takeMove(move) class MidAi(Ai): #======================================================================= # Functions #======================================================================= def takeDumbMove(self): move = legalMovesList.legalMovesAvailable / 2 self.takeMove(move) #======================================================================= # Debug Main #======================================================================= if isDebugMode == True: while legalMovesList.legalMovesAvailable > 0: i = i + 1 takeDumbMove() #can use i for debugging GameBoard.printMatrix(freeTiles)