def test_set_set(self): player_set = 6 player_one = Player(PLAYER_NAME_ONE) player_one.set = player_set self.assertIsInstance(player_one.set, int)
def initialize_game(self): ''' Initializes the game so it is ready to play: - Sets as active - Randomizes turn order - Fills and shuffles card pile - Creates Player objects and deals cards Up to the user to set whose turn it is with set_turn(player_id) ''' # Fill the card pile and shuffle it self._fill_card_pile() self.shuffle() # Set game to `active` state self._active = True # Initialize all the players for user_id, user in self._signup_ids.items(): # give player their user ID / mention, start coins, and start influences player = Player(user, self._start_coins, self._start_influences) for i in range(self._start_influences): # Draw a card and give it to the player player.set_influence(i, self.draw_card()) self._players[user_id] = player self._order.append(user_id) # Randomize the turn order self.randomize_order()
def test_set_score(self): player_score = 15 player_one = Player(PLAYER_NAME_ONE) player_one.score = player_score self.assertIsInstance(player_one.score, int)
def game (): from classes.player import Player print('Welcome to BlackJack! Get as close to 21 as you can without going over!\n\ Dealer hits until she reaches 17. Aces count as 1 or 11.\n\n') #Create Player name = input ("What is your player's name?") chips = int(input('How much money do you want to play with?')) player = Player(name, chips) #Loop Game continue_game = True while continue_game == True: print(f'\n{player.name} has {player.chips.total} dinero!') player.place_bet() round (player) continue_input = input('\n Do you want to play again? Y or N') if continue_input[0] in ('y', 'Y'): continue_input = True else: continue_input = False
def generate_level(level, all_sprites, tile_group, player_group, tile_size): player1, player2, x, y = None, None, None, None for y in range(len(level)): for x in range(len(level[y])): if level[y][x] in " .": pass elif level[y][x] == 'p': player1 = Player( "Player 1", x, y, all_sprites, player_group, pygame.transform.scale( load_image('Player1.png', -1), tuple(map(int, (tile_size * 0.8, tile_size * 0.8)))), tile_size) elif level[y][x] == 'q': player2 = Player( "Player 2", x, y, all_sprites, player_group, pygame.transform.scale( load_image('Player2.png', -1), tuple(map(int, (tile_size * 0.8, tile_size * 0.8)))), tile_size) else: Tile( tile_render[level[y][x]], x, y, all_sprites, tile_group, pygame.transform.scale( load_image(tile_render[level[y][x]] + '.png'), (tile_size, tile_size)), tile_size) return player1, player2
def brier(models, surface, sy, ey, ts, r): matches = db_conn.all_matches_year(sy, ey, surface) rs = {} for model in models: rs[model] = [0, 0, 0] for match in matches: end_date = match[3] + datetime.timedelta(days=-1) start_date = end_date + datetime.timedelta(days=-r) if not Player.end_year == end_date.__str__(): Player.start_year = start_date.__str__() Player.end_year = end_date.__str__() Player.surface = surface Player.clean_cached_players() for model in models: p = Prediction(match[0], match[1], model, bo=3, ts=ts) p.predict_set_score() if p.match_winner_prob['p1'] > 1 or p.match_winner_prob['p1'] < 0: print p.match_winner_prob['p1'] continue if not np.isnan(p.match_winner_prob['p1']): rs[model][0] += 1 if match[2] == 1: if p.match_winner_prob['p1'] > 0.5: rs[model][1] += 1 rs[model][2] += (1 - p.match_winner_prob['p1'])**2 else: if p.match_winner_prob['p2'] > 0.5: rs[model][1] += 1 rs[model][2] += (1 - p.match_winner_prob['p2'])**2 return rs
def test_team_jsonable(self): player1 = Player("Marto") player2 = Player("Pesho") team1 = Team("Wolf") team1.add_team_members([player1, player2]) self.assertEqual( team1.to_json(), json.dumps( { "Wolf": [{ "Marto": { "points": 0, "announcements": [], "cards": [] } }, { "Pesho": { "points": 0, "announcements": [], "cards": [] } }] }, cls=OurEncoder))
def test_set_score(self): player_one = Player(PLAYER_NAME_ONE) player_two = Player(PLAYER_NAME_TWO) game = Game(player_one, player_two, False) game.score = PLAYER_NAME_ONE self.assertIsInstance(game.score, str)
def brier(model, surface, sy, ey, mixture, ts): matches = db_conn.all_matches_year(sy, ey, surface) c = 0 prob = 0 right = 0 for match in matches: end_date = match[3] + datetime.timedelta(days=-1) start_date = end_date + datetime.timedelta(days=-365) if not Player.end_year == end_date.__str__(): Player.start_year = start_date.__str__() Player.end_year = end_date.__str__() Player.surface = surface Player.clean_cached_players() p = PredictionSetend(match[0], match[1], model, points_played=match[5], mixture=mixture, ts=ts) p.predict_set_score() # print p.match_winner_prob['p1'], p.match_winner_prob['p2'], match if not np.isnan(p.match_winner_prob['p1']): c += 1 if match[2] == 1: if p.match_winner_prob['p1'] > 0.5: right += 1 prob += (1 - p.match_winner_prob['p1'])**2 else: if p.match_winner_prob['p2'] > 0.5: right += 1 prob += (1 - p.match_winner_prob['p2'])**2 return [c, right, prob]
def gamelogic(layer, tilesets): x = 0 y = 0 for data in layer['data']: if data > 0: for t in tilesets: if (t['firstgid'] <= data): tileset = t break id = data - t['firstgid'] + 1 if id == 1: #block c = Entity() c.set_collider(Collider()) c.set_position(sf.Vector2(x, y)) elif id == 2: #blob spawn m = Blob() m.set_position(sf.Vector2(x, y)) elif id == 6: #purple spawn m = Purple() m.set_position(sf.Vector2(x, y)) elif id == 10: #purple spawn m = Witch() m.set_position(sf.Vector2(x, y)) elif id == 3: #player spawn p = Player() p.set_position(sf.Vector2(x, y)) Scene.current().camera.set_parent(p) x += 1 if (x >= layer['width']): x = 0 y += 1
def Play_Game(self): """ Plays current game! original by Philip Johnson, modifications by Chadwick. """ player = Player( world ) # instantiate new player by giving it the loaded world model so it has all the map information. while player.is_alive() and self.game_active: room = world.tile_at(player.x, player.y) # Get current tile / room room.modify_player(player) if player.is_alive() and self.game_active: if room != world.tile_at( player.x, player.y ): # On NL, room was not being updated to fix this, we check to see if there are any updates. room = world.tile_at(player.x, player.y) room_strip = str(world.tile_at(player.x, player.y)).split( )[0].strip( '<' ) # checks current tile player is on, strips away unnecessary information. if room_strip == "classes.world.StartTile": print(room.level_name) print(room.intro_text()) self.choose_action(room, player) elif not player.is_alive(): print("%s has died! Game Over." % self.name)
def brier(model, surface, sy, ey, ts, r): matches = db_conn.all_matches_year(sy, ey, surface) c = 0 prob = 0 for match in matches: end_date = match[3] + datetime.timedelta(days=-1) start_date = end_date + datetime.timedelta(days=-r) if not Player.end_year == end_date.__str__(): Player.start_year = start_date.__str__() Player.end_year = end_date.__str__() Player.surface = surface Player.clean_cached_players() p = Prediction(match[0], match[1], model, bo=3, ts=ts) p.predict_set_score() pbp = match[5] pbp = pbp.split('.') actual_length = 0 for pbp_ in pbp: actual_length += pbp_.split(';').__len__() if p.match_winner_prob['p1'] > 1 or p.match_winner_prob['p1'] < 0: continue if not np.isnan(p.match_winner_prob['p1']): c += 1 prob += (p.match_length_mean - actual_length)**2 return [c, prob]
def gamelogic(layer, tilesets): x = 0 y = 0 for data in layer['data']: if data > 0: for t in tilesets: if(t['firstgid'] <= data): tileset = t break; id = data - t['firstgid'] +1 if id==1: #block c = Entity() c.set_collider(Collider()) c.set_position(sf.Vector2(x,y)) elif id==2: #blob spawn m = Blob() m.set_position(sf.Vector2(x,y)) elif id==6: #purple spawn m = Purple() m.set_position(sf.Vector2(x,y)) elif id==10: #purple spawn m = Witch() m.set_position(sf.Vector2(x,y)) elif id==3: #player spawn p = Player() p.set_position(sf.Vector2(x,y)) Scene.current().camera.set_parent(p) x += 1 if(x >= layer['width']): x = 0 y += 1
def scrape_pages(driver, env, team_rosters, players): pitcher_list = [] batter_list = [] for i, player in players.iterrows(): my_player = env['MY_PLAYERS'].get(player['espn_name']) team_id = team_rosters.get(player['bref_name']) if player['bref_id'] == '': continue if team_id is not None: player['team_id'] = team_id TEAM_ROSTER_NAMES_FOUND[player['bref_name']] = True elif TRANSLATIONS.get(player['bref_name']) is not None: translation = TRANSLATIONS.get(player['bref_name']) team_id = team_rosters.get(translation) player['team_id'] = team_id TEAM_ROSTER_NAMES_FOUND[translation] = True else: continue if TRADES.get(player['bref_name']) is not None: team_id = TRADES.get(player['bref_name']) #if team_id != 8: # continue print('Scraping Player: ' + player['bref_name'] + ' index: ' + str(i) + '\n\n') current_player = Player(player) if my_player is not None: current_player.mine = True # Baseball Reference br_url = env['BR_URL'] + current_player.bref_id if not current_player.batter: br_url = br_url + '&t=p' driver.get(br_url) tr_xpath_start = '//*[@id="total"]/tbody/tr' current_player = get_stats(driver, 'BR', tr_xpath_start, './/th[1]', current_player) tr_xpath_start = '//*[@id="plato"]/tbody/tr' current_player = get_stats(driver, 'BR', tr_xpath_start, './/th[1]', current_player) if not current_player.batter: tr_xpath_start = '//*[@id="total_extra"]/tbody/tr' current_player = get_stats(driver, 'BR', tr_xpath_start, './/th[1]', current_player) if current_player.batter: batter_list.append(current_player.to_dict()) else: pitcher_list.append(current_player.to_dict()) return { 'batter_list': batter_list, 'pitcher_list': pitcher_list, }
def __init__(self): # scene stuff super(InitialScreen, self).__init__() self.next_state = "GAMEPLAY" # board self.board = Board() # region positions self.positions = list() self.read_in_regions() # objects self.player = Player("Player") self.ai = Player("AI") # gui elements self.action_bar = ActionBar( 0, pygame.display.get_surface().get_height() - 80, pygame.display.get_surface().get_width(), 80, []) self.menu_bar = MenuBar(0, 0, pygame.display.get_surface().get_width(), 40, middle='Select a Starting Region') # flags self.user_choosing = True self.ai_choosing = False self.paused = False # timer for basic things self.end_time = time.time() # setup pause menu self.menu = Menu(w=300, h=400) self.menu.set_pos((pygame.display.get_surface().get_width() / 2, pygame.display.get_surface().get_height() / 2)) self.menu.set_title('Paused') self.menu.set_buttons(['Continue', 'Quit Game'])
def test_set_game(self): player_game = 6 player_one = Player(PLAYER_NAME_ONE) player_one.game = player_game self.assertIsInstance(player_one.game, int)
def test_score(self): player_one = Player(PLAYER_NAME_ONE) player_two = Player(PLAYER_NAME_TWO) set_game = Set(player_one, player_two) self.assertEqual(set_game.score, '0 - 0, 0 - 0') set_game.play_game(PLAYER_NAME_TWO) self.assertEqual(set_game.score, '0 - 0, 0 - 15')
def test_when_add_more_members_from_2_exception(self): member1 = Player("Pesho") member2 = Player("Gosho") member3 = Player("Thosho") team = Team("Wolf") with self.assertRaises(ValueError): team.add_team_members([member1, member2, member3])
def test_get_score(self): player_one = Player(PLAYER_NAME_ONE) player_two = Player(PLAYER_NAME_TWO) game = Game(player_one, player_two, False) game.score = PLAYER_NAME_ONE self.assertEqual(game.score, '15 - 0')
def test_score_tie_breaker(self): player_one = Player(PLAYER_NAME_ONE) player_two = Player(PLAYER_NAME_TWO) game = Game(player_one, player_two, True) game.score = PLAYER_NAME_ONE self.assertEqual(game.score, '1 - 0')
def TPlayer_to_player_Transaction(self): P1 = Player() P2 = Player() initMoneyP1 = P1.money initMoneyP2 = P2.money Bank.Player_to_player_Transaction(P1, P2, 100) unittest.assertTrue(P1.money == initMoneyP1 - 100 and P2.money == initMoneyP2 + 100)
def testNewPlayer(self): player = Player() self.assertEqual(player.name, None),"Unable to instantiate Player" self.assertEqual(player.photo, None),"Unable to instantiate Player" self.assertEqual(player.karma, 400),"Unable to instantiate Player" self.assertEqual(player.setName("Ricardo"), True), "Unable to set player's name" self.assertEqual(player.setPhoto("invalid/path/to/image.jpg"), False), "Player's class is accepting invalid photo image" self.assertEqual(player.setPhoto("images/test-image.jpg"), True), "Player's class isn't accepting valid photo image" self.assertEqual(player.photo, "images/test-image.jpg"), "Player's class isn't accepting valid photo image"
def setupPlayer(self): ''' Sets up player for the first level ''' self.player = Player(self.game_display, self.game_map, self.player_x, - 100) self.player_group = pygame.sprite.Group() self.player_group.add(self.player) self.characters = pygame.sprite.Group() self.characters.add(self.player)
def index(postVars): global votesToFinish global couchdbServer templateVars = dict() try: db = couchdbServer["currentgame"] except ResourceNotFound as exception: print "There's no active game" return output_template("error.html", templateVars) except: print "Unexpected error on get current game" return output_template("error.html", templateVars) currentGameId = "" for gameid in db: currentGameId = gameid game = Game.load(db,currentGameId) templateVars["opponent"] = game.opponent try: db = couchdbServer["players"] except ResourceNotFound as exception: print "Unable to access players database" return output_template("error.html", templateVars) except: print "Unexpected error accessing players database" return output_template("error.html", templateVars) # select randomly two different players faultSelectingPlayer = True; while faultSelectingPlayer: randomPlayersIds = game.getRandomPlayers() player0 = Player.load(db,randomPlayersIds[0]) player1 = Player.load(db,randomPlayersIds[1]) # are the two players valid? if player0 != None and player1 != None: faultSelectingPlayer = False # save photo files to static content directory player0.updatePhotoFileOnDisk(db) player1.updatePhotoFileOnDisk(db) templateVars["votesToFinish"] = votesToFinish templateVars["player0"] = player0 templateVars["player1"] = player1 return output_template("index.html", templateVars)
def __init__(self): ''' game init ''' #print(Deck()) print('BlackJack pays {}'.format(self.bj_pays)) self.deck = Deck() self.player = Player() self.dealer = Dealer() self.deck.shuffle()
def test_when_add_two_members_to_team_return_correctly(self): member1 = Player("Pesho") member2 = Player("Gosho") team = Team("Wolf") team.add_team_members([member1, member2]) self.assertEqual(len(team.players), 2) self.assertTrue(team.players.__contains__(member1)) self.assertTrue(team.players.__contains__(member2))
def __init__(self): pyxel.init(256, 150, caption='Corong', fps=60) self.virus = Virus() self.state = STATES['0'] self.player1 = Player('p1') self.player2 = Player('p2') self.score = Score(self.player1, self.player2) pyxel.load('assets/sprites.pyxres') pyxel.run(self.update, self.draw)
def test_play_game_deuce(self): player_one = Player(PLAYER_NAME_ONE) player_two = Player(PLAYER_NAME_TWO) set_game = Set(player_one, player_two) for index in range(4): set_game.play_game(PLAYER_NAME_ONE) set_game.play_game(PLAYER_NAME_TWO) self.assertEqual(set_game.score, '0 - 0, Deuce')
def addPlayer(postVars): global couchdbServer templateVars = dict(saved = False) try: templateVars["name"] = postVars["playerName"].value.decode("utf-8") templateVars["birth"] = postVars["playerBirth"].value.decode("utf-8") templateVars["nickname"] = postVars["playerNickname"].value.decode("utf-8") tempImagePath = "/tmp/%s" % postVars["playerPhoto"].filename tempImageFile = open(tempImagePath ,"w") tempImageFile.write(postVars["playerPhoto"].value) tempImageFile.close(); try: db = couchdbServer.create("players") except: db = couchdbServer["players"] player = Player() player.setName(templateVars["name"]) player.birth = templateVars["birth"] player.nickname = templateVars["nickname"] player.setPhoto(tempImagePath) player.store(db) templateVars["saved"] = True except KeyError: name = u"undef" return output_template("addPlayer.html", templateVars)
def test_get_score_deuce(self): player_one = Player(PLAYER_NAME_ONE) player_two = Player(PLAYER_NAME_TWO) game = Game(player_one, player_two, False) for index in range(4): game.score = PLAYER_NAME_ONE game.score = PLAYER_NAME_TWO # Check the Deuce game self.assertEqual(game.score, 'Deuce')
def test_game_jsonable(self): player1 = Player("Marto") player2 = Player("Pesho") player3 = Player("Nasko") player4 = Player("Petko") team1 = Team("Wolf") team2 = Team("Lion") team1.add_team_members([player1, player2]) team2.add_team_members([player3, player4]) round1 = Round("All trumps", 1) round1.add_round_members([team1, team2]) game = Game([team1, team2], 1) game.rounds.append(round1) self.assertEqual( game.to_json(), json.dumps( { "game 1": [{ "round 1": [{ "Wolf": [{ "Marto": { "points": 0, "announcements": [], "cards": [] } }, { "Pesho": { "points": 0, "announcements": [], "cards": [] } }] }, { "Lion": [{ "Nasko": { "points": 0, "announcements": [], "cards": [] } }, { "Petko": { "points": 0, "announcements": [], "cards": [] } }] }] }] }, cls=OurEncoder))
def __init__(self, difficulty, legumesFruits, game): self.difficulty = difficulty self.legumesFruits = legumesFruits self.images = self.loadImagesEnnemis() self.game = game self.player = Player() self.background = pygame.image.load(f'assets/backgrounds/backgroundD{difficulty}.jpg') self.background = pygame.transform.scale(self.background, (1024, 768)) self.liste_projectiles = [] self.time = 0 # Indique le nombre de frames effectuées dans le cauchemar depuis son début self.frequence = 75 - difficulty * 15 # La fréquence à laquelle on crée un ennemi self.cooldownDash = 120 # Permets de ne pas autoriser le joueur de faire des dash à l'infini mais toutes les deux secondes
def test_play_game_advantage(self): player_one = Player(PLAYER_NAME_ONE) player_two = Player(PLAYER_NAME_TWO) set_game = Set(player_one, player_two) for index in range(4): set_game.play_game(PLAYER_NAME_ONE) set_game.play_game(PLAYER_NAME_TWO) set_game.play_game(PLAYER_NAME_TWO) self.assertEqual(set_game.score, f'0 - 0, Advantage {PLAYER_NAME_TWO}')
def test_player_jsonable(self): player = Player("Marto") self.assertEqual( player.to_json(), json.dumps( {"Marto": { "points": 0, "announcements": [], "cards": [] }}, cls=OurEncoder))
def play(): world.load_tiles() player = Player() room = world.tile_exists(player.location_x, player.location_y) print(room.intro_text()) while player.is_alive() and not player.victory: room = world.tile_exists(player.location_x, player.location_y) room.modify_player(player) if room.id == CONST.EXIT_TILE_ID: player.victory = True if player.is_alive() and not player.victory: print("Choose an action:\n") available_actions = room.available_actions() for action in available_actions: print(action) action_input = input('Action: ') for action in available_actions: if action_input == action.hotkey: player.do_action(action, **action.kwargs) break
def player_enter(self, id=None): player = Player("content/entity/man", self) player.set_pos(0, 0, 0) player.set_move_task() player.id = id self.player_add(player, id) return player
def vote(postVars): global couchdbServer templateVars = dict() winnerId = postVars["winner"].value.decode("utf-8") loserId = postVars["loser"].value.decode("utf-8") try: db = couchdbServer.create("players") except: db = couchdbServer["players"] winner = Player.load(db,winnerId) loser = Player.load(db,loserId) match = Match() if postVars["draw"].value == "0": match.matchWithWinner(winner,loser) else: match.matchWithoutWinner(winner,loser) try: winner.store(db) except ResourceConflict: print "Unable to store winner" try: loser.store(db) except ResourceConflict: print "Unable to store loser" votesCount = classes.rankingsession.getSession("votesToFinish") votesCount -= 1 votesCount = classes.rankingsession.setSession("votesToFinish", votesCount) templateVars = dict(json = json.dumps(dict())) return output_template("json.html", templateVars )
def newGame(postVars): global couchdbServer players = [] try: db = couchdbServer.create("players") except: db = couchdbServer["players"] for playerId in db: players.append(Player.load(db,playerId)) return output_template("newGame.html", dict(players = players))
def updatePlayer(postVars): global couchdbServer playerId = postVars["playerId"].value.decode("utf-8") operation = postVars["operation"].value.decode("utf-8") jsonReturn = dict() jsonReturn["error"] = False try: db = couchdbServer.create("players") except: db = couchdbServer["players"] if operation == "delete": jsonReturn["htmlId"] = "row_%s" % playerId try: player = db[playerId] db.delete(player) except: jsonReturn["error"] = True elif operation == "resetKarma": jsonReturn["htmlId"] = "karma_col_%s" % playerId try: player = Player.load(db,playerId) player.resetKarma() jsonReturn["newKarma"] = "%.1f" % player.karma; player.store(db) except: jsonReturn["error"] = True templateVars = dict(json = json.dumps(jsonReturn)) return output_template("json.html", templateVars )
def main(): parser = argparse.ArgumentParser(description = "Video player wrapper for RaspberryPI.") parser.add_argument("--list", action='store_true', help = "List available files") parser.add_argument("--delete", help = "Delete provided file from repository") parser.add_argument("--play", help = "Play provided playlist") parser.add_argument("--stop", action='store_true', help = "Abort/stop player") parser.add_argument("--status", action='store_true', help = "Get status of player") args = parser.parse_args() if not (args.list or args.delete or args.play or args.stop or args.status): parser.error("At least one argument is expected.") else: configurations = SafeConfigParser() configurations.read("config.ini") playlistStore = PlaylistStoreMemcache ( configurations.get("Memcache", "Host"), configurations.get("Memcache", "Port") ) player = Player ( configurations.get("General", "SuperUserPrivilegesNeeded"), configurations.get("General", "FilesRepositoryAbsolutePath"), configurations.get("VideoPlayer", "Name"), configurations.get("VideoPlayer", "AbsolutePath"), configurations.get("VideoPlayer", "AdditionalArguments"), configurations.get("VideoUtility", "Name"), configurations.get("VideoUtility", "AbsolutePath"), configurations.get("VideoUtility", "AdditionalArguments"), playlistStore, configurations.get("Daemon", "PidFileAbsolutePath") ) if (args.list): print player.list() elif (args.delete): print player.delete(args.delete) elif (args.play): print player.play(json.loads(args.play)) elif (args.stop): print player.stop() else: print player.status()
class World(ShowBase): def __init__(self, reactor, is_server=False): ShowBase.__init__(self) self.reactor = reactor self.client = None self.players = {} self.player = None self.instance = None self.gc = globalClock self.load_instance("content/entity/terr") self.is_server = is_server if not is_server: self.set_player() Controls(self) def load_instance(self, model): self.instance = self.loader.loadModel(model) self.instance.reparentTo(render) #self.instance.setScale(0.25, 0.25, 0.25) self.instance.setPos(0, 0, 0) self.instance.setScale(5, 5, 5) def set_player(self): self.player = Player("content/entity/man", self) self.player.set_pos(0, 0, 0) self.player.set_move_task() self.player.is_player = True def player_enter(self, id=None): player = Player("content/entity/man", self) player.set_pos(0, 0, 0) player.set_move_task() player.id = id self.player_add(player, id) return player def player_add(self, player, id): # self.players.append(player) self.players[id] = player def state_change(self, data): """data: players, mobs fires then state changed Default - server version""" print 'Server stateChange', data def update_data(self, data): print "updateData", data if "add_player" in data: self.player_enter(data["add_player"]) if "player" in data: self.update_player(data["player"]) if "players" in data: for p in data["players"]: self.update_player(p) def update_player(self, data): player = None if "id" not in data or (not self.is_server and data["id"] == self.player.id): # Without ID it's client's player player = self.player elif "id" in data: if data["id"] in self.players: player = self.players[data["id"]] else: # Add player! player = self.player_enter(data["id"]) else: print "Incorrect data", data return if "action" in data: player.set_control(data["action"][0], data["action"][1]) if "actions" in data: player.actions = data["actions"] if "loc" in data: player.set_pos(data["loc"]) def get_players(self): return self.players def stop(self): print 'going to bed...' self.taskMgr.stop() print 'stop reactor' self.reactor.stop() print 'close window' self.closeWindow(self.win) print 'sys.exit' sys.exit() print 'user exit' base.userExit()
def viewRanking(postVars): global couchdbServer players = [] try: db = couchdbServer.create("players") except: db = couchdbServer["players"] for playerId in db: players.append(Player.load(db,playerId)) sortedPlayers = sorted(players, reverse=True, key=lambda player: player.karma) playersNames = [] playersKarmas = [] for player in sortedPlayers: playersKarmas.append(str(player.karma)) playersNames.append("\"%s\"" % player.name) try: db = couchdbServer.create("snapshots") except: db = couchdbServer["snapshots"] snapshots = [] lastOpponent = None for snapshotId in db: snapshot = Snapshot.load(db,snapshotId) snapData = {} snapData["decription"] = snapshot.description snapData["opponent"] = snapshot.game.opponent snapData["idx"] = "%d%d%d%d%d%d" % (snapshot.date.year, snapshot.date.month, snapshot.date.day, snapshot.date.hour, snapshot.date.minute, snapshot.date.second ) snapshotLabel = "%d/%d/%d" % (snapshot.date.day, snapshot.date.month, snapshot.date.year ) if snapshot.game.opponent != lastOpponent: lastOpponent = snapshot.game.opponent snapshotLabel = "%s %s" % (snapshot.game.opponent, snapshotLabel) snapData["label"] = snapshotLabel snapData["players"] = {} for player in snapshot.players: snapData["players"][player.name]= player.karma snapshots.append(snapData) sortedSnapshots = sorted(snapshots, key=lambda snapshot: snapshot["idx"]) templateVars = {} templateVars["playersKarmas"] = ",".join(playersKarmas) templateVars["playersNames"] = ",".join(playersNames) templateVars["jsonSnapshots"] = json.dumps(sortedSnapshots) return output_template("viewRanking.html", templateVars)
def set_player(self): self.player = Player("content/entity/man", self) self.player.set_pos(0, 0, 0) self.player.set_move_task() self.player.is_player = True
def testPlayerDb(self): server = Server() try: db = server.create("players") except: db = server["players"] bolivar = Player() bolivar.setName("Bolivar") bolivar.setPhoto("images/bolivar.jpg") bolivar.store(db) indio = Player() indio.setName("Indio") indio.setPhoto("images/indio.jpg") indio.store(db) nei = Player() nei.setName("Nei") nei.setPhoto("images/nei.jpg") nei.store(db) server.delete("players")
def testSnapshots(self): server = Server() try: db = server.create("players") except: db = server["players"] bolivar = Player() bolivar.setName("Bolivar") bolivar.setPhoto("images/bolivar.jpg") bolivar.setKarma(288) bolivar.store(db) indio = Player() indio.setName("Indio") indio.setPhoto("images/indio.jpg") indio.setKarma(388) indio.store(db) ss = Snapshot() ss.description = "Teste de snapshot" self.assertEqual(ss.takeSnapshot(), True), "Error taking snapshot" try: server.delete("snapshots") except: pass try: db = server.create("snapshots") except: db = server["snapshots"] ss.store(db) ss = Snapshot.load(db,ss.id) server.delete(ss.name) server.delete("snapshots")
def main(): global FPSCLOCK, DISPLAYSURF pygame.init() FPSCLOCK = pygame.time.Clock() # set up the window DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) pygame.display.set_caption('My Test Game') DISPLAYSURF.fill(BGCOLOR) field = Field() player = Player() curKey = NONE curKey2 = NONE posKey1 = NONE posKey2 = NONE while True: for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): pygame.quit() sys.exit() elif event.type == KEYDOWN and (event.key == K_UP or event.key == K_DOWN or event.key == K_LEFT or event.key == K_RIGHT): player.isActive = True if curKey == NONE: curKey = event.key elif event.key == posKey1 or event.key == posKey2: curKey2 = event.key posKey1 = NONE posKey2 = NONE if curKey2 == NONE: if curKey == K_UP: DIRECTION = UP posKey1 = K_LEFT posKey2 = K_RIGHT elif curKey == K_DOWN: DIRECTION = DOWN posKey1 = K_LEFT posKey2 = K_RIGHT elif curKey == K_LEFT: DIRECTION = LEFT posKey1 = K_UP posKey2 = K_DOWN elif curKey == K_RIGHT: DIRECTION = RIGHT posKey1 = K_UP posKey2 = K_DOWN else: if (curKey == K_UP and curKey2 == K_LEFT) or (curKey == K_LEFT and curKey2 == K_UP): DIRECTION = UPLEFT elif (curKey == K_UP and curKey2 == K_RIGHT) or (curKey == K_RIGHT and curKey2 == K_UP): DIRECTION = UPRIGHT elif (curKey == K_DOWN and curKey2 == K_LEFT) or (curKey == K_LEFT and curKey2 == K_DOWN): DIRECTION = DOWNLEFT elif (curKey == K_DOWN and curKey2 == K_RIGHT) or (curKey == K_RIGHT and curKey2 == K_DOWN): DIRECTION = DOWNRIGHT elif event.type == KEYUP and (event.key == curKey or event.key == curKey2): if event.key == curKey: if curKey2 != NONE: curKey = curKey2 curKey2 = NONE elif curKey2 == NONE: player.isActive = False DIRECTION = NONE curKey = NONE curKey2 = NONE posKey1 = NONE posKey2 = NONE elif event.key == curKey2: curKey2 = NONE if curKey == K_UP: DIRECTION = UP posKey1 = K_LEFT posKey2 = K_RIGHT elif curKey == K_DOWN: DIRECTION = DOWN posKey1 = K_LEFT posKey2 = K_RIGHT elif curKey == K_LEFT: DIRECTION = LEFT posKey1 = K_UP posKey2 = K_DOWN elif curKey == K_RIGHT: DIRECTION = RIGHT posKey1 = K_UP posKey2 = K_DOWN if player.isAtDestination and player.isActive: player.SetDestination(DIRECTION) if not player.isAtDestination: player.AnimateToDestination() field.DrawField(DISPLAYSURF, player) pygame.display.update() FPSCLOCK.tick(FPS)
def testExpectedResults(self): player0 = Player() player1 = Player() match = Match() self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.5), "Error estimating match result" player1.karma = 375 self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.5), "Error estimating match result" self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player0, player1), 1), "Error estimating match result" player1.karma = 374 self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.53), "Error estimating match result" self.assertEqual(match.getExpectedResultIndex(player0,player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result" player1.karma = 300 self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.57), "Error estimating match result" self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result" player1.karma = 299 self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.64), "Error estimating match result" self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result" player1.karma = 249 self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.7), "Error estimating match result" self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result" player1.karma = 199 self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.76), "Error estimating match result" self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result" player1.karma = 149 self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.81), "Error estimating match result" self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result" player1.karma = 99 self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.85), "Error estimating match result" self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result" player1.karma = 49 self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.89), "Error estimating match result" self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result" player1.karma = 0 self.assertEqual(match.getExpectedResultIndex(player0, player1), 0.92), "Error estimating match result" self.assertEqual(match.getExpectedResultIndex(player0, player1) + match.getExpectedResultIndex(player1, player0), 1), "Error estimating match result"
def testMatchesResults(self): server = Server() try: db = server.create("players") except: db = server["players"] player0 = Player() player0.store(db) player1 = Player() player1.store(db) match = Match() match.matchWithWinner(player0, player1) self.assertEqual(player0.karma, 405), "Error on match" self.assertEqual(player0.matches, 1), "Error on match" self.assertEqual(player0.wins, 1), "Error on match" self.assertEqual(player0.losses, 0), "Error on match" self.assertEqual(player1.karma, 395), "Error on match" self.assertEqual(player1.matches, 1), "Error on match" self.assertEqual(player1.wins, 0), "Error on match" self.assertEqual(player1.losses, 1), "Error on match" match.matchWithWinner(player1, player0) self.assertEqual(player0.karma, 400), "Error on match" self.assertEqual(player0.matches, 2), "Error on match" self.assertEqual(player0.wins, 1), "Error on match" self.assertEqual(player0.losses, 1), "Error on match" self.assertEqual(player1.karma, 400), "Error on match" self.assertEqual(player1.matches, 2), "Error on match" self.assertEqual(player1.wins, 1), "Error on match" self.assertEqual(player1.losses, 1), "Error on match" match.matchWithWinner(player0, player1) self.assertEqual(player0.karma, 405), "Error on match" self.assertEqual(player0.matches, 3), "Error on match" self.assertEqual(player1.karma, 395), "Error on match" self.assertEqual(player1.matches, 3), "Error on match" match.matchWithWinner(player0,player1) self.assertEqual(player0.karma, 410), "Error on match" self.assertEqual(player0.matches, 4), "Error on match" self.assertEqual(player1.karma, 390), "Error on match" self.assertEqual(player1.matches, 4), "Error on match" match.matchWithWinner(player0, player1) self.assertEqual(player0.karma, 415), "Error on match" self.assertEqual(player0.matches, 5), "Error on match" self.assertEqual(player1.karma, 385), "Error on match" self.assertEqual(player1.matches, 5), "Error on match" match.matchWithWinner(player0, player1) self.assertEqual(player0.karma, 419.7), "Error on match" self.assertEqual(player0.matches, 6), "Error on match" self.assertEqual(player1.karma, 380.3), "Error on match" self.assertEqual(player1.matches, 6), "Error on match" player0.resetKarma() player1.resetKarma() match.matchWithoutWinner(player0, player1) self.assertEqual(player0.karma, 400), "Error on match" self.assertEqual(player0.matches, 1), "Error on match" self.assertEqual(player1.karma, 400), "Error on match" self.assertEqual(player1.matches, 1), "Error on match" self.assertEqual(player1.wins, 0), "Error on match" self.assertEqual(player1.losses, 0), "Error on match" match.matchWithWinner(player0, player1) self.assertEqual(player0.karma, 405), "Error on match" self.assertEqual(player0.matches, 2), "Error on match" self.assertEqual(player1.karma, 395), "Error on match" self.assertEqual(player1.matches, 2), "Error on match" match.matchWithoutWinner(player0, player1) self.assertEqual(player0.karma, 405), "Error on match" self.assertEqual(player0.matches, 3), "Error on match" self.assertEqual(player1.karma, 395), "Error on match" self.assertEqual(player1.matches, 3), "Error on match" match.matchWithoutWinner(player0, player1) self.assertEqual(player0.karma, 405), "Error on match" self.assertEqual(player0.matches, 4), "Error on match" self.assertEqual(player1.karma, 395), "Error on match" self.assertEqual(player1.matches, 4), "Error on match"
def generateOpponent(self, player): enemyType = random.randint(0, 2) enemySkill = player.skill * random.randint(1, 4) * 0.12 return Enemy(enemyType, enemySkill) def playerLevelUp(self, player): player.level += 1 player.experience == 0 # Experience is per level player.skill += 5 player.maxHealthAndArmor() print("!! You have leveled up to level", player.level, "!!") game = Game() game.start() player = Player("Juha") while game.isRunning: enemy = game.generateOpponent(player) pick = input("Do you wish to attack? Y/N") if pick == "Y": while enemy.health >= 1: player.attack(enemy) if enemy.health >= 1: enemy.attack(player) else: experience = enemy.damage * 2 print(enemy.name, "is defeated! You have earned", experience, "XP!") player.experience += experience if player.experience >= player.level * 10: game.playerLevelUp(player)
def application(env, start_response): output = "" error = False form = cgi.FieldStorage( fp = env['wsgi.input'], environ = env, keep_blank_values = True ) # operation = form.getvalue('operation') queryStr = env['QUERY_STRING'] match = re.match('^operation=(play|stop|status|list|upload|delete)(&file=(.*))?', queryStr) if match is None: # if operation not in ['play','stop','status', 'list', 'upload', 'delete']: error = True else: operation = match.group(1) configurations = SafeConfigParser() configurations.read("config.ini") playlistStore = PlaylistStoreMemcache ( configurations.get("Memcache", "Host"), configurations.get("Memcache", "Port") ) player = Player ( configurations.get("General", "SuperUserPrivilegesNeeded"), configurations.get("General", "FilesRepositoryAbsolutePath"), configurations.get("VideoPlayer", "Name"), configurations.get("VideoPlayer", "AbsolutePath"), configurations.get("VideoPlayer", "AdditionalArguments"), configurations.get("VideoUtility", "Name"), configurations.get("VideoUtility", "AbsolutePath"), configurations.get("VideoUtility", "AdditionalArguments"), playlistStore, configurations.get("Daemon", "PidFileAbsolutePath") ) if (env['REQUEST_METHOD'] == "GET"): if (operation == "list"): output = player.list() elif (operation == "status"): output = player.status() else: error = True elif (env['REQUEST_METHOD'] == "POST"): if (operation == "play"): if getattr(form, "file"): jsonString = form.file.read() output = player.play(json.loads(jsonString)) else: error = True elif (operation == "upload"): fileItem = form['new_file'] if fileItem.filename: output = player.save(fileItem) else: error = True else: error = True elif (env['REQUEST_METHOD'] == "PUT"): if (operation == "stop"): output = player.stop() else: error = True elif (env['REQUEST_METHOD'] == "DELETE"): if (operation == "delete"): fileName = match.group(3) if fileName: output = player.delete(fileName) else: error = True else: error = True else: error = True if error: start_response("500 Internal Server Error", [("Content-Type", "text/html")]) else: start_response ("200 OK", [ ("Access-Control-Allow-Origin", "*"), ("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE"), ("Access-Control-Allow-Headers", "x-requested-with"), ("Content-Type", "application/json") ] ) return output