def fix_broken_times_json(err_file): data = json.load(open(err_file, 'r')) fixes = data['fixes'] for fix in fixes: game_id = fix['game_id'] game = Game(game_id) player_id = fix['player_id'] player = Player(player_id) time_data = [(dt.timedelta(seconds=t['start']), dt.timedelta(seconds=t['end'])) for t in fix['times']] print('Updating playing time for {} ({}) in {} ({})'.format( player, player.id, game, game.id)) player.save_timestream(game, time_data) #print(compute_ts_length(time_data, unit='minutes')) boxscore_minutes = game.player_boxscore( player)['total_seconds_played'] / 60.0 computed_minutes = compute_ts_length(player.time_on_court( game, recompute=False), unit='minutes') if not abs(computed_minutes - boxscore_minutes) <= 0.5: err = colored( 'Discrepancy between computed time: {0: 2.2f} and boxscore time: {1:2.2f}' .format(computed_minutes, boxscore_minutes), 'red') print(err) else: print('{} played {} minutes in {}'.format( player, round(computed_minutes, 3), game))
def fix_broken_times(err_file): with open(err_file, 'r') as f: for line in f: matches = re.findall('\([\d]+\)', line) if matches and matches != []: ids = map(lambda x: int(x.replace('(', '').replace(')', '')), matches) player_id, game_id = ids[0], ids[1] player = Player(player_id) game = Game(game_id) print( 'Calculating time on court for {} ({}) in {} ({})'.format( player, player.id, game, game.id)) time_on_court = player.time_on_court(game, recompute=True) computed_minutes = compute_ts_length(time_on_court, unit='minutes') boxscore_minutes = game.player_boxscore( player)['totalSecondsPlayed'] / 60.0 if not abs(computed_minutes - boxscore_minutes) <= 1.0: print('In computing playing time for {} ({}) in {} ({}):'. format(player, player.id, game, game.id), file=sys.stderr) print( 'Discrepancy between computed time: {0:2.2f}, and boxscore time: {1:2.2f}' .format(computed_minutes, boxscore_minutes), file=sys.stderr) else: print('{} played {} minutes in {}'.format( player, round(computed_minutes, 3), game))
def __init__(self, numHouses, debug): self.numHouse = numHouses self.houses = [] row = [] self.monsterNum = 0 self.player = Player() if (debug): self.player.printPlayer() for x in range(numHouses): row = [] for y in range(numHouses): numMon = randint(0, 10) self.monsterNum += numMon house = House(numMon, x * numHouses + y) house.add_observer(self) row.append(house) if (debug): # Debug Purposes print("\n\n{:d}, {:d}".format(x, y)) house.printHouse() self.houses.append(row) self.houses[0][0].addPlayer(self.player)
class ClientChannel(Channel): def __init__(self, *args, **kwargs): self.name = "anonymous" self.player = Player(0, 0, False, 100, '@', self.name) Channel.__init__(self, *args, **kwargs) def Close(self): self._server.DelPlayer(self) def Network(self, data): print(data) def Network_nickname(self, data): self.name = data['nickname'] self.player.setName(self.name) self._server.SendALL({ 'action': 'updatePlayers', 'updatePlayers': self.player.getPlayerData() }) def Network_posUpdate(self, data): pos = data['posUpdate'] self.player.x = pos[0] self.player.y = pos[1] print(self.name) self._server.SendALL({ 'action': 'posUpdate', 'posUpdate': [self.name, self.player.x, self.player.y] }) def Network_wantMap(self, data): self._server.sendMap(self)
def __init__(self, aggressiveness): Player.__init__(self, aggressiveness) self.displayer = Displayer() self.hand_strength = HandStrength() self.winning_prob = WinningProbabilities() self.thresholds = [0.02,0,0.1,0.01,0.3,0.1,0.4,0.2,0.1,0.01,0.14,0.02,0.2,0.05,0.33,0.01] self.initThresholds()
def __init__(self, map_name, config=None, train=False): super(Game, self).__init__(map_name, config=config, train=train) self.default_setup() # Initialize 2 teams with one player each self.teams: Dict[int, Team] = {1: Team(), 2: Team()} self.teams[1].add_player(Player(self.players[0], 1, self)) self.teams[2].add_player(Player(self.players[1], 2, self)) self.euclidean_mat = dict() self.manhattan_mat = dict() self.create_distance_matrices(10, 10) self.prev_stat = None
def test_get_team_stats_by_time(self): team = Team(12) players = [Player(399725), Player(3085)] timestream = self.game.multiple_player_overlap(players)[0] stats = self.game.team_stats_by_time(team, timestream) pprint(stats.__dict__) self.assertEqual(stats.assists, 13) self.assertEqual(stats.field_goals_attempted, 40) self.assertEqual(stats.field_goals_made, 18)
def __init__(self, **kwargs): self.__dict__.update(kwargs) self.winning_score = 10000 self.current_highscore = 0 self.rounds = 0 steve = Player('Steve', 300, 2, 3) paul = Player('Paul', 450, 2, 2) jerry = Player('Jerry', 250, 3, 3) tina = Player('Tina', 350, 3, 2) one = score_bracket(250, 350, 4) two = score_bracket(400, 500, 3) three = score_bracket(550, 850, 2) four = score_bracket(900, 99999, 1) steve.passToBrackets.append(one) steve.passToBrackets.append(two) steve.passToBrackets.append(three) steve.passToBrackets.append(four) lone = score_bracket(250, 350, 4) ltwo = score_bracket(400, 500, 3) lthree = score_bracket(550, 850, 2) lfour = score_bracket(900, 99999, 1) paul.passToBrackets.append(lone) paul.passToBrackets.append(ltwo) paul.passToBrackets.append(lthree) paul.passToBrackets.append(lfour) pone = score_bracket(250, 350, 4) ptwo = score_bracket(400, 500, 3) pthree = score_bracket(550, 850, 2) pfour = score_bracket(900, 99999, 1) jerry.passToBrackets.append(pone) jerry.passToBrackets.append(ptwo) jerry.passToBrackets.append(pthree) jerry.passToBrackets.append(pfour) jone = score_bracket(250, 350, 4) jtwo = score_bracket(400, 500, 3) jthree = score_bracket(550, 850, 2) jfour = score_bracket(900, 99999, 1) tina.passToBrackets.append(jone) tina.passToBrackets.append(jtwo) tina.passToBrackets.append(jthree) tina.passToBrackets.append(jfour) self.players.append(steve) self.players.append(paul) self.players.append(jerry) self.players.append(tina)
def createInInitialState(self): self.dices = Dices() self.pawns = Pawns.createInitial() self.players = [Player.createWhitePlayer(), Player.createBlackPlayer()] self.fields = Fields() self.turn = self.players[0] self.winner = None self.moves = Moves() self.moveCountPerPlayer = 0 self.fields.setInitialState() for player in self.players: self.fields.setPawnsAtStartPositions(self.pawns, player) player.pawns = self.pawns.getPawnsForPlayer(player) self.dices.roll() self.getMoves()
def __init__(self, loading=False): self.players = [Player(self.height), Player(self.height)] self.ball = Ball() if loading: for i in range(len(self.players)): self.players[i].load('game/q_best/q_weights%d' % i, 'game/q_best/q_biases%d' % i) pygame.init() self.gameDisplay = pygame.display.set_mode((self.width, self.height)) self.clock = pygame.time.Clock() self.font = pygame.font.Font("assets/ATARCC__.TTF", 40) self.start()
def compute_player_clusters(data, clusters=10, method='Affinity'): # expects a pandas DataFrame features = data.values scaled_features = StandardScaler().fit_transform(features) cluster_obj = select_cluster_obj(method, clusters) cluster_obj.fit(scaled_features) print 'Clustering using {}'.format(method) if method == 'GMM': labels = cluster_obj.predict(scaled_features) else: labels = cluster_obj.labels_ categories = {} for label in np.unique(labels): categories[label] = [] for label, player_id in zip(labels, data.index): player = Player(player_id) categories[label].append(player) return categories, cluster_obj
def enter(self, player_id): if player_id in self.players: print('xxoo') return player = Player(player_id) self.players.append(player)
def __init__(self, moment, player_jersey): self.quarter = moment[0] self.game_clock = moment[2] self.shot_clock = moment[3] # Ball info ball_info = {'x': moment[5][0][2], 'y': moment[5][0][3], 'radius': moment[5][0][4] } self.ball = Ball(ball_info) # Player info self.players = [] team_id_set = set() for item in moment[5][1:]: team_id_set.add(item[0]) color = Team.color_dict[item[0]][0] player = {'id':item[1], 'x': item[2], 'y':item[3], 'jersey':player_jersey[item[1]], 'color': color } self.players.append(Player(player)) # Team info self.teams = (Team(team_id_set.pop()), Team(team_id_set.pop()))
def calc_all_player_times(year, recompute=False): class TimeComputationError(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg all_players = players.find({}, no_cursor_timeout=True).sort( 'id', pymongo.ASCENDING) print('Loading the {}-{} NBA season'.format(year, year + 1)) season = Season(year) print('Loaded season') print('Computing time on court for all players in all games...') for player_data in all_players: player = Player(player_data['id']) games_played = season.get_player_games_in_range(player) for game in games_played: print('Calculating time on court for {} ({}) in {} ({})'.format( player, player.id, game, game.id)) boxscore_minutes = game.player_boxscore( player)['total_seconds_played'] / 60.0 if boxscore_minutes > 0: time_on_court = player.time_on_court(game, recompute=recompute) computed_minutes = compute_ts_length(time_on_court, unit='minutes') else: # there's never anything to calculate anyway computed_minutes = 0 if not abs(computed_minutes - boxscore_minutes) <= 0.5: print( 'In computing playing time for {} ({}) in {} ({}):'.format( player, player.id, game, game.id), file=sys.stderr) print( 'Discrepancy between computed time: {0:2.2f}, and boxscore time: {1:2.2f}' .format(computed_minutes, boxscore_minutes), file=sys.stderr) #raise TimeComputationError('Discrepancy between computed time: {}, and boxscore time: {}'.format(computed_minutes, boxscore_minutes) else: print('{} played {} minutes in {}'.format( player, round(computed_minutes, 3), game)) del player del games_played
def __init__(self, action_table, players, decks, init_bank, max_shuffles, max_win, min_bet): self.player = Player(action_table, init_bank) self.players = players self.decks = decks self.shoe = Shoe(decks) self.max_shuffles = max_shuffles self.init_bank = init_bank self.max_win = max_win self.min_bet = min_bet self.dealer_hand = Hand()
def __init__(self, p1, p2, pygame): self.p1 = p1 self.p2 = p2 self.player1 = Player(side=0, a=p1) self.player1.side = 1 self.player2 = Player(side=0, a=p2) self.player2.side = 0 self.ball = Ball() self.running = True self.pygame = pygame self.window = self.pygame.display.set_mode( (self.canvas_width, self.canvas_height), 0, 32) self.myfont = self.pygame.font.SysFont("monospace", 45) self.fps = self.pygame.time.Clock() self.initialize_scene()
def __init__(self, cfg, main): """ Constructor ----------------------------------------------------------------------- Arguments : - cfg : Config of the class - main : Main class ----------------------------------------------------------------------- Return : None. """ super(GameState, self).__init__(cfg=cfg, main=main) self._main = main self.__grid = [] self.__player1 = Player(cfg=self._ownConfig["players"]["1"], game=self, number=1) self.__player2 = Player(cfg=self._ownConfig["players"]["2"], game=self, number=2) self.__piece_to_mouse = None
def load_normal_player(): one = score_bracket(250, 350, 4) two = score_bracket(400, 500, 3) three = score_bracket(550, 850, 2) four = score_bracket(900, 99999, 1) p = Player('test', 350, 3, 2) p.passToBrackets.append(one) p.passToBrackets.append(two) p.passToBrackets.append(three) p.passToBrackets.append(four) pytest.normal_player = p
def initialize_players(self, bots, map): self.players = [] positions = STARTING_POSITIONS[len(bots) - 1] # create a player object for each bot for count, bot in enumerate(bots): pos = Coordinate(x=positions[count][0], y=positions[count][1]) self.players.append(Player(count, self.map, bots[count], pos)) # create a starting hive for each player for player in self.players: self.map.get_cell(player.starting_pos).create_hive(player.playerId)
def playGame(): _map = Map(70, 50) _map.generate_Dungeon(70, 50) playerx, playery = _map.findPlayerLoc() player = Player(playerx, playery, False, 100, '@', "Tom") terminal.clear() _map.do_fov(player.x, player.y, constants.FOV_RADIUS) while True: ex = gameTick(_map, player) if ex == 2: terminal.bkcolor(black) break
def get_all_player_features(season, start_date=None, end_date=None, recompute=False): all_players = players.find({}).sort('id', pymongo.ASCENDING) o_header = ['ast_pct', 'ts_pct', 'orb_pct', 'usg', 'ortg', 'mp_pct'] d_header = ['blk_pct', 'stl_pct', 'drb_pct', 'drtg', 'pf_pct'] str_format = '%Y-%m-%d' feature_file = 'player-features-from-{}-to-{}.csv'.format( start_date.strftime(str_format), end_date.strftime(str_format)) path = os.path.join('season_data', str(season.season), feature_file) if os.path.exists(path) and not recompute: player_features = pd.read_csv(path, index_col=0) else: feature_headers = o_header + d_header index = [] all_features = [] for i, player_data in enumerate(all_players): player = Player(player_data['id']) index.append(player.id) #print 'Extracting offensive features for {} from the {}'.format(player, season) o_features = player_ocluster_features(player, season, start_date, end_date) #print 'Extracting defensive features for {} from the {}'.format(player, season) d_features = player_dcluster_features(player, season, start_date, end_date) # drop the id in d_features all_features.append(o_features[1:] + d_features[1:-1]) player_features = pd.DataFrame(data=all_features, columns=feature_headers, index=index) player_features.index.name = 'id' player_features.to_csv(path) return player_features
class Game: def __init__(self, action_table, players, decks, init_bank, max_shuffles, max_win, min_bet): self.player = Player(action_table, init_bank) self.players = players self.decks = decks self.shoe = Shoe(decks) self.max_shuffles = max_shuffles self.init_bank = init_bank self.max_win = max_win self.min_bet = min_bet self.dealer_hand = Hand() def __call__(self, *args, **kwargs): shuffles = 0 while shuffles < self.max_shuffles and 0 < self.player.bank < self.init_bank * self.max_win: # print('---new shuffle---') # print('bank: ' + str(self.player.bank)) win = self.shuffle() # print('win: ' + str(win)) if win > 0: self.player.bank += win shuffles += 1 return self.player.bank def shuffle(self): self.shoe = Shoe(self.decks) self.shoe.shuffle() self.bet = 0 self.make_bet(self.min_bet) self.dealer_hand = Hand() self.player.hand = Hand() self.player.hit(self.shoe.deal()) self.dealer_hand.append(self.shoe.deal()) self.player.hit(self.shoe.deal()) # print("Player's hand:") # self.player.hand.print() # print("Dealer's hand:") # self.dealer_hand.print() if self.player.hand.score() == 21: # print("Blackjack") return self.blackjack() for _ in range(self.players - 1): self.shoe.deal() self.shoe.deal() dealer_state = self.dealer_state() shoe_state = self.shoe_state() # print("Shoe count: " + str(self.shoe.count)) return self.action(dealer_state, shoe_state, True) def make_bet(self, bet): self.player.bank -= bet self.bet += bet def action(self, dealer_state, shoe_state, canDoubled): player_state = self.player.state() act = self.player.act(player_state, dealer_state, shoe_state) if act == 's': # print('stand') return self.stand() elif act == 'd' and canDoubled: # print('double') return self.double() else: # print('hit') return self.hit() def dealer_state(self): card = self.dealer_hand[0] if card.isAce(): return '11' return str(card.val) def shoe_state(self): true_count = self.shoe.count / self.decks if true_count > 5: return 1 if true_count < -5: return -1 return 0 def stand(self): self.dealer_play() if self.dealer_hand.score() > 21: # print('Dealer over') return self.bet * 2 return self.compare_hand() def hit(self): self.player.hit(self.shoe.deal()) # print("Player's hand") # self.player.hand.print() cur_score = self.player.hand.score() if cur_score > 21: return self.over() if cur_score == 21: return self.stand() shoe_state = self.shoe_state() dealer_state = self.dealer_state() if cur_score > 21: pass return self.action(dealer_state, shoe_state, False) def over(self): # print('player over') return 0 def blackjack(self): return self.bet * 2.5 def double(self): if self.player.bank > self.min_bet: self.make_bet(self.bet) return self.hit() def dealer_play(self): while self.dealer_hand.score() < 17: self.dealer_hand.append(self.shoe.deal()) def compare_hand(self): dealer_score = self.dealer_hand.score() player_score = self.player.hand.score() # print("dealer : " + str(dealer_score)) # print("player : " + str(player_score)) if player_score > dealer_score: return self.bet * 2 if player_score == dealer_score: return self.bet return 0
class Neighborhood(Observer): def __init__(self, numHouses, debug): self.numHouse = numHouses self.houses = [] row = [] self.monsterNum = 0 self.player = Player() if (debug): self.player.printPlayer() for x in range(numHouses): row = [] for y in range(numHouses): numMon = randint(0, 10) self.monsterNum += numMon house = House(numMon, x * numHouses + y) house.add_observer(self) row.append(house) if (debug): # Debug Purposes print("\n\n{:d}, {:d}".format(x, y)) house.printHouse() self.houses.append(row) self.houses[0][0].addPlayer(self.player) #getter def getPlayer(self): return self.player #checks for indices that could be out of bounds def isValidSpace(self, x, y): if (x < self.numHouse and y < self.numHouse and x >= 0 and y >= 0): #print("Valid") return True else: #print("{:d},{:d} Is out of the bounds of {:d} {:d}, {:d} {:d}".format(x,y,0,self.numHouse,0,self.numHouse)) print( "You reach the end of the Neighborhood. \nChoose a different Direction" ) return False """ Handles the player/house battle interactions. """ def attackHouse(self): #set up a lot of temp variables playerPos = self.player.getLocation() xpos = playerPos[0] ypos = playerPos[1] tmpHouse = self.houses[xpos][ypos] tmpHouse.printHouse() #current house #while they dont leave... winput = False while not winput: wep = input("Which weapon would you like to use?\n>> ") self.player.printPlayer() atkVal = 0.0 if wep == "" or wep == "leave": #exit the loop winput = True break elif wep in Player.SHORT_WEAPONS.keys( ): #if it is a shortened version of the weapon name atkval = self.player.attack(Player.SHORT_WEAPONS[wep]) tmpHouse.atk(atkval, Player.SHORT_WEAPONS[wep]) dmg = tmpHouse.damage() self.player.getHit(dmg) print( "You took {:f} damage.\nYour new health is {:f}\n".format( dmg, self.player.getHealth())) suc = True elif wep in Player.WEAPONS: #normal weapon name atkval = self.player.attack(wep) tmpHouse.atk(100.01, wep) dmg = tmpHouse.damage() self.player.getHit(dmg) print("You took {:f} damage.\nYour new health is {:d}".format( dmg, self.player.getHealth())) suc = True else: #try again. print("Incorrect Input. Try again.") suc = False #changes the players location and adds/removes him from that house def movePlayer(self, x, y): loc = self.player.getLocation() self.houses[loc[0]][loc[1]].remPlayer() self.player.movePlayer(x, y) self.player.printPlayer() self.houses[x][y].addPlayer(self.player) self.houses[x][y].printHouse() #if total # of monsters in hood=0, you win! def update(self, monster): self.monsterNum -= 1 if (self.monsterNum == 0): print("Congratulations! You win!") exit() #printer method def printHouses(self): for a in range(0, len(self.houses)): for b in range(0, len(self.houses)): self.houses[a][b].printHouse()
game = Game(id=find_id(), board_width=50, board_height=50, display_option=True, general_turn_latency=0, highlight_turn_latency=300, number_of_games=150, food_offset=150, max_number_of_stones=12, max_score=-1, players=players, food_to_start=1, food_nutrition_value=25, save_logs=True, save_models=True, display_plot=True, max_turns=-1, debug=False, trap_percentage=0.2) # inputs = vision_distance^2 + vision_distance * 2 + 2 # players.append(Player(len(players), game, BaseWrapper(random(inputs=41, outputs=4)), name="random")) players.append( Player(len(players), game, ConvolutionWrapper( convolution(inputs=196, outputs=4, learning_rate=0.001)), vision_distance=7, name="0.001")) # players.append(Player(len(players), game, ConvolutionWrapper(convolution(inputs=196, outputs=4, learning_rate=0.0001)), vision_distance=7, name="0.0001")) run_game(game)
def add_a_player(self, team_id): player: pyDeepRTS.Player = self.add_player() player = Player(player, team_id, self) self.teams[team_id].add_player(player) return player
from game.Weapon import Weapon from game.Player import Player, GameOverError from game.Armor import Armor from game.game_over_error import GameOverError player = Player() player.add_to_inventory(Armor('Robe', 0.1)) player.add_to_inventory(Weapon('Sword', 3)) player.wield_item('Robe') player.wield_item('Sword') print(player) player.take_damage(10) print(player) axe = Weapon('Axe', 20) player.take_damage(axe.hit()) print(player) nuclear_bomb = Weapon('Bomb', 100000) try: player.take_damage(nuclear_bomb.hit()) except GameOverError as error: print("Game error: {0}".format(error))
def __init__(self, aggressiveness): Player.__init__(self, aggressiveness)
def away_players(self): away_player_ids = [player['player']['id'] for player in self._away_boxscore['playerstats']] away_players = [Player(id) for id in away_player_ids] return away_players
def __init__(self, aggressiveness): Player.__init__(self, aggressiveness) self.thresholds = [3,2,4,3,5,4] self.initThresholds()
class GameState(BaseState): """ This class is the main game class. --------------------------------------------------------------------------- Attributes : - __main : Main object - __grid : The grid of the game (8x8) - __player1 : The player 1 of the game - __player2 : The player 2 of the game - __piece_to_mouse : The piece that has been clicked dans that the player is moving """ def __init__(self, cfg, main): """ Constructor ----------------------------------------------------------------------- Arguments : - cfg : Config of the class - main : Main class - See attributes above. ----------------------------------------------------------------------- Return : None. """ super(GameState, self).__init__(cfg=cfg, main=main) self._main = main self.__grid = [] self.__player1 = Player(cfg=self._ownConfig["players"]["1"], game=self, number=1) self.__player2 = Player(cfg=self._ownConfig["players"]["2"], game=self, number=2) self.__piece_to_mouse = None def set_up(self): """ Method used to set_up everything ----------------------------------------------------------------------- Arguments : None. ----------------------------------------------------------------------- Return : None. """ # Set up the grid self.set_up_grid() # Set up pieces self.set_up_pieces() # start player self.__player1.set_playing(True) def launch(self): """ Method called to launch the game ----------------------------------------------------------------------- Arguments : None. ----------------------------------------------------------------------- Return : None. """ self.set_up() def set_up_grid(self): """ Method called to set up the grid ----------------------------------------------------------------------- Arguments : None. ----------------------------------------------------------------------- Return : None. """ # Setting the grid 8x8 for i in range(8): self.__grid.append(i) def set_up_pieces(self): """ Method called to set up the pieces It is not done with loop because it could need so much effort for nothing as the pieces are always the same and at the same square ----------------------------------------------------------------------- Arguments : None. ----------------------------------------------------------------------- Return : None. """ pieces = [] # Player 1 pieces.append( Rook(y=0, x=0, code=Piece.ROOK_CODE, player=self.__player1)) pieces.append( Knight(y=0, x=1, code=Piece.KNIGHT_CODE, player=self.__player1)) pieces.append( Bishop(y=0, x=2, code=Piece.BISHOP_CODE, player=self.__player1)) pieces.append( King(y=0, x=3, code=Piece.KING_CODE, player=self.__player1)) pieces.append( Queen(y=0, x=4, code=Piece.QUEEN_CODE, player=self.__player1)) pieces.append( Bishop(y=0, x=5, code=Piece.BISHOP_CODE, player=self.__player1)) pieces.append( Knight(y=0, x=6, code=Piece.KNIGHT_CODE, player=self.__player1)) pieces.append( Rook(y=0, x=7, code=Piece.ROOK_CODE, player=self.__player1)) for i in range(8): pieces.append( Pawn(y=1, x=i, code=Piece.PAWN_CODE, player=self.__player1)) # pass self.__player1.setPieces(pieces) pieces = [] # Player 2 pieces.append( Rook(y=7, x=0, code=Piece.ROOK_CODE, player=self.__player2)) pieces.append( Knight(y=7, x=1, code=Piece.KNIGHT_CODE, player=self.__player2)) pieces.append( Bishop(y=7, x=2, code=Piece.BISHOP_CODE, player=self.__player2)) pieces.append( King(y=7, x=3, code=Piece.KING_CODE, player=self.__player2)) pieces.append( Queen(y=7, x=4, code=Piece.QUEEN_CODE, player=self.__player2)) pieces.append( Bishop(y=7, x=5, code=Piece.BISHOP_CODE, player=self.__player2)) pieces.append( Knight(y=7, x=6, code=Piece.KNIGHT_CODE, player=self.__player2)) pieces.append( Rook(y=7, x=7, code=Piece.ROOK_CODE, player=self.__player2)) for i in range(8): pieces.append( Pawn(y=6, x=i, code=Piece.PAWN_CODE, player=self.__player2)) # pass self.__player2.setPieces(pieces) def handle_events(self, events): """ This method is used to handle events. ----------------------------------------------------------------------- Arguments : - events : List of event from pygame.event.get() ----------------------------------------------------------------------- Return : None. """ # Event from pygame for event in events: # Window quit event if event.type == pygame.QUIT: self._main.stop_gui() # Click event elif event.type == pygame.MOUSEBUTTONUP: # Getting mouse coordinates mx, my = pygame.mouse.get_pos() # Checking button click for b in self._main.get_buttons(): if mx > b.get_x() and mx < b.get_x() + b.get_width( ) and my > b.get_y() and my < b.get_y() + b.get_height(): b.action() # Checking if it's the first player is playing if self.__player1.is_playing(): # If it's him then we can check what to do with his click played = self.check_clicked_pieces( self.__player1.getPieces(), mx, my, self.__player1.getNumber()) if played: # self.check_check(1) # Change playing player self.__player1.set_playing(False) self.__player2.set_playing(True) self.check_check(2) else: played = self.check_clicked_pieces( self.__player2.getPieces(), mx, my, self.__player2.getNumber()) if played: # Change playing player self.__player2.set_playing(False) self.__player1.set_playing(True) self.check_check(1) else: # Getting mouse coordinates mx, my = pygame.mouse.get_pos() for b in self._main.get_buttons(): b.hover(mx, my) def check_clicked_pieces(self, pieces, mx, my, player_nb): """ This method handle the click on the pieces. It will check which piece is clicked and how to handle it with the current player and pieces pos. ----------------------------------------------------------------------- Arguments : - pieces : Current player pieces - mx : X pos of the mouse - my : Y pos of the mouse - player_nb : current number of the player ----------------------------------------------------------------------- Return : - True : If the player moved his piece - False : If not """ # We players's pos current_pl_pos, other_pl_pos = self.get_players_pos(player_nb) # There we go for each piece of the player to check if he clicked on one for p in pieces: # Get the coordintes of the piece y = p.getY() * 62.5 x = p.getX() * 62.5 # We use x, y, mx, my to check if the current piece of the loop is being clicked and if there is no piece already # selected if mx > x and mx < x + p.getWidth( ) and my > y and my < y + p.getWidth( ) and self.__piece_to_mouse == None: # If so, we change the state of the piece p.selected() # And we keep a reference to the piece self.__piece_to_mouse = p return False # Same than above but with a piece already selected, so we need to check if the square is empty or if the is # an enemy on it elif mx > x and mx < x + p.getWidth( ) and my > y and my < y + p.getWidth( ) and self.__piece_to_mouse != None: self.__piece_to_mouse.selected() self.__piece_to_mouse = None return False # If there is already a piece selected elif self.__piece_to_mouse is not None: # If the selected piece is the current if p.is_selected(): # We get the clicked square x, y = self.get_clicked_square(mx, my) # We call the method of the piece to check if the moce is avaible if p.is_move_available( x, y, current_pl_pos=current_pl_pos, other_pl_pos=other_pl_pos, for_check=False) and not self.check_check( player_nb=player_nb, add_msg=True, x=x, y=y, piece_moving=p): # Check if there is a kill self.check_kill(x, y, player_nb) # Update the pos of the piece p.new_pos(x, y) # Update the selected attribute of the piece p.selected() # Remove the reference self.__piece_to_mouse = None self.add_msg_to_logger( "Player " + str(player_nb) + " moved " + str(p.code_to_str()).capitalize() + " to " + str(x) + "," + str(y) + ".") return True # If the move is not available we reset and put back the piece where it belongs p.selected() self.__piece_to_mouse = None return False return False def check_check(self, player_nb, add_msg=False, piece_moving=None, x=None, y=None): """ This method is used to check if there is a check ----------------------------------------------------------------------- Arguments : - player_nb : [int] Number of the player you want to check the check state - add_msg: [bool] True if you want to display FlashMessage to the screen - piece_moving : [Piece object or child] Need to be set if the method is called because it will set up a new list with updated pos of the piece - x : x target of the piece_moving - y : y target of the piece_moving ----------------------------------------------------------------------- Return : - True : If the player mis under check - False : If he is not """ # There we set up the var depending on the player if player_nb == 1: cur_pl, other_pl = self.get_players_pieces(1) cur_pl_pos = self.__player1.get_pieces_pos() # Get the currently playing king pos king_pos = self.__player1.get_king_pos() else: cur_pl, other_pl = self.get_players_pieces(2) # Get the currently playing king pos cur_pl_pos = self.__player2.get_pieces_pos() king_pos = self.__player2.get_king_pos() # If the method is called with a piece that need to have its # pos updated if piece_moving != None: # Creating a temporary lsit temp_pl_pos = [] # filling it with all the pos of the current player except the piece_moving one for i in cur_pl_pos: if i != piece_moving.getPos(): temp_pl_pos.append(i) # Then we add the next pos of the moving_piece temp_pl_pos.append((x, y)) # transfer the data between lists cur_pl_pos = temp_pl_pos if piece_moving.getCode() == KING_CODE: king_pos = (x, y) # save_king_pos = king_pos # Then we go through all the other pieces to check if he can reach the king for piece_moving in other_pl: # If it can then we return True and set the check_state of the player to # True and return to leave the method. if piece_moving.is_move_available(king_pos[0], king_pos[1], other_pl, cur_pl_pos, True): print(piece_moving) if add_msg and piece_moving is not None: text = "This move is not allowed because of Check" self._flash_msgs.append( FlashMessage(size=12, text=text, x=0, y=0, code=WARNING_CODE, duration=4)) elif add_msg and piece_moving is None: text = "Check" self._flash_msgs.append( FlashMessage(size=15, text=text, x=0, y=0, code=WARNING_CODE, duration=4)) if player_nb == 1: self.__player1.set_check(True) else: self.__player2.set_check(True) return True # If the return True above is never called during the loop, it means that the player # is not under check so we set it to false and return False if player_nb == 1: self.__player1.set_check(False) else: self.__player2.set_check(False) return False def add_msg_to_logger(self, msg): self._main.add_msg_to_logger(msg) # GETTERS SETTERS def get_grid(self): return self.__grid def get_pieces(self): return self.__player1.getPieces(), self.__player2.getPieces() def get_players_pos(self, player_nb): """ Method used to get the player pieces pos ----------------------------------------------------------------------- Arguments : - player_nb : Current number of the player ----------------------------------------------------------------------- Return : - current_pl_pos : list with current player pieces pos - other_pl_pos : list with the player that is not playing pieces pos """ current_pl_pos = [] other_pl_pos = [] # Setting up var to loop if player_nb == 1: player = self.__player1 other_player = self.__player2 else: player = self.__player2 other_player = self.__player1 # Adding pieces to each list for p in player.getPieces(): current_pl_pos.append(p.getPos()) for p in other_player.getPieces(): other_pl_pos.append(p.getPos()) return current_pl_pos, other_pl_pos def get_players_pieces(self, player_nb): if player_nb == 1: cur_pl = self.__player1.getPieces() other_pl = self.__player2.getPieces() else: cur_pl = self.__player2.getPieces() other_pl = self.__player1.getPieces() return cur_pl, other_pl def check_kill(self, x, y, player_nb): """ Method used to check if there is a kill ----------------------------------------------------------------------- Arguments : - x : X of the next square - y : Y of the next square ----------------------------------------------------------------------- Return : None. """ # Going through all pieces for pl in (self.__player1, self.__player2): for i, piece in enumerate(pl.getPieces()): # If the pieces that might be killed is an enemy piece if piece.getX() == x and piece.getY( ) == y and piece.getPlayerNumber() != player_nb: # If there is a kill then we leave the loop self.kill_piece(piece.getPlayerNumber(), i) self.add_msg_to_logger( "Player " + str(player_nb) + " killed " + str(piece.code_to_str()).capitalize() + " on " + str(x) + "," + str(y) + ".") break def kill_piece(self, nb_player, piece): """ Method used to kill a piece ----------------------------------------------------------------------- Arguments : - nb_player : Number of the piece's player - piece : Piece that have to be kill ----------------------------------------------------------------------- Return : None. """ if nb_player == 1: self.__player1.kill_piece(piece) else: self.__player2.kill_piece(piece) def get_theme(self): return self._main.get_theme() @staticmethod def get_clicked_square(x, y): """ Method that calculate the square from coordinate (x, y) ----------------------------------------------------------------------- Arguments : - x : X coordinate - y : Y coordinate ----------------------------------------------------------------------- Return : - x : X within the grid (from 0 to 7) - y : Y within the grid (from 0 to 7) """ x = int(x / 62.5) y = int(y / 62.5) return x, y def get_piece_color_choice(self, nb): return self._main.get_piece_color_choice(nb)
class GameState(BaseState): """ This class is the main game class. --------------------------------------------------------------------------- Attributes : - __main : Main object - __grid : The grid of the game (8x8) - __player1 : The player 1 of the game - __player2 : The player 2 of the game - __piece_to_mouse : The piece that has been clicked dans that the player is moving """ def __init__(self, cfg, main): """ Constructor ----------------------------------------------------------------------- Arguments : - cfg : Config of the class - main : Main class ----------------------------------------------------------------------- Return : None. """ super(GameState, self).__init__(cfg=cfg, main=main) self._main = main self.__grid = [] self.__player1 = Player(cfg=self._ownConfig["players"]["1"], game=self, number=1) self.__player2 = Player(cfg=self._ownConfig["players"]["2"], game=self, number=2) self.__piece_to_mouse = None def set_up(self): """ Method used to set_up everything ----------------------------------------------------------------------- Arguments : ----------------------------------------------------------------------- Return : None. """ # Set up the grid self.set_up_grid() # Set up pieces self.set_up_pieces() # start player self.__player1.set_playing(True) def launch(self): """ Method called to launch the game ----------------------------------------------------------------------- Arguments : None. ----------------------------------------------------------------------- Return : None. """ self.set_up() def set_up_grid(self): """ Method called to set up the grid ----------------------------------------------------------------------- Arguments : None. ----------------------------------------------------------------------- Return : None. """ # Setting the grid 8x8 for i in range(8): self.__grid.append(i) def set_up_pieces(self): """ Method called to set up the pieces It is not done with loop because it could need so much effort for nothing as the pieces are always the same and at the same square ----------------------------------------------------------------------- Arguments : None. ----------------------------------------------------------------------- Return : None. """ pieces = [] # Player 1 pieces.append( Rook(y=0, x=0, code=Piece.ROOK_CODE, player=self.__player1)) pieces.append( Knight(y=0, x=1, code=Piece.KNIGHT_CODE, player=self.__player1)) pieces.append( Bishop(y=0, x=2, code=Piece.BISHOP_CODE, player=self.__player1)) pieces.append( King(y=0, x=3, code=Piece.KING_CODE, player=self.__player1)) pieces.append( Queen(y=0, x=4, code=Piece.QUEEN_CODE, player=self.__player1)) pieces.append( Bishop(y=0, x=5, code=Piece.BISHOP_CODE, player=self.__player1)) pieces.append( Knight(y=0, x=6, code=Piece.KNIGHT_CODE, player=self.__player1)) pieces.append( Rook(y=0, x=7, code=Piece.ROOK_CODE, player=self.__player1)) for i in range(8): pieces.append(Pawn(y=1, x=i, code=PAWN_CODE, player=self.__player1)) pass self.__player1.setPieces(pieces) pieces = [] # Player 2 pieces.append( Rook(y=7, x=0, code=Piece.ROOK_CODE, player=self.__player2)) pieces.append( Knight(y=7, x=1, code=Piece.KNIGHT_CODE, player=self.__player2)) pieces.append( Bishop(y=7, x=2, code=Piece.BISHOP_CODE, player=self.__player2)) pieces.append( King(y=7, x=3, code=Piece.KING_CODE, player=self.__player2)) pieces.append( Queen(y=7, x=4, code=Piece.QUEEN_CODE, player=self.__player2)) pieces.append( Bishop(y=7, x=5, code=Piece.BISHOP_CODE, player=self.__player2)) pieces.append( Knight(y=7, x=6, code=Piece.KNIGHT_CODE, player=self.__player2)) pieces.append( Rook(y=7, x=7, code=Piece.ROOK_CODE, player=self.__player2)) pieces.append( Rook(y=7, x=8, code=Piece.ROOK_CODE, player=self.__player2)) for i in range(8): pieces.append(Pawn(y=6, x=i, code=PAWN_CODE, player=self.__player2)) self.__player2.setPieces(pieces) # GETTERS SETTERS def getGrid(self): return self.__grid def getPieces(self): return self.__player1.getPieces(), self.__player2.getPieces() def handle_events(self, events): """ This method is used to handle events. ----------------------------------------------------------------------- Arguments : - events : List of event from pygame.event.get() ----------------------------------------------------------------------- Return : None. """ # Event from pygame for event in events: # Window quit event if event.type == pygame.QUIT: self._main.stop_gui() # Click event elif event.type == pygame.MOUSEBUTTONUP: # Getting mouse coordinates mx, my = pygame.mouse.get_pos() # Checking if it's the first player is playing if self.__player1.is_playing(): # If it's him then we can check what to do with his click played = self.check_clicked_pieces( self.__player1.getPieces(), mx, my, self.__player1.getNumber()) if played: self.__player1.set_playing(False) self.__player2.set_playing(True) else: played = self.check_clicked_pieces( self.__player2.getPieces(), mx, my, self.__player2.getNumber()) if played: self.__player1.set_playing(True) self.__player2.set_playing(False) def checkmate(self): pass def check_clicked_pieces(self, pieces, mx, my, player_nb): """ This method handle the click on the pieces. It will check which piece is clicked and how to handle it with the current player and pieces pos. ----------------------------------------------------------------------- Arguments : - pieces : Current player pieces - mx : X pos of the mouse - my : Y pos of the mouse - player_nb : current number of the player ----------------------------------------------------------------------- Return : - True : If the player moved his piece - False : If not """ for player in (self.__player1, self.__player2): current_pl_pos, other_pl_pos = self.getPlayersPos(player_nb) # There we go for each piece of the player to check if he clicked on one for p in pieces: # Get the coordintes of the piece y = p.getY() * 62.5 x = p.getX() * 62.5 # We use x, y, mx, my to check if the current piece of the loop is being clicked and if there is no piece already # Selected if mx > x and mx < x + p.getWidth( ) and my > y and my < y + p.getWidth( ) and self.__piece_to_mouse == None and p.is_alive(): # If so, we change the state of the piece p.selected() # And we keep a reference to the piece self.__piece_to_mouse = p # Same than above but with a piece already selected, so we need to check if the square is empty or if the is # an enemy on it elif mx > x and mx < x + p.getWidth( ) and my > y and my < y + p.getWidth( ) and self.__piece_to_mouse != None and p.is_alive(): self.__piece_to_mouse.selected() # If there is already a piece selected elif self.__piece_to_mouse is not None: # If the selected piece is the current if p.is_selected(): # We get the clicked square x, y = self.get_clicked_square(mx, my) # We call the method of the piece to check if the moce is avaible if p.is_move_avaible(x, y, current_pl_pos=current_pl_pos, other_pl_pos=other_pl_pos): # Check if there is a kill self.check_kill(x, y, player_nb) # Update the pos of the piece p.new_pos(x, y) # Update the selected attribute of the piece p.selected() # Remove the reference self.__piece_to_mouse = None return True # If the move is not avaible we reset put back the piece where it belongs p.selected() self.__piece_to_mouse = None return False return False def getPlayersPos(self, player_nb): """ Method used to get the player pieces pos ----------------------------------------------------------------------- Arguments : - player_nb : Current number of the player ----------------------------------------------------------------------- Return : - current_pl_pos : list with current player pieces pos - other_pl_pos : list with the player that is not playing pieces pos """ current_pl_pos = [] other_pl_pos = [] # Setting up var to loop if player_nb == 1: player = self.__player1 other_player = self.__player2 else: player = self.__player2 other_player = self.__player1 # Adding pieces to each list for p in player.getPieces(): current_pl_pos.append(p.getPos()) for p in other_player.getPieces(): other_pl_pos.append(p.getPos()) return current_pl_pos, other_pl_pos def check_kill(self, x, y, player_nb): """ Method used to check if there is a kill ----------------------------------------------------------------------- Arguments : - x : X of the next square - y : Y of the next square ----------------------------------------------------------------------- Return : None. """ # Going through all pieces for pl in (self.__player1, self.__player2): for i, piece in enumerate(pl.getPieces()): # If the pieces that might be killed is an enemy piece if piece.getX() == x and piece.getY( ) == y and piece.getPlayerNumber() != player_nb: # If there is a kill then we leave the loop self.kill_piece(piece.getPlayerNumber(), i) break def kill_piece(self, nb_player, piece): """ Method used to kill a piece ----------------------------------------------------------------------- Arguments : - nb_player : Number of the piece's player - piece : Piece that have to be kill ----------------------------------------------------------------------- Return : None. """ if nb_player == 1: self.__player1.kill_piece(piece) else: self.__player2.kill_piece(piece) def get_clicked_square(self, x, y): """ Method that calculate the square from coordinate (x, y) ----------------------------------------------------------------------- Arguments : - x : X coordinate - y : Y coordinate ----------------------------------------------------------------------- Return : - x : X within the grid (from 0 to 7) - y : Y within the grid (from 0 to 7) """ x = int(x / 62.5) y = int(y / 62.5) return x, y
lives_text = BitmapText( font_2, [Game.screen_width - 200, 50] ) lives_text.setSurface( screen ) gameover_text = BitmapText( font_1, [(Game.screen_width / 2)-300, 100] ) gameover_text.setSurface( screen ) dead_text = BitmapText( font_2, [(Game.screen_width / 2)-50, 100] ) dead_text.setSurface( screen ) restart_text = BitmapText( font_2, [(Game.screen_width / 2)-200, 200] ) restart_text.setSurface( screen ) Game.level = 1 world = World( ) player = Player( ) pygame.mouse.set_visible( False ) # Define core colours black = ( 0, 0, 0 ) white = ( 255, 255, 255 ) red = ( 255, 0, 0 ) green = ( 0, 255, 0 ) blue = ( 0, 0, 255 ) # Create clock clock = pygame.time.Clock( ) # Main Program Loop flag inLoop = True
def home_players(self): home_player_ids = [player['player']['id'] for player in self._home_boxscore['playerstats']] home_players = [Player(id) for id in home_player_ids] return home_players
def __init__(self, *args, **kwargs): self.name = "anonymous" self.player = Player(0, 0, False, 100, '@', self.name) Channel.__init__(self, *args, **kwargs)