我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用game.Game()。
def __init__(self, playerCount): """ Initialisierung eines GameLogic Parameter: int die maximale Spieleranzahl Rückgabewerte: - """ threading.Thread.__init__(self) self.deamon = True self.queue = Queue.Queue(0) self.playerCount = playerCount self.playerConnectedCount = 0 self.players = [] self.weaponPositions = [] self.possibleWeaponPositions = ["140_110", "490_110", "420_300", "220_300", "060_300", "600_300", "420_550", "220_550", "090_490", "550_480", "600_170", "600_040", "350_050", "290_040", "050_180"] self.playerPositions = [] self.game = game.Game(self) self.MCAST_GRP = '224.1.1.1' self.MCAST_PORT = 5000 self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
def __init__(self, username: str, password: str, botModule: str, botconfig: Mapping, numPlayers: int, variant: Variant, spectators: bool, gameName: str, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.username: str = username self.password: str = password module = importlib.import_module(botModule + '.bot') self.botCls: Type[Bot] = module.Bot # type: ignore self.botconfig: Mapping = botconfig self.numPlayers: int = numPlayers self.variant: Variant = variant self.spectators: bool = spectators self.gameName: str = gameName self.conn: socketIO_client.SocketIO self.tablePlayers: List[str] = [] self.readyToStart: bool = False self.game: Optional[Game] = None
def message_sent(self, mtype, data): if mtype == 'game_start': pass elif mtype == 'init': self.game = Game(self.connection, Variant(data['variant']), data['names'], self.position, self.botcls, **self.botkwargs) self.bot = self.game.bot self.connection.game = self.game self.connection.bot = self.bot elif self.game is not None: if mtype == 'notify' and data['type'] == 'draw': card = TestCard(Suit(data['suit']), Rank(data['rank']), data['order']) self.deck[data['order']] = card self.game.received(mtype, data) elif mtype == 'notify' and data['type'] == 'reveal': pass elif mtype == 'action': pass else: print(mtype, data) raise Exception()
def reloop(): other.turns.player1_name = "" other.turns.player2_name = "" other.turns.player3_name = "" other.turns.player4_name = "" other.turns.player_count = 0 other.turns.playerz = [] other.turns.current_player = 0 other.turns.current_player_name = "" other.turns.match_started = False game.Game.ina = 0 game.Game.won = 0 other.questions.correct = 2 other.questions.player1_correct = 2 other.questions.player2_correct = 2 other.questions.player3_correct = 2 other.questions.player4_correct = 2 other.questions.pressed = False other.questions.dice_result = 1 for _ in dir(): if _[0]!='_': delattr(sys.modules[__name__], _) exec(open("MainMenuNew.py").read())
def check_valid_request(f): '''Decorator. Verifies game exists and client is authorized. Returns game and client''' @wraps(f) def wrapper(*args, **kwargs): try: game: Game = games[kwargs['game_id']] except KeyError: abort(400, util.error('Game does not exist')) try: player: Player = [player for player in game.players if player.token == request.cookies.get('tbg_token')][0] except IndexError: abort(400, util.error('Not authorized to view game')) return f(game, player) return wrapper
def create_new_game(): '''Creates new player and game, returns game id''' post_data: Dict = request.get_json() try: player: Player = Player(post_data['name']) except KeyError: abort(400, util.error('Name not supplied')) try: game_type: str = post_data['game_type'] except KeyError: abort(400, util.error('Game type not supplied')) if game_type not in ('public', 'private'): abort(400, util.error('Invalid game type parameter')) game: Game = Game(game_type) game.add_player(player) games[game.id] = game clients[player.token] = game.id response = make_response(jsonify({'game': game.id})) response.set_cookie('tbg_token', player.token, max_age=6000) return response
def test_in_check(self): player_points = {'w': 0, 'b': 0} # Initialized Board situation_a = Game() in_check(situation_a, player_points, 1) self.assertEqual(player_points['b'], 0, "Should not increment player_points when opponent not in check or checkmate") self.assertEqual(player_points['w'], 0, "Should not increment player_points when opponent not in check or checkmate") # Check situation situation_b = Game("rnbqkbnr/ppp2ppp/8/1B1pp3/3PP3/8/PPP2PPP/RNBQK1NR b KQkq - 1 3") in_check(situation_b, player_points, 1) self.assertEqual(player_points['b'], 0, "Should not increment player_points when opponent not in check or checkmate") self.assertEqual(player_points['w'], 1, "Should increment player_points when opponent is in check") # Checkmate situation situation_c = Game("r1bqkbnr/p1pppB1p/1pn2p2/6p1/8/1QP1P3/PP1P1PPP/RNB1K1NR b KQkq - 1 5") in_check(situation_c, player_points, 1) self.assertEqual(player_points['b'], 0, "Should not increment player_points when opponent not in check or checkmate") self.assertEqual(player_points['w'], float("inf"), "Should set player_points to infinity when opponent in checkmate")
def prompt_user(self): self.computer.print_board() while self.game.status < 2: user_move = raw_input("Make a move: ") while user_move not in self.game.get_moves() and user_move != "ff": user_move = raw_input("Please enter a valid move: ") if user_move == "ff": break; self.game.apply_move(user_move) start_time = time.time() self.computer.print_board() print("\nCalculating...\n") if self.game.status < 2: current_state = str(self.game) computer_move = self.computer.ab_make_move(current_state) PIECE_NAME = {'p': 'Pawn', 'b': 'Bishop', 'n': 'Knight', 'r': 'Rook', 'q': 'Queen', 'k': 'King'} print("Computer moved " + PIECE_NAME[self.game.board.get_piece(self.game.xy2i(computer_move[:2]))] + " at " + computer_move[:2] + " to " + computer_move[2:]) self.game.apply_move(computer_move) self.computer.print_board() print("Elapsed time in sec: {time}".format(time=time.time() - start_time)) user_move = raw_input("Game over. Play again? y/n: ") if user_move.lower() == "y": self.game = Game() self.computer.game = self.game self.prompt_user()
def get_heuristic(self, board_state=None): cache_parse = board_state.split(" ")[0] + " " + board_state.split(" ")[1] if board_state == None: board_state = str(self.game) if cache_parse in self.cache: self.found_in_cache += 1 return self.cache[cache_parse] clone = Game(board_state) total_points = 0 # total piece count total_points += heuristics.material(board_state, 100) total_points += heuristics.piece_moves(clone, 50) total_points += heuristics.in_check(clone, 1) total_points += heuristics.pawn_structure(board_state, 1) self.cache[cache_parse] = total_points return total_points
def on_status(self, status): rv = self.handle_play(status) if rv is False: # there's no need to force the game to end; it's already over self.save() return rv elif datetime.now() > self.end_at: self.tweet_image( 'Game over. The answer was {}.'.format(self.game.original), in_reply_to_status_id=self.initial_status_id, ) self.over = True self.save() return False else: self.save() return rv
def new_game(self, chat): """ Create a new game in this chat """ chat_id = chat.id self.logger.debug("Creating new game in chat " + str(chat_id)) game = Game(chat) if chat_id not in self.chatid_games: self.chatid_games[chat_id] = list() # remove old games for g in list(self.chatid_games[chat_id]): if not g.players: self.chatid_games[chat_id].remove(g) self.chatid_games[chat_id].append(game) return game
def main(): choice = '0' while choice not in 'kpq': choice = input('Knight or Princess? [k/p] ') if choice == 'q': print('Maybe you are braver next time!') return character = characters.Character(1000, 75, 'Knight', 'Roy') enemy = characters.Character(800, 100, 'Princess', 'Lisi') if choice == 'p': character, enemy = enemy, character print('You are {}. Your opponent is {}.'.format(character, enemy)) print('Are you ready to take the crown? Fight!') fight = game.Game(character, enemy) while fight.active(): attack = 'n' while attack not in 'ws': attack = input('\nWeak or Strong attack? [w/s] ') print(fight.fight(attack, random.choice('ws'))) print(fight.result())
def game_over(self): """ Determine if the game is over Used by the engine to determine when to finish the game. A game is over when there are no players remaining, or a single winner remaining. """ if len(self.remaining_players()) < 1: self.cutoff = 'extermination' return True elif len(self.remaining_players()) == 1: self.cutoff = 'lone survivor' return True elif self.game_won() == DRAW: self.cutoff = "Board full" return True elif self.game_won() != EMPTY: self.cutoff = "Game won" return True elif self.count_active() < 1: self.cutoff = "No more moves" return True else: return False
def main(): games = [] for fn in os.listdir('../ACPC'): if os.path.isfile('../ACPC/' + fn) and fn != '.DS_Store': print(fn) with open('../ACPC/' + fn) as f: counter = 0 for line in f: print(counter) counter += 1 print(line) this_game = game.Game(line, 50, 100) print(this_game.deepstack.moves) games.append(this_game) pickle.dump( games, open( "../games.p", "wb" ) )
def __init__(self, username: str, password: str, botModule: str, botconfig: Mapping, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.username: str = username self.password: str = password module = importlib.import_module(botModule + '.bot') self.botCls: Type[Bot] = module.Bot # type: ignore self.botconfig: Mapping = botconfig self.conn: socketIO_client.SocketIO self.game: Optional[Game] = None
def draw_card(self, player: int) -> None: if self.nextDraw >= len(self.deck): return card: ServerCard = self.deck[self.nextDraw] if card.status != CardStatus.Deck: raise GameException('Bad Card Status', card.status) card.player = player card.status = CardStatus.Hand p: Game info: dict for p in self.players: info = {'type': 'draw', 'who': player, 'order': self.nextDraw} if p.botPosition != player: info['suit'] = card.suit.value info['rank'] = card.rank.value self.send('notify', info, player=p.botPosition) info = {'type': 'draw', 'who': player, 'order': self.nextDraw, 'suit': card.suit.value, 'rank': card.rank.value} self.log('notify', info) self.hands[player].append(self.nextDraw) self.nextDraw += 1 if self.nextDraw >= len(self.deck): self.endTurn = self.turnCount + len(self.players) self.send('notify', {'type': 'draw_size', 'size': len(self.deck) - self.nextDraw}) self.print(verbose="{} draws {} {}".format( names[player], card.suit.full_name(self.variant), card.rank.value))
def discard_card(self, player: int, deckIdx: int) -> None: if self.isGameComplete(): raise GameException('Game is complete') if self.lastAction == player: raise GameException('Player already made a move', player) if self.currentPlayer != player: raise GameException('Wrong Player Turn', player) if self.clues == 8: raise GameException('Cannot Discard') card: ServerCard = self.deck[deckIdx] if card.status != CardStatus.Hand: raise GameException('Bad Card Status', card.status) if card.player != player: raise GameException('Card does not belong to player', card.player) self.discards[card.suit].append(card.position) self.send('notify', {'type': 'discard', 'which': {'suit': card.suit, 'rank': card.rank, 'index': card.index, 'order': card.position}}) card.status = CardStatus.Discard position: int position = len(self.hands[player]) - self.hands[player].index(deckIdx) self.hands[player].remove(deckIdx) self.clues += 1 self.print( "{} discards {} {}".format( names[player], card.suit.full_name(self.variant), card.rank.value), "{} discards {} {} from slot {}".format( names[player], card.suit.full_name(self.variant), card.rank.value, position)) self.draw_card(player) self.lastAction = player
def __init__(self, gameObj: 'game.Game', playerObj: int, deckPosition: int, suit: Optional[Color], rank: Optional[Value]) -> None: self.game: game.Game = gameObj self.player: int = playerObj self.deckPosition: int = deckPosition self.suit: Optional[Color] = suit self.rank: Optional[Value] = rank self.positiveClueColor: List[Color] = [] self.negativeClueColor: List[Color] = [] self.positiveClueValue: Optional[Value] = None self.negativeClueValue: List[Value] = []
def __init__(self, width, height): self.Width = width self.Height = height self.Image = pygame.image.load(os.path.join('project2/euromast_illustratie_02.jpg')) self.Buttons = [Button("PLAY", 250, 40, lambda : game.Game().program_loop()), #Button("LOAD SAVE GAME", 250, 80, lambda: [game.Game().program_loop(), other.SaveGame.load()]), Button("INSTRUCTIONS", 250, 110, lambda : InstructionMenu(width, height)), Button("HIGH SCORE", 250, 180, lambda : HighScoreMenu(width, height)), Button("QUIT", 250, 250, lambda : sys.exit())]
def program(): #game.Game.program_loop() games.program_loop() mainmenu.MainmenuNew.program_loop()
def newGame( self, layout, pacmanAgent, ghostAgents, display, quiet = False, catchExceptions=False): agents = [pacmanAgent] + ghostAgents[:layout.getNumGhosts()] initState = GameState() initState.initialize( layout, len(ghostAgents) ) game = Game(agents, display, self, catchExceptions=catchExceptions) game.state = initState self.initialState = initState.deepCopy() self.quiet = quiet return game
def newGame( self, layout, agents, display, length, muteAgents, catchExceptions ): initState = GameState() initState.initialize( layout, len(agents) ) starter = random.randint(0,1) print('%s team starts' % ['Red', 'Blue'][starter]) game = Game(agents, display, self, startingIndex=starter, muteAgents=muteAgents, catchExceptions=catchExceptions) game.state = initState game.length = length game.state.data.timeleft = length if 'drawCenterLine' in dir(display): display.drawCenterLine() self._initBlueFood = initState.getBlueFood().count() self._initRedFood = initState.getRedFood().count() return game
def on_login(login_info): try: game: Game = games[login_info['game']] player: Player = [player for player in game.players if player.token == login_info['token']][0] except KeyError: socketio.emit('error', 'Socket connection must start with sending of token (cookie) and game (id) in JSON format') return except IndexError: socketio.emit('error', 'User does not exist') return player.socket_sid = request.sid socketio.emit('client full', json.dumps(game.retrieve_game(player)), room=player.socket_sid)
def access() -> Dict: ''' Checks if request has a cookie of a logged in user. If cookie exists it sends user their game info. If not, it takes them to the login page. ''' cookie: str = request.cookies.get('tbg_token') try: game_id: str = clients[cookie] except KeyError: abort(400, util.error('Access denied')) if games[game_id].status == 'Completed': abort(400, util.error('Game already completed')) player: Player = util.shrink([player for player in games[game_id].players if player.token == request.cookies.get('tbg_token')]) return jsonify({'game': game_id, "player_name": player.name})
def login() -> Dict: ''' Adds user to the requested game as long as game isn't full or already started, game exists, and user name isn't already used in game. ''' post_data: Dict = request.get_json() try: name: str = post_data['name'] game_id: str = post_data['game'] except KeyError: abort(400, util.error('Incorrect JSON data')) # Get first public game game: Game = util.shrink([games[game_id] for game_id in games if games[game_id].game_type == 'public']) # If game game_id isn't a blank string, use that game if game_id in games: game = games[game_id] if name in [player.name for player in game.players]: abort(400, util.error('User already exists with that name')) if game.status != 'Awaiting': abort(400, util.error('Game has already started or ended')) if game.is_full(): abort(400, util.error('Game is full')) player: Player = Player(name) game.add_player(player) clients[player.token] = game_id response = make_response(jsonify(util.success('Successfully logged into game'))) response.set_cookie('tbg_token', player.token, max_age=6000) update_client(game) return response
def game_status(game: Game, player: Player) -> Dict: '''Returns all game info''' result: Dict = game.retrieve_game(player) error_check(result) return jsonify(result)
def start_game(game: Game, player: Player) -> Dict: '''Starts requested game if user is host''' result: Dict = game.start_game(player) error_check(result) update_client(game) return jsonify(result)
def play_card_from_hand(game: Game, player: Player) -> Dict: '''Plays top card from hand to field specified''' post_data: Dict = request.get_json() try: field_index: int = post_data['field_index'] except KeyError: abort(400, util.error('Incorrect JSON data')) result: Dict = game.hand_to_field(player, field_index) error_check(result) update_client(game) return jsonify(result)
def play_card_from_market(game: Game, player: Player) -> Dict: '''Places card from market into field''' post_data: Dict = request.get_json() try: field_index: int = post_data['field_index'] card_id: str = post_data['card_id'] except KeyError: abort(400, util.error('Incorrect JSON data')) result: Dict = game.market_to_field(player, field_index, card_id) error_check(result) update_client(game) return jsonify(result)
def play_card_from_pending(game: Game, player: Player) -> Dict: '''Places card from market into field''' post_data: Dict = request.get_json() try: card_id: str = post_data['card_id'] field_index: int = post_data['field_index'] except KeyError: abort(400, util.error('Incorrect JSON data')) result: Dict = game.pending_to_field(player, field_index, card_id) error_check(result) update_client(game) return jsonify(result)
def draw_for_hand(game: Game, player: Player) -> Dict: '''Draws three cards and places them in players hand''' result: Dict = game.deck_to_hand(player) error_check(result) update_client(game) return jsonify(result)
def create_trade(game: Game, player: Player) -> Dict: '''Creates new trade''' post_data: Dict = request.get_json() try: card_ids: List[str] = post_data['card_ids'] other_player_name: str = post_data['other_player'] wants: List[str] = post_data['wants'] # List of card names except KeyError: abort(400, util.error('Incorrect JSON data')) result = game.create_trade(player, other_player_name, card_ids, wants) error_check(result) update_client(game) return jsonify(result)
def accept_trade(game: Game, player: Player) -> Dict: '''Accepts a trade''' post_data: Dict = request.get_json() try: trade_id: str = post_data['trade_id'] card_ids: List[str] = post_data['card_ids'] except KeyError: abort(400, util.error('Incorrect JSON data')) result = game.accept_trade(player, trade_id, card_ids) error_check(result) update_client(game) return jsonify(result)
def reject_trade(game: Game, player: Player) -> Dict: '''Rejects a trade''' post_data: Dict = request.get_json() try: trade_id: str = post_data['trade_id'] except KeyError: abort(400, util.error('Incorrect JSON data')) result = game.reject_trade(player, trade_id) error_check(result) update_client(game) return jsonify(result)
def buy_field(game: Game, player: Player) -> Dict: '''Buys third field for 3 coins''' result = game.buy_field(player) error_check(result) update_client(game) return jsonify(result)
def test_piece_moves_heuristics(self): player_points_1 = {'w': 0, 'b': 0} new_game = Game() self.assertEqual(piece_moves(new_game, player_points_1, 0.50)['w'], 16, "Should return white player's sum of total weighted legal moves") player_points_2 = {'w': 0, 'b': 0} new_game.apply_move("d2d3") new_game.apply_move("e7e6") self.assertEqual(piece_moves(new_game, player_points_2, 0.50)['w'], 29, "Should return white player's sum of total weighted legal moves after pawn moves d2d3")
def test_center_squares(self): player_points = {'w': 0, 'b': 0} #Initialized board situation_a = Game() center_squares(situation_a, player_points, 1) self.assertEqual(player_points['b'], 0, "Should not have value since no piece is in any of the center squares") self.assertEqual(player_points['w'], 0, "Should not have value since no piece is in any of the center squares") situation_b = Game("r1bqkb1r/ppp1pppp/2n2n2/3p4/3PP3/2PQ4/PP3PPP/RNB1KBNR b KQkq e3 0 4") center_squares(situation_b, player_points, 1) self.assertEqual(player_points['b'], 5, "Should have points for 2 pieces in the outer square and 1 in the inner (5)") self.assertEqual(player_points['w'], 8, "Should have points for 2 pieces in the outer square and 2 in the inner (8)")
def __init__(self): self.game = Game() self.computer = AI(self.game, 4)
def __init__(self, board_state): self.game = Game(board_state) self.computer = AI(self.game, 5)
def get_moves(self, board_state=None): if board_state == None: board_state = str(self.game) possible_moves = [] for move in Game(board_state).get_moves(): if (len(move) < 5 or move[4] == "q"): clone = Game(board_state) clone.apply_move(move) node = Node(str(clone)) node.algebraic_move = move possible_moves.append(node) return possible_moves
def start_new_game(): game = Game() listener = TwitterGame(api, game, api.update_status(game.clue).id) return listener
def __init__(self, screen: pygame.Surface): super(MainMenu, self).__init__(screen) self.game = Game(self.screen) screen_portion = (self.screen.get_width() / 2, self.screen.get_height() / 3) screen_portion1 = (screen_portion[0], screen_portion[1] * 1.5) screen_portion2 = (screen_portion[0], screen_portion[1] * 2) self.menu = [MenuItem(self.screen, '1 PLAYER', screen_portion), MenuItem(self.screen, '2 PLAYER', screen_portion1), MenuItem(self.screen, 'QUIT MENU', screen_portion2)]
def generateSuccessor(self, action, agentIndex): """ Returns the successor state after the specified pursuer takes action """ # Check that successors exist if self.isWin() or self.isLose(): # time.sleep(2) raise Exception('Game over') # Copy current state state = GameState(self) # Let agent's logic deal with its action's effects on the board if agentIndex == 0: # Pacman is moving # state.data._eaten = [False for i in range(state.getNumAgents())] TargetRules.applyAction( state, action ) else: # A ghost is moving PursuerRules.applyAction( state, action, agentIndex ) # Book keeping #state.data._agentMoved = agentIndex state.data.score += state.data.scoreChange GameState.explored.add(self) GameState.explored.add(state) return state
def newGame(self, layout, targetAgent, pursuerAgents, display, catchExceptions = False): agents = [targetAgent] + pursuerAgents[:layout.getNumPursuers()] initState = GameState() initState.initialize(layout, len(pursuerAgents)) game = Game(agents, display, self, catchExceptions = catchExceptions) game.state = initState self.initialState = initState.deepCopy() return game
def setUp(self): self.game = Game(None)
def start_game(self, *args): if self.treeview.focus() != "": if not self.treeview.item(self.treeview.focus())["text"].startswith("-"): self.parent.canvas.delete("all") self.parent.canvas.unbind("<Configure>") self.parent.canvas.bind("<Configure>", self.parent.canvas.on_resize) self.game = Game(self.parent) self.spawn(self.scenario_list[self.selected_scenario]) self.game.update_families() self.game.recreate_taskbar() del args
def testStateAfterListen(self): game = Game() # testing 10 times to account for uncertainty for i in range(10): old_state = game.getState() game.respond("listen") new_state = game.getState() self.assertFalse(old_state != new_state)