def post(self): self.response.out.write('METODO POST<br/>') opcao = self.request.get('opcao') self.response.out.write('Opcao:'+opcao+'<br>') if opcao == 'criar': name = self.request.get('name') player = Player(name=name) player.put() if opcao == 'listar': all_players = Player.all() for player in all_players: self.response.out.write('Player name:'+player.name+'<br>') ##################Joao Pedro################################# if opcao == 'upload': name = self.request.get('name') university = self.request.get('university') course= self.request.get('course') image = self.request.get('image') picture = Picture() """picture.image = db.Blob(image) picture.name = name picture.name_university = university picture.name_course = course""" #self.response.out.write('name:'+name+'<br>') #self.response.out.write('university:'+university+'<br>') #self.response.out.write('course:'+course+'<br>') picture.put() ###################################################### self.redirect('/')
def reply_handler(cls, action, response): if response == "Y" or response == "y": action.need_validation = False action.incorrect_kill = False action_key = action.put() victim = Player.get_by_id(action.victim) attacker = Player.get_by_id(action.attacker) victim.state = "DEAD" victim.killed_by = str(action_key.id()) victim.put() attacker.killed.append(str(action_key.id())) attacker.put() return [("*", "{} has been killed".format(victim.codename))] else: action.need_validation = False action.incorrect_kill = False action.put() return [ ( action.attacker, "Your victim claims that he/she was not " "killed. Please check that you have the correct codename", ) ]
def reply_handler(cls, action, response, from_): # Deep copy bomb action_c = Action() action_c.attacker = action.attacker action_c.action = action.action action_c.victim = from_.key.id() action_c.datetime = datetime.now() action_c.place = action.place if response == "Y" or response == "y": action_c.need_validation = False action_c.incorrect_kill = False action_c_key = action_c.put() victim = Player.get_by_id(action_c.victim) victim.state = "DEAD" victim.killed_by = str(action_c_key.id()) victim.put() attacker = Player.get_by_id(action_c.attacker) attacker.killed.append(str(action_c_key.id())) attacker.put() return [("*", "{} has been killed".format(victim.codename))] else: action_c.need_validation = True action_c.incorrect_kill = True return []
def initial_state(self): """ Change the state into initial state """ # init player self.player_list.append(Player(5, 0)) self.player_list.append(Player(5, 1)) # init King self.white_king = King(self.KING_HP_DEFAULT, self.KING_ATK_DEFAULT, 4, 8, self.player_list[0]) self.board[4][8] = self.white_king self.black_king = King(self.KING_HP_DEFAULT, self.KING_ATK_DEFAULT, 4, 0, self.player_list[1]) self.board[4][0] = self.black_king init_pawn_spawn = int(9 / 2) + 1 for i in range(init_pawn_spawn): self.white_pawn_list.append( SoldierPawn(i, self.PAWN_HP_DEFAULT, self.PAWN_ATK_DEFAULT, i * 2, 7, False, self.player_list[0], self.PAWN_STEP_DEFAULT)) self.board[i * 2][7] = self.white_pawn_list[i] self.black_pawn_list.append( SoldierPawn(i, self.PAWN_HP_DEFAULT, self.PAWN_ATK_DEFAULT, i * 2, 1, False, self.player_list[1], self.PAWN_STEP_DEFAULT)) self.board[i * 2][1] = self.black_pawn_list[i]
def test_player_at_game_change(mocker): ps = Playerset() gs = Gameset(ps) p = Player(**{"id_": 1, "login": "******"}) ps[p.id] = p p = Player(**{"id_": 2, "login": "******"}) ps[p.id] = p p = Player(**{"id_": 3, "login": "******"}) ps[p.id] = p data = copy.deepcopy(GAME_DICT) g1 = Game(playerset=ps, **data) gUpd = mocker.Mock() ps[1].newCurrentGame.connect(gUpd) gs[1] = g1 gUpd.assert_called_with(ps[1], g1, None) gUpd.reset_mock() data["state"] = GameState.PLAYING gs[1].update(**data) assert not gUpd.called data["state"] = GameState.CLOSED gs[1].update(**data) gUpd.assert_called_with(ps[1], None, g1)
def menu(): fast = False if fast: board = generate_board(3) return Game([Player("p1"), Player("p2")], board) players = [] print( '''Entre respectivamente o tamanho da quadra que voce quer usar, um valor de 3 a 10, e o qantidade de jogadores que vao jogar. Minimo 2, maximo 5, para sair digite sair a qualquer momento''' ) while True: board_size = int(input('Tamanho do tabuleiro: ')) if 2 < board_size <= 10: break while True: pos = len(players) player_name = input('Nome do jogador ' + (pos + 1).__str__() + ": ") players.append(Player(player_name)) # verifica se o tamanho do tabuleiro é 3 e se tem 2 jogadores e continua o jogo, fica impossivel # jogar com mais de dois jogadores no mesmo tabuleiro if board_size.__eq__(3) and len(players).__eq__(2): break if board_size > 3 and len(players) >= 2: more = input('Continuar(S/N)? ') if more.upper().__eq__("N"): break board = generate_board(board_size) return Game(players, board)
def test_game_fire(self, MockShip): ship = MockShip() ship.is_dead.return_value = False rules = Rules(mode='standard', opponent='human') player1 = Player('p1') player2 = Player('p2') player2.ships.append(ship) g = Game(1, player1, player2, rules) ship.is_hit.return_value = True expected = True actual = g.fire(Coordinates('a', 1)) self.assertEqual(expected, actual) g = Game(1, player1, player2, rules) ship.is_hit.return_value = False expected = False actual = g.fire(Coordinates('b', 3)) self.assertEqual(expected, actual) expected = False actual = g.fire(Coordinates('i', 10)) self.assertEqual(expected, actual)
def init_players(self, tournament_table, actors_db): """ Fonction qui instancie les joueurs du tournoi """ for i in range(8): input(f"\nEnter player{i+1} informations [ENTER]\n") name = vp.get_player_name() surname = vp.get_player_surname() birthday = vp.get_player_birthday() sexe = vp.get_player_sexe() elo = vp.get_player_elo() score = 0 player = Player(name, surname, birthday, sexe, elo, score) self.tournament_progress.add_player(player) serialized_player = player.serialize() actor_table = actors_db.table(f"{name}") User = Query() actor_table.upsert(serialized_player, User.name == name) self.tournament_progress.serialized_players.append( serialized_player) self.tournament_progress.serialized_tournament = ( self.tournament_progress.serialize()) tournament_table.truncate() tournament_table.insert(self.tournament_progress.serialized_tournament)
def create_players(tournament): """Fonction Permetant de creer huits joueurs a un tournoi""" enter_player = 1 while enter_player <= 8: player_list = select_players() selection = view.menu_create_player(player_list) if selection == 1: # --------------------------------------------------------------------------------- # Joueur existant view.print_actors(player_list) data = create_existing_player() player_db = Player(data['Nom'], data['Prenom'], data['Date de Naissance'], data['Sexe'], data['Classement']) # add the player id to the list of tournament players_id tournament.players_index_list.append(data.doc_id) # add the player to the list of tournament players with the tournament method tournament.add_player(player_db) # --------------------------------------------------------------------------------- elif selection == 2: # --------------------------------------------------------------------------------- # Nouveau joueur data = view.create_player_view(enter_player) player = Player(data['name'], data['first_name'], data['birth_day'], data['sex'], data['ranking']) # add the player to the list of tournament players with the tournament method tournament.add_player(player) # players are registered in the database save_player(player) # prendre l'identifiantiant du joueur for id_player in get_players_id(1): tournament.players_index_list.append(id_player) # --------------------------------------------------------------------------------- enter_player += 1
def spy(): logging.info("Spy cron") client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) ''' Get all ALIVE spies ''' alive_spies = Player.query(Player.role == "SPY").fetch() logging.info("Alive Spies:") logging.info(alive_spies) ''' For each spy, make and send hint ''' for spy in alive_spies: if spy.state == "DEAD": continue response = Player.spy_hint(spy) msg = Message(From=SERVER_NUMBER, To=spy.key.id(), Body=response) msg.put() client.messages.create( to=spy.key.id(), from_=SERVER_NUMBER, body=response) logging.info("SPY CRON: completed send to {}".format(alive_spies)) return "Ok"
def test_game_at_missing_player(mocker): ps = Playerset() gs = Gameset(ps) p = Player(**{"id_": 1, "login": "******"}) ps[p.id] = p p = Player(**{"id_": 2, "login": "******"}) ps[p.id] = p data = copy.deepcopy(GAME_DICT) g1 = Game(playerset=ps, **data) pAdd = mocker.Mock() g1.connectedPlayerAdded.connect(pAdd) gs[1] = g1 assert len(g1.players) == 3 gps = [g1.to_player(n) for n in g1.players if g1.is_connected(n)] assert len(gps) == 2 assert ps[1] in gps assert ps[2] in gps assert not pAdd.called p = Player(**{"id_": 3, "login": "******"}) ps[p.id] = p pAdd.assert_called_with(g1, ps[3]) gps = [g1.to_player(n) for n in g1.players if g1.is_connected(n)] assert len(gps) == 3 assert ps[3] in gps assert g1.is_ingame(ps[3].login) assert ps[3].currentGame is g1
def new_tournament(self): name = self.check_tournament_name() time_control = self.check_tournament_time_control() tournament_date = self.check_tournament_date() tournament_place = self.check_tournament_place() tournament_description = self.check_tournament_description() self.tournament = Tournament( name, time_control, tournament_date, tournament_place, tournament_description, ) for i in range(8): first_name = get_player_first_name() last_name = get_player_last_name() elo = get_player_elo() date_of_birth = get_date_of_birth() player_gender = get_player_gender() player = Player(first_name, last_name, elo, date_of_birth, player_gender) self.tournament.players.append(player) player.save_player() """self.tournament.players = players
def setUp(self): """ Creates a test fixture before each test method is run """ self.logPoint() self.test_player = Player(self.NO_ID, self.TEST_F_NAME, self.TEST_L_NAME, self.TEST_ADDRESS, self.TEST_PHONE, self.TEST_PLYR_POSITION, self.TEST_JERSEY_NUMBER, self.TEST_HOURLY_WAGE)
def get_victim(cls, victim_name): victim = Player.query(Player.codename == victim_name).get() if not victim: logging.error("Get Victim: victim {} not found".format(victim_name)) logging.error("Database looks like: {}".format(Player.query().fetch())) raise DbError(victim_name) logging.info("Get Victim: victim {} found".format(victim_name)) return victim
def dict_to_obj(cls, room_as_dict): room_id = room_as_dict['id'] room_name = room_as_dict['name'] room_state = room_as_dict['state'] room_players = [Player.dict_to_obj(player_as_dict) for player_as_dict in room_as_dict['players']] room_host = Player.dict_to_obj(room_as_dict['host']) room = cls(room_id, room_name, room_state, room_players, room_host) return room
def __init__(self): super().__init__() self.ui_manager = UIManager() self.controlador = controller.Controller() self.player_1 = Player('assets/blue') self.player_2 = Player('assets/yellow') self.cards_list = None self.text = "Jogador azul escolha carta 0/2"
def set_up(): global game global player_1 global player_2 player_1 = Player(name="Pascal") player_2 = Player(name="Alina") game = Game([player_1, player_2]) game.word = ['n', 'a', 'm', 'e']
def deserializing_players_list(self, players_dict): db = TinyDB('db.json', indent=4) player_table = db.table('players') self.players = [] for player_item in players_dict: player_dict = player_table.get(doc_id=player_item['id_player']) player = Player() player.deserializing_player(player_dict) self.players.append(player)
def on_mouse_press(self, x, y, _button, _modifiers): choice = arcade.get_sprites_at_point((x, y), self.personagem_list) if len(choice) > 0: if choice[0].tipo == 1: self.window.show_view( self.controlador.card_view(Player('assets/yellow'))) else: self.window.show_view( self.controlador.card_view(Player('assets/blue')))
def get_victim(cls, victim_name): victim = Player.query(Player.codename == victim_name).get() if not victim: logging.error( "Get Victim: victim {} not found".format(victim_name)) logging.error("Database looks like: {}".format( Player.query().fetch())) raise DbError(victim_name) logging.info("Get Victim: victim {} found".format(victim_name)) return victim
def setUp(self): self.game = Game([Player(1, "P1"), Player(2, "P2"), Player(3, "P3")]) self.game.game_variant = GameVariantGrand() self.game.players[0].type = Player.Type.DEFENDER self.game.players[1].type = Player.Type.DECLARER self.game.players[2].type = Player.Type.DEFENDER self.game.trick.leader = self.game.players[1] self.state = GameStatePlay(self.game) self.state_machine = GameStateMachine(self.state)
def test_game_next_player(self): rules = Rules(mode='standard', opponent='human') p1 = Player('p1') p2 = Player('p2') g = Game(1, p1, p2, rules) expected = p2 actual = g.next_player() self.assertEqual(expected, actual)
def choice_update_rank_player(): input_control = ReadInformation() id_player = input_control.read_id2() ranking = input_control.read_ranking() player = Player() ret = player.update_ranking2(id_player, ranking) if ret == 1: view.print_player_updated(player) else: view.print_msg_error_4() view.clear_screen()
def test_update_signal(mocker): p = Player(**DEFAULT_DICT) updated = mocker.Mock() def check_signal(new, old): assert old.number_of_games == 374 assert new.number_of_games == 375 p.updated.connect(updated) p.updated.connect(check_signal) p.update(number_of_games=375) assert updated.called
def update_scores(self, match): """ Update score of both Match and Player table Args: match: match to update """ while True: response = self.select.write_score_menu(match) if input_validators.is_valid_write_score_menu_response(response): break Match.update_score_match(self, match, response, self.match_table) Player.update_score_player(self, match, response, self.player_table)
def remote_createGame(self, playerOneSymbol, playerOneType, playerTwoSymbol, playerTwoType, searchDepth=0, cbk=None): """Creates a new Game object. Args: playerOneSymbol (int) playerOneType (int) playerTwoSymbol (int) playerTwoType (int) searchDepth (Optional[int]) Returns: UUID: The UUID of the newly created game. Raises: ValueError """ # creates the game playerOne = Player.playerBuilder().symbol(playerOneSymbol). \ type(playerOneType).build() playerTwo = Player.playerBuilder().symbol(playerTwoSymbol). \ type(playerTwoType).build() if playerOne.isAi: playerOne.depth = searchDepth elif playerTwo.isAi: playerTwo.depth = searchDepth else: raise ValueError('No AI player') game = Game.create(playerOne, playerTwo) # stores the game in our map self._games[game.uuid] = game # returns the GUID back to the caller self.log.info('A new game ({uuid}) was created', uuid=game.uuid) # starts the game try: game.start() except Exception, e: self.log.failure( 'Failed to start the game {0}. Reason: {1}'.format( game.uuid, str(e)))
def deserializer(name): db = TinyDB("db_tournament.json", indent=4) tournaments = db.table("Tournaments") tournament = Query() tournament = tournaments.search(tournament.name == name)[0] reload_tournament = Tournament( tournament["name"], tournament["time control"], tournament["place"], tournament["date"], tournament["description"], ) for player in tournament["players"]: reload_player = Player( player["first name"], player["last name"], player["elo"], player["date of birth"], player["player's gender"], player["score"], player["opponent list"], ) reload_tournament.add_player(reload_player) for round in tournament["rounds"]: reload_round = Round(round["number"]) for match in round["matchs"]: player1 = Player( match["player1"]["first name"], match["player1"]["last name"], match["player1"]["elo"], match["player1"]["date of birth"], match["player1"]["player's gender"], match["player1"]["score"], match["player1"]["opponent list"], ) player2 = Player( match["player2"]["first name"], match["player2"]["last name"], match["player2"]["elo"], match["player2"]["date of birth"], match["player2"]["player's gender"], match["player2"]["score"], match["player2"]["opponent list"], ) reload_match = Match(player1, player2, match["score player 1"], match["Score player 2"]) reload_round.add_reload_match(reload_match) reload_tournament.add_round(reload_round) return reload_tournament
def test_next_guessing_player_current_not_none(): global game start_test('test_next_guessing_player_current_not_none') game.current_player = game.players[0] next_player_1 = game.next_guessing_player(game.players[1]) next_player_2 = game.next_guessing_player(next_player_1) current_correct = game.current_player == Player(name="Pascal") player_1_correct = next_player_1 == Player(name="Alina") player_2_correct = next_player_2 == Player(name="Alina") return current_correct and player_1_correct and player_2_correct
def post(self): self.response.out.write('METODO POST<br/>') opcao = self.request.get('opcao') self.response.out.write('Opcao:'+opcao+'<br>') if opcao == 'criar': name = self.request.get('name') player = Player(name=name) player.put() if opcao == 'listar': all_players = Player.all() for player in all_players: self.response.out.write('Player name:'+player.name+'<br>')
def test_hasTrump_withoutTrump(self): # given player = Player(1, "Player") player.cards = [ Card(Card.Suit.DIAMOND, Card.Face.SEVEN), Card(Card.Suit.DIAMOND, Card.Face.EIGHT) ] # when result = self.game_variant.has_trump(player) # then self.assertFalse(result)
def add_players_to_tournament(self): """ Add players to tournament. Initialize their score to 0. """ number_of_player = 0 list_of_players_added = [] list_of_remaining_players = Player.list_of_remaining_players( self, self.player_table ) while number_of_player < 8: self.table.remaining_players(list_of_remaining_players) self.warning.remaining_players_to_add(number_of_player) while True: response = self.select.add_player_create_tournament_menu() if input_validators.is_valid_add_player_create_tournament_menu_response( response ): break if response == "1": if not self.player_table or list_of_remaining_players == []: self.warning.no_player() continue while True: existed_player_id = int( self.choice_player_for_add_player_to_a_tournament() ) if input_validators.is_valid_id_player(existed_player_id) is True: break list_of_players_added.append(existed_player_id) elif response == "2": new_player_id = self.create_player_in_tournament() existed_player_id = new_player_id list_of_players_added.append(new_player_id) number_of_player += 1 contains_duplicates = any( list_of_players_added.count(element) > 1 for element in list_of_players_added ) if contains_duplicates: list_of_players_added.pop(-1) number_of_player -= 1 self.warning.add_a_player_several_time() continue self.tournament_table.update( {"players": list_of_players_added}, doc_ids=[self.tournament_table.all()[-1].doc_id], ) Player.initialize_score(self, self.player_table, self.tournament_table) for player in list_of_remaining_players: if player[0] == existed_player_id: list_of_remaining_players.remove(player)
def setup(): ps = Playerset() gs = Gameset(ps) p = Player(**{"id_": 1, "login": "******"}) ps[p.id] = p p = Player(**{"id_": 2, "login": "******"}) ps[p.id] = p p = Player(**{"id_": 3, "login": "******"}) ps[p.id] = p g = Game(playerset=ps, **GAME_DICT) gs[g.uid] = g return ps, gs
def validate(db: StandardDatabase, token, email=None): """ validate player token :param db: connection :param token: jwt token :param email: mail :return Player or None """ if not db.has_collection('players'): logger.error('cannot validate token if players do not exist') raise PlayerStateException('players collection does not exist') col = db.collection('players') if email: db_player = next(col.find({'mail': email}), None) if not db_player: logger.error(f'could not resolve player {email}') raise PlayerStateException(f'player {email} does not exist') if token in db_player['tokens']: player = Player(db_player['mail'], '') player.id = UUID(db_player['_key']) player.password = db_player['password'] return player else: for db_player in col.all(): if 'tokens' in db_player and token in db_player['tokens']: player = Player(db_player['mail'], '') player.id = UUID(db_player['_key']) player.password = db_player['password'] return player return None
def test_next_player(): global game start_test('test_next_player') first = game.next_player() game.current_player = first first_correct = first == Player(name="Pascal") second = game.next_player() game.current_player = second second_correct = second == Player(name="Alina") last = game.next_player() == Player(name="Pascal") return first_correct and second_correct and last
def remote_createGame(self, playerOneSymbol, playerOneType, playerTwoSymbol, playerTwoType, searchDepth=0, cbk=None): """Creates a new Game object. Args: playerOneSymbol (int) playerOneType (int) playerTwoSymbol (int) playerTwoType (int) searchDepth (Optional[int]) Returns: UUID: The UUID of the newly created game. Raises: ValueError """ # creates the game playerOne = Player.playerBuilder().symbol(playerOneSymbol). \ type(playerOneType).build() playerTwo = Player.playerBuilder().symbol(playerTwoSymbol). \ type(playerTwoType).build() if playerOne.isAi: playerOne.depth = searchDepth elif playerTwo.isAi: playerTwo.depth = searchDepth else: raise ValueError('No AI player') game = Game.create(playerOne, playerTwo) # stores the game in our map self._games[game.uuid] = game # returns the GUID back to the caller self.log.info('A new game ({uuid}) was created', uuid=game.uuid) # starts the game try: game.start() except Exception, e: self.log.failure('Failed to start the game {0}. Reason: {1}'. format(game.uuid, str(e)))
def inner_handler(cls, message): """ Return [(number, msg),...]""" action, params = CommandHandler.get_command(message.Body) attacker = Util.get_attacker(message.From) if action == "KILL": return Kill.handler(attacker, params) elif action[1:] == "REPLY": ref = params.pop(0)[:-1] return Reply.handler(ref, params, attacker) elif action == "BOMB": return Bomb.handler(attacker, params) elif action == "INVUL": return Invul.handler(attacker, params) elif action == "DISARM": return Disarm.handler(attacker, params) elif action == "SNIPE": if message.From != WEI_HAN: raise CommandError(action) sniper = Player.query(Player.codename == params[0]).get() if sniper == None: raise DbError(params[0]) return Snipe.handler(sniper, params[1]) elif action == "?": msg = "Guide for SAMSU Assassins:\n" msg += "KILL <target codename>\n" msg += "BOMB <mm> <dd> <hour> <min> <place>\n" msg += "INVUL <target codename> <mm> <dd> <hour> <min>\n" msg += "DISARM <target codename>\n" msg += "SNIPE - send message and picture to {}\n".format(WEI_HAN) msg += "REPLY - [REPLY <number>] Y or [REPLY <number>] N\n" msg += "If you receive an UNKNOWN ERROR or don't get a message that you expect, contact Wei Han at 312-731-0539." return [(attacker.key.id(), msg)] else: raise CommandError(action)
def reply_handler(cls, action, response): if response == "Y" or response == "y": action.need_validation = False action.incorrect_kill = False action_key = action.put() victim = Player.get_by_id(action.victim) victim.disarm = True victim.put() disarm = Disarm() disarm.attacker = action.attacker disarm.victim = action.victim disarm.starttime = datetime.now() disarm.endtime = datetime.now() + timedelta(hours = 1) disarm_key = disarm.put() task = taskqueue.Task(url="/disarm", params={"id": disarm_key.id()}, eta=disarm.endtime) task.add(queue_name="disarm") q = taskqueue.Queue('disarm').fetch_statistics() logging.critical(q) return [(action.victim, "You have been DISARM until {}".format(\ Util.utc_to_chi(disarm.endtime).strftime("%m-%d %I:%M%p")))] else: action.need_validation = False action.incorrect_kill = False action.put() return [(action.attacker, "Your DISARM target claims he was not " "disarmed by you.")]
def _kill(self): if self.action.need_validation: response_number = [self.action.victim] response = "[REPLY {}] Were you recently killed? Reply 'Y' or 'N'.".format(self.action_key) else: response_number = [self.all_numbers] victim = Player.get_by_id(self.action.victim) response = "{} has been killed".format(victim.id()) return response_number, response
def get_attacker(cls, attacker_number): attacker = Player.get_by_id(attacker_number) if not attacker: logging.error( "Get Attacker: attacker number {} not found in \ get_attacker()".format( attacker_number ) ) raise DbError(attacker_number) logging.info("Get Attacker: attacker {} found".format(attacker.realname)) return attacker
def handler(cls, message): responses = CommandHandler.inner_handler(message) output_responses = [] for (response_to, response) in responses: if response_to == "" and response == "": break if response_to == "*": response_num_list = [key.id() for key in Player.query().fetch(keys_only=True)] else: response_num_list = [response_to] output_responses.append((response_num_list, response)) return output_responses
def handler(cls, attacker, victim_codename): logging.info("SNIPE start.") victim = Util.get_victim(victim_codename) logging.info("Attacker {}".format(attacker)) logging.info("Victim {}".format(victim)) """ validation """ outgoing = [] try: Kill.validate_kill(attacker, victim) if attacker.role != "SNIPER": raise MeError("not SNIPER") except (TeamError, MeError, TargetError) as message: outgoing.append((WEI_HAN, message.message)) outgoing.append((attacker.key.id(), message.message)) return outgoing except: message = "[ERR] Unknown Error in SNIPE" outgoing.append((WEI_HAN, message)) outgoing.append((attacker.key.id(), message)) return outgoing action = Action() action.attacker = attacker.key.id() action.action = "SNIPE" action.victim = victim.key.id() action.datetime = datetime.now() action_key = action.put() attacker = Player.get_by_id(action.attacker) attacker.killed.append(str(action_key.id())) attacker.put() victim.state = "DEAD" victim.killed_by = str(action_key.id()) victim.put() message = "{} has been SNIPED.".format(victim_codename) outgoing.append((victim.key.id(), "You have been SNIPED. (Ref {}).".\ format(action_key.id()))) outgoing.append(("*", message)) outgoing += Team.push(Team.get_by_id(victim.team)) return outgoing
def get(self): query = Player.all() players = query.fetch(limit=None) query = Picture.all() pictures = query.fetch(limit=None) upload_picture = blobstore.create_upload_url('/upload_picture') template_values = { 'players': players, 'pictures': pictures, 'upload_picture': upload_picture, } template = jinja_environment.get_template('index.html') self.response.out.write(template.render(template_values))
def disarm_worker(): ''' Get disarm id''' req_key = request.form.get("id", "") disarm = Disarm.get_by_id(int(req_key)) ''' No disarm found ''' if not disarm: logging.error("DISARM worker: no DISARM found") raise Exception() '''Disarm deprecated''' if disarm.deprecated: logging.info("DISARM Worker: Disarm deprecated. No action.") return "DISARM Worker: deprecated" client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) disarmed_player = Player.get_by_id(disarm.victim) disarmed_player.disarm = False disarmed_player.put() disarm.deprecated = True disarm.put() logging.info("DISARM Worker: Turning off disarmed state for {}".format(\ disarm.victim)) response = "You are no longer DISARMED. Go ahead and kill people." msg = Message(From=SERVER_NUMBER, To=disarm.victim, Body=response) msg.put() client.messages.create( to=disarm.victim, from_=SERVER_NUMBER, body=response) return "DISARM WORKER"
def test_player_rotates(): player = Player() rot_before = player.rotation[0] player.rotate(90) rot_after = player.rotation[0] assert rot_after == rot_before + 90
# -*- coding: utf-8 -*- import datetime import json from model.player import Player from model.admin import Admin, Moderator from model.session import Session from model.money import Money, Wallet,GOLD,SILVER,COPPER if __name__=="__main__": player = Player(nickname='Arseni', email='*****@*****.**', password='******') print("{}Information about the player.\n".format(player)) player.save_to_db() print("{}Player was inserted to db.\n".format(player)) admin = Admin(nickname='admin_arseni', email='*****@*****.**', password='******') print("{}Information about the player.\n".format(admin)) admin.save_to_db() print("{}Admin was inserted to db.\n".format(admin)) moderator = Moderator(nickname='moderator_arseni', email='*****@*****.**', password='******') print("{}Information about the player.\n".format(moderator)) moderator.save_to_db() print("{}Moderator was inserted to db.\n".format(moderator))
def test_player_doesnt_rotate_over_90_degrees(): player = Player() player.rotation = (85, 0) player.rotate(10) assert (5, 0) == player.rotation
def bomb_worker(): ''' Get bomb id ''' req_key = request.form.get('id', "") bomb = Bomb.get_by_id(int(req_key)) ''' ERROR: no bomb found by id ''' if not bomb: logging.error("BOMB Worker: No bomb found by key {}".format(req_key)) raise Exception() ''' Bomb deprecated no action ''' if bomb.deprecated: logging.info("BOMB Worker: Bomb with key {} deprecated. No explosion".format(req_key)) return "BOMB Worker: Deprecated Bomb" ''' Trigger bomb ''' logging.info("BOMB: triggered at {} UTC {} Chicago".format( datetime.now(), Util.utc_to_chi(datetime.now().replace(tzinfo=pytz.utc)))) client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) attacker = Player.get_by_id(bomb.attacker) attacker.can_set_after = Util.next_day() attacker.put() bomb.trigger = True bomb_key = bomb.put() action = Action() action.attacker = bomb.attacker action.action = "BOMB" action.victim = "*" action.datetime = datetime.now() action.place = bomb.place action_key = action.put() response_num_list = [key.id() for key in Player.query(ndb.AND(Player.state=="ALIVE",\ Player.invul==False) ).fetch(keys_only=True)] response = "{} has been bombed at {}. If you were there, [REPLY {}] Y.".format( action.place, Util.utc_to_chi(action.datetime).strftime("%m-%d %I:%M%p"), action_key.id()) for response_number in response_num_list: logging.info("Making message {} for {} with num_list {}".format( response, response_number, response_num_list)) '''Make message''' outgoing_message = Message(From=SERVER_NUMBER, To=response_number, Body=response) outgoing_message.put() '''Send message''' client.messages.create( to=response_number, from_=SERVER_NUMBER, body=response) return "Bomb triggered at {}".format(bomb.place)
def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() ndb.get_context().clear_cache() self.testbed.init_taskqueue_stub(root_path=".") self.taskqueue_stub = self.testbed.get_stub(testbed.TASKQUEUE_SERVICE_NAME) # Setup fixture today = Util.next_day() - timedelta(days=1) # Make Team 1 and populate with player 1a, 1b, 1c. # p1a is ALIVE and DEMO # p1b is ALIVE, DISARM, and SNIPER # p1c is ALIVE, MEDIC self.team1 = Team(id="Team1", to_kill="Team2", target_of="Team3") self.p1a = Player( id="+1", realname="player1a", codename="p1a", team="Team1", state="ALIVE", role="DEMO", can_set_after=today ) self.team1.demo = "+1" self.p1a.put() self.p1b = Player( id="+2", realname="player1b", codename="p1b", team="Team1", state="ALIVE", disarm=True, role="SNIPER", can_set_after=today, ) self.team1.sniper = "+2" self.p1b.put() self.p1c = Player( id="+3", realname="player1c", codename="p1c", team="Team1", state="ALIVE", role="MEDIC", can_set_after=today ) self.team1.medic = "+3" self.p1c.put() self.team1.put() # Make Team 2 and populate with player 2a, 2b, 2c. # p2a is ALIVE # p2b is DEAD # p2c is INVUL self.team2 = Team(id="Team2", to_kill="Team3", target_of="Team1") self.p2a = Player( id="+4", realname="player2a", codename="p2a", team="Team2", state="ALIVE", role="DEMO", can_set_after=today ) self.team2.demo = "+4" self.p2a.put() self.p2b = Player( id="+5", realname="player2b", codename="p2b", team="Team2", state="DEAD", role="SNIPER", can_set_after=today ) self.team2.sniper = "+5" self.p2b.put() self.p2c = Player( id="+6", realname="player2c", codename="p2c", team="Team2", state="ALIVE", invul=True, role="MEDIC", can_set_after=today, ) self.team2.medic = "+6" self.p2c.put() self.team2.put() # Make Team 3 and populate with player 3a, 3b, 3c. self.team3 = Team(id="Team3", to_kill="Team1", target_of="Team2") self.p3a = Player( id="+7", realname="player3a", codename="p3a", team="Team3", state="ALIVE", role="DEMO", can_set_after=today ) self.team3.demo = "+7" self.p3a.put() self.p3b = Player( id="+8", realname="player3b", codename="p3b", team="Team3", state="ALIVE", role="SPY", can_set_after=today ) self.team3.sniper = "+8" self.p3b.put() self.p3c = Player( id="+9", realname="player3c", codename="p3c", team="Team3", state="ALIVE", role="MEDIC", can_set_after=today ) self.team3.medic = "+9" self.p3c.put() self.team3.put()
def invul_worker(): ''' Get invul id''' req_key = request.form.get("id", "") inv = Invul.get_by_id(int(req_key)) ''' No Inv found ''' if not inv: logging.error("INV worker: no INV found") raise Exception() '''Inv deprecated''' if inv.deprecated: logging.info("INV Worker: Inv deprecated. No action.") return "INVUL Worker: Deprecated" client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) '''Target dead. Report back to medic''' logging.info(inv) target_num = inv.target logging.info(target_num) target = Player.get_by_id(target_num) medic = Player.get_by_id(inv.medic) logging.info(medic) if not target: logging.error("INV worker: cannot find target {}".format(target_num)) return if target.state == "DEAD": logging.error("INV worker: Target {} has died. Cannot grant INVUL".format(target.codename)) response = "Your INVUL target has died. Cannot grant dead people INVUL." msg = Message(From=SERVER_NUMBER, To=inv.medic, Body=response) msg.put() client.messages.create( to=inv.medic, from_=SERVER_NUMBER, body=response) return "INVUL Worker" '''Target alive. If INVUL not yet in effect, trigger''' if not inv.in_effect: logging.info("INVUL worker: Triggering 8 hour INVUL for target {} at {}".format(target.codename, datetime.now())) inv.in_effect = True inv_key = inv.put() task = taskqueue.Task(url="/invul", params={"id": inv_key.id()}, eta=inv.end_time) task.add(queue_name="invul") logging.info("Task queue okay") logging.info(target) target.invul = True target.put() logging.info("target set okay") logging.info(medic) medic.can_set_after = Util.next_day() medic.put() logging.info("medic set okay") response = "You have been granted INVUL for 8 hour from {} to {}".\ format(Util.utc_to_chi(inv.start_time).strftime("%m-%d %I:%M%p"),\ Util.utc_to_chi(inv.end_time).strftime("%m-%d %I:%M%p")) msg = Message(From=SERVER_NUMBER, To=inv.target, Body=response) msg.put() client.messages.create( to=inv.target, from_=SERVER_NUMBER, body=response) logging.info("message set okay") return "INVUL Worker" else: logging.info("INVUL worker: END 8 hour INVUL for target {} at {}".format(target.codename, datetime.now())) inv.deprecated = True inv.put() target.invul = False target.put() response = "Your INVUL period has ended. You are no longer INVUL." msg = Message(From=SERVER_NUMBER, To=inv.target, Body=response) msg.put() client.messages.create( to=inv.target, from_=SERVER_NUMBER, body=response) return "INVUL Worker"
def parseTeam(teamUrl): data = urllib2.urlopen(teamUrl) soup = BeautifulSoup(data.read()) players = [] # List of all td's in order for team players # print soup.find_all('a') # # 0 Name # # # 2 GP # 3 Goals # 4 Ass. # 5 PPG # 6 PPA # 7 SHG # 8 SHA # 9 GWG # 10 GWA # 11 PSG # 12 ENG # 13 SOG # 14 Pts for tr in soup.find_all('tr'): if tr and tr.td and tr.td.get('align'): tds = tr.find_all('td') # Only get the player stats if len(tds) == 15 : #print len(tds) #print(tds) #print( type(tds)) newPlayer = Player() #assert isinstance(newPlayer, Player) i = 0 for td in tds: #print td if i==0: newPlayer.name = td.string elif i == 1: newPlayer.number = td.string elif i == 2: newPlayer.gamesPlayed = td.string elif i == 3: newPlayer.goals = td.string elif i == 4 : newPlayer.assists = td.string elif i == 14 : newPlayer.points = td.string i = i + 1 if int(newPlayer.gamesPlayed) != 0 : newPlayer.average = float(float(newPlayer.points) / float(newPlayer.gamesPlayed)) else : newPlayer.average = float(0.0) players.append(newPlayer) return players
def setUp(self): """ Creates a new instance of a Player. """ self.player = Player('LizTest')
def __init__(self, action_key, action): self.action_key = action_key self.action = action numbers_qry = Player.query() all_keys = numbers_qry.fetch(keys_only=True) self.all_numbers = [key.id() for key in all_keys]
from model.player import Player from model.admin import Admin, Moderator from model.session import Session from model.money import Money, Wallet,GOLD,SILVER,COPPER if __name__=="__main__": gold = Money(code=1, amount=10) silver = Money(code=2, amount=100) copper = Money(code=3, amount=1000) wallet = Wallet(gold,silver,copper) arseni = Player(nickname = 'Arseni', email = '*****@*****.**', password = '******', wallet=wallet) arseni.save(open("arseni_player.txt", "w")) print(u"Player is:" u"\n#################################################\n" \ u"{}" u"\n#################################################\n".format(arseni)) arseni2 = Player(nickname = 'Arseni2', email = '*****@*****.**', password = '******', wallet=wallet) arseni2.load(open("arseni_player.txt")) print(u"Deserialized player is:" u"\n#################################################\n" \ u"{}" u"\n#################################################\n".format(arseni2)) ########################################################################################################################
def test_player_tilts(): player = Player() tilt_before = player.rotation[1] player.tilt(45) tilt_after = player.rotation[1] assert tilt_after == tilt_before + 45
class TestPlayer(unittest.TestCase): """ Tests the functionality of a Player. """ def setUp(self): """ Creates a new instance of a Player. """ self.player = Player('LizTest') def tearDown(self): """ Sets the original user data. """ self.player.data = { 'username': '******', 'games_played': 10, 'games_won': 5, 'longest_winning_streak': 3, 'longest_losing_streak': 2, 'current_streak': 1, 'shortest_winning_time': '00:01:03', 'longest_winning_time': '00:05:15', 'average_winning_time': '00:02:30', 'fewest_winning_moves': 100, 'most_winning_moves': 150, 'average_winning_moves': 125.3, 'highest_score': 1025, 'lowest_score': 350, 'average_score': 757.4 } self.player.db.update_all('LizTest', self.player.data) self.player.current_score = 0 self.player.current_moves = 0 self.player.current_time = 0 def test_init(self): """ """ self.assertEqual(self.player.username, 'LizTest') self.assertEqual(self.player.current_score, 0) self.assertEqual(self.player.current_moves, 0) self.assertEqual(self.player.current_time, 0) def test_usernameExists(self): """ Tests the username_exists function. """ self.assertTrue(self.player.username_exists('LizTest')) def test_getStatistics(self): """ Tests that a Player can get his or her statistics in a dictionary. """ keys = [ 'username', 'average_winning_time', 'most_winning_moves', 'average_score', 'games_won', 'highest_score', 'shortest_winning_time', 'average_winning_moves', 'fewest_winning_moves', 'longest_winning_streak', 'current_streak', 'longest_winning_time', 'lowest_score', 'games_played', 'id', 'longest_losing_streak' ] keys.sort() data = self.player.get_statistics() got_keys = data.keys() got_keys.sort() self.assertEqual(got_keys, keys) def test_changeUsername(self): """ Tests that a Player can change his or her username, and that the resulting change will maintain his or her existing statistics in the database. """ self.player.change_username('Liztest') self.assertEqual(self.player.username, 'Liz_Test') self.assertFalse(self.player.username_exists('LizTest')) self.assertTrue(self.player.username_exists('Liz_Test')) self.player.change_username('LizTest') self.assertEqual(self.player.username, 'LizTest') self.assertTrue(self.player.username_exists('LizTest')) self.assertFalse(self.player.username_exists('Liz_Test')) def test_winPercentage(self): """ Tests that a player calculates his or her win percentage correctly. """ percent = self.player.calculate_win_percentage() self.assertEqual(percent, 50.0) def test_updateCurrentScore(self): """ Tests that moving certain piles and cards updates scores correctly. """ score = self.player.current_score self.player.update_current_score(10) self.assertEqual(self.player.current_score, score + 10) def test_updateStreaks(self): """ """ longest_winning_streak = self.player.data["longest_winning_streak"] longest_losing_streak = self.player.data["longest_losing_streak"] current_streak = self.player.data["current_streak"] def test_updateScoresMiddle(self): """ Tests that when a game has ended the user's best/worse/average scores are updated in the database. """ old_highest = self.player.data["highest_score"] old_lowest = self.player.data["lowest_score"] self.player.data["games_played"] += 1 self.player.current_score = 500 self.player.update_scores(self.player.current_score) self.assertEqual(self.player.data["highest_score"], old_highest) self.assertEqual(self.player.data["lowest_score"], old_lowest) self.assertEqual(self.player.data["average_score"], 734.0) def test_updateScoresHighest(self): old_lowest = self.player.data["lowest_score"] self.player.data["games_played"] += 1 self.player.current_score = 1226 self.player.update_scores(self.player.current_score) self.assertEqual(self.player.data["highest_score"], self.player.current_score) self.assertEqual(self.player.data["lowest_score"], old_lowest) self.assertEqual(self.player.data["average_score"], 800.0) def test_updateScoresLowest(self): old_highest = self.player.data["highest_score"] self.player.data["games_played"] += 1 self.player.current_score = 126 self.player.update_scores(self.player.current_score) self.assertEqual(self.player.data["highest_score"], old_highest) self.assertEqual(self.player.data["lowest_score"], self.player.current_score) self.assertEqual(self.player.data["average_score"], 700.0) def test_updateTimes(self): """ Tests that when a game has ended the user's best/worse/average times are updated in the database. """ time = self.player.current_time def test_updateMoves(self): """ Tests that when a game has ended the user's best/worse/average moves are updated in the database. """ moves = self.player.current_moves self.player.update_moves(moves, win=1) self.assertEqual(self.player.data["fewest_winning_moves"], moves) def test_endGame(self): """ Tests that when a game ends, the user's data is updated and that this update is reflected in the database. """ games_played = self.player.data["games_played"] self.player.end_game(10, 200, 90, 0) self.assertEqual(self.player.data["games_played"], games_played + 1) def test_wonGame(self): """ Tests that when a player wins a game, the data is updated and reflected in the database. """ pass
def test_player_move_forward(): player = Player() x_before = player.position[0] player.move(1, 0, 0) x_after = player.position[0] assert x_after == x_before + 1
from model.player import Player p = Player(name='Vasya', email='*****@*****.**') print(p) p2 = Player() p2.load_from_db("*****@*****.**") print(p2) p3 = Player(name="Lesha", email="*****@*****.**", password="******") p3.save_to_db() print("Player {} was inserted to db".format(p3)) p4 = Player() p4.load_from_db("*****@*****.**") p4.name = "Lesha2" p4.save_to_db() print("Player's {} name was updated in db".format(p4)) # Please uncomment me, if you want to test delete ability #p4.delete_from_db() #print("Player's {} was deleted from db".format(p4))