def set_players(self): self.player1 = Players.Player(self.left + 2, (self.max_height - 1) * self.cell_size + self.top + 2, 1, self.players_sprites) self.player2 = Players.Player( (self.max_width - 1) * self.cell_size + self.left + 2, self.top + 2, 2, self.players_sprites)
def xPlyMaxn(gamestate, depth, maxdepth, max_score): """Return result of x-ply maxn search for best outcome.""" print("xPlyMaxn previewing:") print(gamestate.board) if depth == maxdepth or gamestate.isTerminal(): print("terminal/reached depth limit") return Players.utility(gamestate) else: color = gamestate.turn children = Players.expand(gamestate) if len(children) != 0: max_val = [-100, -100, -100, -100] for child in children: print("testing their move") score = xPlyMaxn(child, depth + 1, maxdepth, max_score) if score[color - 1] == max_score: print("pruning") return score if score[color - 1] > max_val[color - 1]: max_val = score return max_val else: child = gamestate.duplicate() child.update(list()) return xPlyMaxn(child, depth + 1, maxdepth, max_score)
def main(): #initializing game objects sprite_obj = Sprites.Sprites() player_obj = Players.Player() asteroids_obj = Players.Asteroids() event_handler_obj = AsteroidsGame.Event_Handler(player_obj) draw_handler_obj = AsteroidsGame.Draw_Handler(sprite_obj, player_obj, asteroids_obj) state = 'blank screen' while event_handler_obj['running']: for event in pygame.event.get(): ''' instead of having a huge number of if-branches to assess the events, maybe we can pass the event to an event handler which returns a dictionary/hash table that describes the state of the game/player (i.e. {game_state: True, player_health: 100, etc...}) ''' event_handler_obj.action(event, draw_handler_obj) draw_handler_obj[''] pygame.display.flip() pygame.quit()
def maxn(gamestate, max_score): """Return result of maxn search for best outcome.""" # If gamestate is terminal, return vector of utility if gamestate.isTerminal(): return Players.utility(gamestate) else: # Expand to list of child gamestates; do maxn on each and find max color = gamestate.turn children = Players.expand(gamestate) if len(children) != 0: max_val = [-100, -100, -100, -100] for child in children: score = maxn(child, max_score) # If a child has the best possible score for a player, # prune immediately and disregard other children if score[color - 1] == max_score: return score if score[color - 1] > max_val[color - 1]: max_val = score return max_val else: # If no moves are possible but gamestate is not terminal, # simply pass new_gamestate = gamestate.duplicate() new_gamestate.update(list()) return maxn(new_gamestate, max_score)
def set_teams(players: List[pl.Player]): while True: teams.clear() try: aux = input(colors['white'] + 'Which members of team A: ').split() if len(aux) == len(players) / 2: teamA = [] teamB = players for a in aux: teamA.append(pl.search_player(a, players)) teamB.remove(pl.search_player(a, players)) if len(teamA) != len(teamB): raise ValueError( "Teams do not have the same number of players") teams.append(pl.Team(teamA)) teams.append(pl.Team(teamB)) print(teams[0].__str__()) if input('Reverse? ') == 'y': teams[0].reverse() pass print(teams[1].__str__()) if input('Reverse? ') == 'y': teams[1].reverse() pass return None except ValueError: print(colors['red'] + 'Teams do not have the same number of players')
def walk_all_the_way_to(pos): while distance(Players.get_local().position, pos) > 10: if Movement.get_run_energy() > 30 and not Movement.is_run_enabled(): Movement.toggle_run(True) Movement.walk_to(pos) time.sleep(1) sleep_until(lambda: not Players.get_local().is_moving)
def antwoordcorrect(): global Ent_vraag basic.screen.blit(correct, (1065, 260)) pygame.display.flip() correctsound.play() pygame.time.delay(1500) Entvragen.remove(Ent_vraag) Players.player_game(2) ## <- HIER TOEGEVOEDD [VERWIJDER COMMENT] pygame.time.delay(3000)
def __init__(self, pm=PlayerManager([Players.Player("White", []), Players.Player("Black", [])])): # Declarations self.board = [] self.moves_made = [] self.PM = pm # Player Manager self.PLAYERS = pm.get_players() self.PIECE_DIRECTIONS = {f"{self.PLAYERS[0].get_color()}": 1, f"{self.PLAYERS[1].get_color()}": -1} # Downwards is 1 and Upwards is -1 self.current_player = self.PLAYERS[0] # Main self.move_able = {} self.new_board() self.set_start_pieces() self.selected_piece = None
def TimeEvent(): global race_info # update effect status for player in players: Players.handleEffects(player) diff = (datetime.now() - start_time) race_info.Time = diff.seconds * 1000 + diff.microseconds / 1000 sender.sendUpdate(race_info, "RaceInfo") if not shutdown: timer = Timer(0.1, TimeEvent) timer.start()
class Game(): def __init__(self, amountOfPlayers, amountOfDecks): self.players = Players(amountOfPlayers) self.deck=Deck(amount=amountOfDecks) self.playedDeck=Deck() self.activePlayer=self.players.GetCurrentValue() #Clears the CL. def ClearScreen(self): os.system("cls") #Sets up the starting conditions of the game. (7 cards for each player and 1 played card) def SetStartConditions(self): for i in range(7): while(not self.players.Empty()): self.players.GetCurrentValue().DrawCard(self.deck.DrawCard()) self.players.Next() self.players.Reset() self.playedDeck.AddExistingNode(self.deck.DrawCard()) #TODO Prints the basic ui. def PrintBase(self): #Change the type, not the string... lastCard="Change me" print("Last played card: " + lastCard.ToString()) print("Active player: "+self.activePlayer.name) print("Your hand: ") self.activePlayer.hand.PrintHand() #TODO Defines player actions. def PlayerAction(self): x= input("enter to continue") self.ClearScreen() #TODO Switches the active player to the next player in the list. def SwitchTurn(self): self.players.Next() #If what? if(): self.players.Reset() self.activePlayer=self.players.GetCurrentValue() input("switch to player {}. Press enter to continue".format(self.activePlayer.name)) #TODO Basic gameloop. def GameLoop(self): while(True): self.PrintBase() self.PlayerAction() self.SwitchTurn() #TODO Game "Run" function. def Run(self): self.RandomizePlayerOrder() self.SetStartConditions() self.GameLoop() #TODO Randomize the player order. def RandomizePlayerOrder(self): pass
def run(self): if self.currentscene.__name__ == "Menu": self.currentscene = self.currentscene.gm.run() if self.currentscene == "Start": self.currentscene = Players.main() elif self.currentscene == "Instructions": self.currentscene = Instruction_menu.gm.run() elif self.currentscene == "Highscore": self.currentscene = Highscores.gm.run() #print('placeholder') elif self.currentscene == "Settings": self.currentscene = Settings_menu.gm.run() elif self.currentscene == "Quit": self.quitgame() if self.currentscene[2] == "Game": self.currentscene = Game.mainloop(self.currentscene[0], self.currentscene[1]) if self.currentscene == "Back": self.currentscene = Menu if self.currentscene == "pause": self.safestate = self.currentscene self.currentscene = Pausemenu.gm.run() if self.currentscene == "Resume": self.currentscene = Game.mainloop() if self.currentscene == "Main menu": self.currentscene = Menu self.run()
def CreateActiveFoward(attributes): firstName = attributes[0] lastName = attributes[1] jerseyNum = attributes[2] height = attributes[3] draftYear = attributes[4] weight = attributes[5] college = attributes[6] points = attributes[7] rebounds = attributes[8] assists = attributes[9] ftpct = attributes[10] twoPtPct = attributes[11] threePtPCt = attributes[12] per = attributes[13] offRating = attributes[14] defRating = attributes[15] age = attributes[16] steals = attributes[17] turnovers = attributes[18] blocks = attributes[19] team = attributes[20] yearsExp = attributes[21] ActiveFoward = Players.ActiveForward(firstName, lastName, jerseyNum, height, draftYear, weight, college, points, rebounds, assists, ftpct, twoPtPct, threePtPCt, per, offRating, defRating, age, steals, turnovers, blocks, team, yearsExp) return ActiveFoward
def add_pirates(self, _name, _type): if _type == "mage" or _type == "3": _type = "mage" self.players.append(Players.Mage([_name, _type, self.player_count])) elif _type == "rogue" or _type == "1": _type = "rogue" self.players.append( Players.Rogue([_name, _type, self.player_count])) elif _type == "warrior" or _type == "2": _type = "warrior" self.players.append( Players.Warrior([_name, _type, self.player_count])) self.player_count = self.player_count + 1 print(_type + " pirate: " + _name + " has joined " + self.name + "'s band of merry pirates.\n")
def createPairing(size=C.teamsize): # Define player details, Name and handicap player_list = P.getPlayers() # Get player names only player_names = [entry['Name'] for entry in player_list] # Randomiz order of playrs random_player_list = np.random.permutation(player_names) # Find possible teams, and represent it in a number teams_list = itertools.combinations(random_player_list, size) t_list = list(teams_list) # Find non overlapping set of teams possible_pairings = _randomTeamCombination(t_list, len(player_list), size) result = [] for pairing in possible_pairings: entry = {} entry['players'] = pairing entry['hc'] = _getHandicapForPlayers(pairing, player_list) result.append(entry) return {'pairings': result}
def simulateWeightedGame(self): """Simulate a game with random moves weighted by piece size, and return utility vector outcome.""" print("Simulating weighted random game..") # Simulate game gamestate = self.gamestate.duplicate() while not gamestate.isTerminal(): moves = gamestate.listMoves() randMove = Players.weightedRandomMove(moves) gamestate.update(randMove) # Update playout and win count in self utility_vector = Players.utility(gamestate) self.updateStats(utility_vector) # Return utility vector for backpropagation return utility_vector
def __init__(self): self._board = Board.Board() self._red_player = Players.Player('red') self._blue_player = Players.Player('blue') self._game_over = False self._player_in_check = None self._turn = 'blue' self._captured_pieces = [] self._move_log = [] for i, piece in enumerate(self._red_player.get_player_pieces()): self._board.set_board(self._red_player.get_initial_placements()[i], piece) piece.set_location(self._red_player.get_initial_placements()[i]) for i, piece in enumerate(self._blue_player.get_player_pieces()): self._board.set_board( self._blue_player.get_initial_placements()[i], piece) piece.set_location(self._blue_player.get_initial_placements()[i])
def InitializePlayers(self, stacks, counts): if not stacks: stacks = [1000] * self.Nplayers if not counts: counts = [0] * self.Nplayers players = [] for i, (stack, count) in enumerate(zip(stacks, counts)): players.append(Players.Player(f'Player{i}', stack, count=count)) return players
def Game(decks, players): # Shuffle the given cards and give them all values card_translate = { "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10, "J": 10, "Q": 10, "K": 10, "A": 11 } cards = Functions.Shuffle(decks) while len(cards) > (players + 1) * 6: # Players play their turns gcards = [cards[0], cards[1]] del cards[0] del cards[0] player_1 = Players.Player(card_translate, 1, cards, gcards) # Deler's turn gcards = [cards[0], cards[1]] del cards[0] del cards[0] deler = Players.Deler(card_translate, cards, gcards) # For testing, write who won and lost if deler > player_1: print("Player 1 Lost") elif deler < player_1: print("Player 1 Won") else: print("Player 1 tied with the deiler") print( "----------------------------------------------------------------------------" )
def __init__(self): super(MainWindow, self).__init__() # Variables: self.game = Game.TicTacToe(Players.HumanPlayer(), Players.QPlayer()) self.game.returnMoveToGUI = self.drawMoveOnBoard self.game.signalGUItoReset = self.informUserGameEnded # Qt window self.setWindowTitle("Tic Tac Toe Game") self.buttongrid = QtWidgets.QWidget(self) self.setCentralWidget(self.buttongrid) self.frame = QtWidgets.QFrame(self.buttongrid) self.frame.setGeometry(QtCore.QRect(0, 0, 3*buttonWidth, int(3.5*buttonWidth))) self.frame.setFrameShape(QtWidgets.QFrame.NoFrame) self.frame.setFrameShadow(QtWidgets.QFrame.Plain) self.frame.setLineWidth(0) self.grid = QtWidgets.QGridLayout(self.frame) # Start a new game self.newGameButton = QtWidgets.QPushButton("New Game") self.newGameButton.setMinimumSize(QtCore.QSize(buttonWidth, 8)) self.newGameButton.clicked.connect(self.reset) self.grid.addWidget(self.newGameButton, 0, 0) # Find all player classes: playerClasses = [x for x in dir(Players) if isclass(getattr(Players, x)) and 'Player' in x and 'Basic' not in x and 'Brain' not in x] self.choosePlayerComboBox = QtWidgets.QComboBox() for player in playerClasses: self.choosePlayerComboBox.addItem(player) self.choosePlayerComboBox.setMinimumSize(QtCore.QSize(buttonWidth, 8)) self.choosePlayerComboBox.setCurrentIndex(0) self.choosePlayerComboBox.activated.connect(self.loadNewPlayer) self.grid.addWidget(self.choosePlayerComboBox, 0, 1) # Add game buttons for i in range(0,self.game._rows): for j in range(0, self.game._cols): newButton = TicTacToeButton((i,j), self.game.gameIsBusy, self.game.play, self.game.humanPlayerMoved) newButton.setFont(QtGui.QFont('Helvetica', 60)) self.grid.addWidget(newButton, i+1, j) self.setGeometry(300, 300, 3*buttonWidth + 5, 3*buttonHeight + 60)
def assign_roles(self): print("assigning roles...") exe = [] for person in self.players: role = Players.assign_role(person) self.send(person, f"You are a {role.name}") self.roles[person] = role if role.name == "Executioner": exe.append(role) # give executioners their targets for e in exe: e.assign_target()
def __init__(self, filepath, w, h): self.data = {} replay = DecodeReplay(filepath) self.data["window"] = w, h self.data["replay"] = replay.data self.data["map"] = GenMap(replay.data) self.data["dynamic"] = DynamicElements(replay.data) self.data["players"] = Players(replay.data) h, w = self.data["map"].data["height"], self.data["map"].data["width"] self.data["height"], self.data["width"] = h, w self.data["follow"] = False self.data["end"] = float(replay.data["gameEndsAt"][0]) / 1000 self.ended = False
def get_player(player_type): players = { 'random': Players.RandomPlayer(), 'manual': Players.ManualPlayer(), 'monte_carlo': Players.MonteCarloPlayer(100), 'minimax': Players.MinimaxPlayer(4), 'en_masse': Players.EnMassePlayer(), 'flanking': Players.FlankingPlayer(), 'aggressive': Players.AggressivePlayer(), } return players[player_type]
def __init__(self, deck, Nplayers=1, players=None, stacks=None, counts=None): self.deck = deck self.ncards = len(self.deck) self.Nplayers = Nplayers self.players = players if not players: self.players = self.InitializePlayers(stacks, counts) self.nplayers = self.players self.dealer = Players.Dealer()
def expand(self): """Expand a random unvisited child from node, play out simulation, update stats, and return utility vector result.""" if self.gamestate.isTerminal(): utilityVector = Players.utility(self.gamestate) self.updateStats(utilityVector) return utilityVector unexplored_moves = self.gamestate.listMoves() for move, child in self.children.items(): try: unexplored_moves.remove(move) except ValueError: pdb.set_trace() print("Moves remaining:") print(unexplored_moves) print("Testing:") randMove = Players.weightedRandomMove(unexplored_moves) print(randMove) # Expand new_gamestate = self.gamestate.duplicate() new_gamestate.update(randMove) self.children[randMove] = MCNode(new_gamestate, parent=self) new_node = self.children[randMove] # Run simulation from new node sim_result = new_node.simulateWeightedGame() # Update own stats with this result self.updateStats(sim_result) # Update fullyExpanded if necessary if len(unexplored_moves) == 1: self.fullyExpanded = True # Return result of simulation (utility vector) for backpropagation return sim_result
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setWindowTitle("Main Window") self.player = Players.Player() explorer = FileSystemMediaExplorer("d:\\", self.rootContext, self.player) self.rootContext().setContextProperty('player', self.player) self.rootContext().setContextProperty('mediaListModel', explorer.MediaList) self.rootContext().setContextProperty('mediaExplorer', explorer) # Renders 'view.qml' self.setSource(QUrl.fromLocalFile('QML/main.qml')) # QML resizes to main window self.setResizeMode(QDeclarativeView.SizeRootObjectToView)
def maxn_getMove(gamestate, max_score): """Wrapper for maxn search - return result of search.""" color = gamestate.turn moves = gamestate.listMoves() children = Players.expandFromList(gamestate, moves) if len(children) != 0: max_val = -100 max_val_index = -1 for i in range(0, len(children)): score = maxn(children[i], max_score)[color - 1] if score == max_score: return moves[i] if score > max_val: max_val = score max_val_index = i return moves[max_val_index] else: return list()
def simulateGame(self): """Simulate a random game starting from this node, and return utility vector outcome.""" print("Simulating random game..") # Simulate game gamestate = self.gamestate.duplicate() while not gamestate.isTerminal(): moves = gamestate.listMoves() randMove = random.choice(moves) gamestate.update(randMove) # Update playout and win count in self utility_vector = Players.utility(gamestate) self.updateStats(utility_vector) # Return utility vector for backpropagation return utility_vector
def simulateGameWithFirstMoves(self): """Simulate a game where players pick first moves, and return utility vector outcome.""" print("Simulating game with first moves...") # Simulate game gamestate = self.gamestate.duplicate() while not gamestate.isTerminal(): move = gamestate.canMove() if not move == False: gamestate.update(move) else: gamestate.update('pass!') # Update playout and win count in self utility_vector = Players.utility(gamestate) self.updateStats(utility_vector) # Return utility vector for backpropagation return utility_vector
def playGame(startLevel, profiles): if startLevel == "VS": CONSTANTS["MODE"] = "VS" else: CONSTANTS["MODE"] = "MAIN" grid = Grid.Grid(startLevel) players = Players.Players(profiles) ballStruct = Balls.BallStruct() effects = Effects.EffectStruct() _done = False while not _done: for ev in pygame.event.get(): if ev.type == QUIT: players.forceQuit() return "QUIT" elif ev.type == KEYDOWN and ev.key == K_ESCAPE: players.forceQuit() return else: players.handleEvent(ev, grid, ballStruct) if grid.isDone(): return effects.update() grid.update(players, ballStruct, effects) ballStruct.update(grid, players, effects) players.update(grid, ballStruct) grid.drawMe() players.drawMe() effects.drawMe() ballStruct.drawMe() #pygame.draw.rect(getConst("SURFACE"), [255, 255, 255], [0, 0, getConst("SCREENSIZE")[0] - 1, getConst("SCREENSIZE")[1] - 1], 1) pygame.display.update() getConst("SURFACE").fill([0] * 3) pygame.time.Clock().tick(40)
def createActiveGuard(attributes): firstName = attributes[0] lastName = attributes[1] jerseyNum = attributes[2] height = attributes[3] draftYear = attributes[4] weight = attributes[5] college = attributes[6] points = attributes[7] assists = attributes[8] ftpct = attributes[9] twoPtPct = attributes[10] threePtPCt = attributes[11] per = attributes[12] offRating = attributes[13] defRating = attributes[14] age = attributes[15] steals = attributes[16] turnovers = attributes[17] yearsExp = attributes[18] team = attributes[19] activeGuard = Players.ActiveGuard(firstName, lastName, jerseyNum, height, draftYear, weight, college, points, assists, ftpct, twoPtPct, threePtPCt, per, offRating, defRating, age, steals, turnovers, yearsExp, team) return activeGuard
def CreateActiveCenter(attributes): firstName = attributes[0] lastName = attributes[1] jerseyNum = attributes[2] height = attributes[3] draftYear = attributes[4] weight = attributes[5] college = attributes[6] points = attributes[7] assists = attributes[8] ftpct = attributes[9] twoPtPct = attributes[10] threePtPCt = attributes[11] per = attributes[12] offRating = attributes[13] defRating = attributes[14] age = attributes[15] blocks = attributes[16] offRebounds = attributes[17] defRebounds =attributes[18] yearsExp = attributes[19] team = attributes[20] activeCenter = Players.ActiveCenter(firstName, lastName, jerseyNum, height, draftYear, weight, college, points, assists, ftpct, twoPtPct, threePtPCt, per, offRating, defRating, age, blocks, offRebounds, defRebounds, yearsExp, team) return activeCenter
def ControllerEvent(player, event, data, packet_id): global race_info global players global last_id global player_infos packet_id = int(packet_id) # did packet arrive in order? try: if packet_id < last_id: print "Discarding packet %d, last_received %d" % (packet_id, last_id) return except Exception as e: print e last_id = packet_id if (DEBUG and race_info.State != LAP_SELECT): try: print "Received controller event (Player %s State %d)" % (player, race_info.State) except Exception as e: print e player = int(player) #Bail if there's an invalid player if (player < 0 or player > Players.MAX_PLAYERS): if DEBUG: print "Invalid player, should be >= 0 and < %d" % Players.MAX_PLAYERS return event = int(event) data = int(data) #don't send a packet unless necessary send = False if race_info.State == JOINING: if DEBUG: print "Joining event=%d data=%d" % (event, data) # If player hasn't joined and pressed A, join them if event == BUT_A and data == 1 and players[player] == None: print "Player %d is now ready" % (player + 1) players[player] = Players.PlayerState() player_infos[player] = PlayerInfo(race_info.JoinedPlayers + 1) race_info.JoinedPlayers += 1 sender.sendUpdate(race_info, "RaceInfo") # If joined player presses start, begin lap count selection if event == START and data == 1 and players[player] != None: print "Starting with current players" race_info.State = LAP_SELECT sender.sendUpdate(race_info, "RaceInfo") # Ignoring all other input in this state elif DEBUG: print "Ignoring input until race begins" return elif race_info.State == LAP_SELECT: # If player pressed up, increase lap count if event == UD and data == -32767 or event == DUP and data == 1: race_info.Laps += 1 # If player pressed down, decrease lap count elif event == UD and data == 32767 or event == DDOWN and data == 1: race_info.Laps -= 1 # Ensure at least one lap if race_info.Laps < 1: race_info.Laps = 1 # If player pressed start, begin the countdown elif event == START and data == 1: race_info.State = COUNTDOWN sender.sendUpdate(race_info, "RaceInfo") print return # Erase the current line, and return to the beginning print "%s[2K\r" % chr(27), # Prompt for number of laps print "Please select number of Laps: %d" % race_info.Laps, # Force buffer to flush (needed because no newline terminating print) sys.stdout.flush() sender.sendUpdate(race_info, "RaceInfo") elif race_info.State == COUNTDOWN: return elif race_info.State == FINISHED: if event == START and data == 1: # reset all the players stats for pl in players: if pl != None: pl.init() race_info.State = JOINING race_info.Time = 0 sender.sendUpdate(race_info, "RaceInfo") return if (event == ACCEL): players[player].forward = data send = True if (event == BRAKE): players[player].reverse = data send = True if (event == LR): send = True # Parse xbox controller data if data == -32767: players[player].turn = -1 if data == 0: players[player].turn = 0 if data == 32767: players[player].turn = 1 print "Player turn", players[player].turn, player, player_infos player_infos[player].Turn == players[player].turn print player_infos[player].Turn print "updated" if event == BUT_A and data == 1 and players[player].powerup != None: # Player fired a powerup triggerPowerup(player) print "F: %d R: %d" % (players[player].forward, players[player].reverse) if send: print "Beginning of controller event" speed2 = players[player].forward - players[player].reverse #Deal with player effects Players.handleEffects(player) players[player].speed_percent = Players.DEFAULT_SPEED_PERCENT speed2 = int(speed2 * players[player].speed_percent) #enforce speed boundaries if (speed2 > Players.MAX_SPEED): speed2 = Players.MAX_SPEED if (speed2 < Players.MIN_SPEED): speed2 = Players.MIN_SPEED #update speed info for the GUI player_infos[player].Speed = speed * 100.0 / (MAX_SPEED * DEFAULT_SPEED_PERCENT) sender.sendUpdate(player_infos[player], "PlayerInfo" + str(player_infos[player].Number)) try: if (DEBUG): print "Player: %d, Speed=%d, Turn=%d" % (player, speed2, players[player].turn) sender.sendAsync("CarEvent", player=str(int(player_infos[player].Number)), speed=str(speed2), turn=str(players[player].turn)) if (DEBUG): print "Packet Sent" except Exception as e: print e