def register(username: str, password: str): profile = Profile.get_or_none(Profile.username == username) if profile is not None: raise BadRequest('A user with this username already exists') hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode() profile = Profile.create( username=username, hashed_password=hashed, ) global_game = Game.get_or_none(Game.name == 'Global Indefinite') GameProfile.create(game=global_game, profile=profile, cash=global_game.starting_cash) global_game = Game.get_or_none(Game.name == 'Global Timed') GameProfile.create(game=global_game, profile=profile, cash=global_game.starting_cash) send_notification(profile, 'Welcome to Fortune!') send_notification( profile, 'Click the Play button in the menubar on top to create a new game.') send_notification( profile, 'To adjust account options, see achiements, and add friends, click on your username on the top and select Profile' ) return create_auth_token(profile)
def prepare_tournament_games(round_of): L.info('***** prepare tournament games for round of %d' % round_of) # 직전 라운드(16강)는 이번 라운드(8강) * 2 # 직전 라운드(16강) 결과에서 이번 라운드(8강) 대진표가 정해짐 games = get_games_round_of(round_of * 2) # 토너먼트: 직전 라운드의 경기 수 == 이번 라운드 번호 if len(games) == round_of: # 이번 라운드 경기수 = 이번 라운드(8강) / 2 for i in range(int(round_of / 2)): # 앞쪽 반을 순회하면서.. 뒤쪽 반은 역순으로... # 최고점자 vs 최저점자 p1 = games[i].winner p2 = games[-1 - i].winner g = Game(p1, p2, round_of) db.session.add(g) db.session.commit() L.info('prepare game#%d round of #%d : %s vs %s' % (g.id, round_of, p1, p2)) # 예선 풀 리그: 직전 라운드의 경기 수 == 0 else: # FIXME: .... players = get_players(round_of) # 이번 라운드 경기수 = 이번 라운드(8강) / 2 for i in range(int(round_of / 2)): # 앞쪽 반을 순회하면서.. 뒤쪽 반은 역순으로... # 최고점자 vs 최저점자 p1 = players[i].name p2 = players[-1 - i].name g = Game(p1, p2, round_of) db.session.add(g) db.session.commit() L.info('prepare game#%d round of #%d : %s vs %s' % (g.id, round_of, p1, p2))
def init_db(session): Base.metadata.create_all(engine) # skip if there are games already if session.query(Game).first(): return game = Game(name="Test Game", uuid="A97E57A2-E440-4975-A624-6F99999D64DA") questions = [Question(question="Who won the quiz?", game=game)] session.add(game) game = Game(name="new", uuid="C0CFAF27-0770-400E-A9B9-82461ED9FB6F") questions = [ Question(question="Who is good at this?", game=game), Question(question="Who read the next question?", game=game), ] session.add(game) session.commit() t = Team(name="ee22dc", team_code="111", game_id=game.id) session.commit() p = Player(color="#ee22dc", name="p1") sp = PlayerInGame(team=t, player=p, game=game) session.add(p) session.commit() session.add( GivenAnswer(answer="This is my answer", question_uuid=questions[0].uuid, player_id=p.id)) session.commit()
def test_check_global_timed_game_creates_new_game_upon_expiration(self): game_before_check = Game.get(Game.name == 'Global Timed') game_before_check.ends_at = datetime.utcnow() game_before_check.save() check_global_timed_game() self.assertEqual( 0, Game.select().where(Game.id == game_before_check.id).count()) Game.get(Game.name == 'Global Timed')
def index(): year_by_number = Game.get_year_by_number() last_year = year_by_number[0][0] return render_template( "index.html", title='Лента игр', year_by_number=year_by_number, day_by_games=Game.get_day_by_games(last_year), )
def getMatch(): game = Game() print('\nAVAILABLE MATCHES\n') game.viewGames() mID = int(input('Enter match you want to book for: ')) if game.gameVerify(mID) != 1: print('The match id you entered is invalid!\nPlease Try Again!!\n') getMatch() return mID
def process_create_game(socw, msg): # create game name = msg.params['name'] game = find_game_by_name(name) if not game: game = Game() game.name = name game.players.append(socw.get_user()) db.games.append(game) # send OK msg = AppMessageFactory.ok() socw.send_message(msg)
def up(db): with db.atomic(): migrator = PostgresqlMigrator(db) db.bind(MODELS, bind_refs=False, bind_backrefs=False) db.create_tables(MODELS) if Coin.get_or_none(Coin.id == 1) is None: Coin.create(name='Bitcoin', symbol='BTC') Coin.create(name='Ethereum', symbol='ETH') Coin.create(name='Litecoin', symbol='LTC') Coin.create(name='Coin 3', symbol='CO3') Coin.create(name='Coin 4', symbol='CO4') Coin.create(name='Coin 5', symbol='CO5') global_indef = Game.create(name='Global Indefinite', starting_cash=10000.00, shareable_link='INDEF', shareable_code='INDEF', ends_at=None) # insert achievements into database Achievement.create( name="Win", description="Finish in first place in a private game") Achievement.create( name="Double net worth", description="Achieved by doubling your net worth in a game") Achievement.create(name="Identity Crisis", description="Change your username") # insert goals into database Goal.create(name="Entrepreneur", description="Create a private game") all_coins = Coin.select() for coin in all_coins: GameCoin.create(game=global_indef, coin=coin) global_timed = Game.create(name='Global Timed', starting_cash=10000.00, shareable_link='TIMED', shareable_code='TIMED', ends_at=datetime.utcnow() + timedelta(minutes=1)) # CHANGEME for devel purposes, making it 1 min for now GameCoin.create(game=global_timed, coin=Coin.get()) # from auth.services import register hashed = bcrypt.hashpw("admin".encode(), bcrypt.gensalt()).decode() admin = Profile.create(username="******", hashed_password=hashed, is_admin=True) # Required so that admin can still view graphs in the landing page GameProfile.create(profile=admin, game=global_indef, cash=0.0)
def active_games_at_page(profile_id, page_number, keyword, criteria): """ Returns - active games in the requested page that matches the keyword (sorted by criteria) - number of active games matching the keyword """ games_query = Game.select() \ .join(GameProfile) \ .where((GameProfile.profile == profile_id) & Game.name.contains(keyword) & (Game.ends_at > datetime.utcnow())) # Note: This line always filters out Global Indef. # LOOKATME: Depending on the keyword, the call above might return EVERY games from the database that belongs to # the player. If that is expensive, optimize this. games = [gm for gm in games_query] global_indef = Game.get_or_none(Game.id == 1) include_global_indef = False if keyword.lower() in global_indef.name.lower( ): # Cannot append global_indef to games yet, include_global_indef = True # else sorting by endTime will break total_games = len(games) + 1 if include_global_indef else len(games) max_page = int(ceil(total_games / PAGE_SIZE)) # Verify page is within range page_number = max(1, page_number) page_number = max_page if page_number > max_page else page_number from operator import attrgetter if criteria['titleAscending']: games.append(global_indef) games.sort(key=attrgetter("name")) elif criteria['titleDescending']: games.append(global_indef) games.sort(key=attrgetter("name"), reverse=True) elif criteria['endTimeAscending']: games.sort(key=attrgetter("ends_at")) games.append(global_indef) elif criteria['endTimeDescending']: games.sort(key=attrgetter("ends_at"), reverse=True) games.insert(0, global_indef) else: games.insert(0, global_indef) first_index_in_page = (page_number - 1) * PAGE_SIZE games = games[first_index_in_page:first_index_in_page + PAGE_SIZE] return games, total_games, PAGE_SIZE
def create_game(teamOneId, teamTwoId): post_body = json.loads(request.data) teamOneScore = post_body.get('teamOneScore', 0) teamTwoScore = post_body.get('teamTwoScore', 0) game = Game(teamOneId=teamOneId, teamTwoId=teamTwoId, teamOneScore=teamOneScore, teamTwoScore=teamTwoScore) db.session.add(game) db.session.commit() return json.dumps({'success': True, 'data': game.serialize()}), 201
def setUp(self): super().setUp() with db.atomic() as txn: #don't need to create a game, migrations/v1.py gets run before every test #Coin.create(id=1, name='Bitcoin', symbol='BTC') Game.create(name='Game', starting_cash=10000.00, shareable_link='aaaabbbbccccdddd', shareable_code='aaaa', ends_at=(datetime.utcnow().replace(tzinfo=pytz.utc) + timedelta(days=7)).isoformat()) profile = Profile.create(username='******', hashed_password='******') self.token = AuthToken.create(profile=profile, token='thevalidtoken').token
def test_user_automatically_joins_new_global_time_game(self): # register user res = self.client.post('/auth/register', data=json.dumps({ 'username': '******', 'password': '******', 'password': '******', }), headers={'Content-Type': 'application/json'}) self.assertEqual(200, res._status_code) game_before_check = Game.get(Game.name == 'Global Timed') game_before_check.ends_at = datetime.utcnow() game_before_check.save() # assert deletes old GameProfile profile = Profile.get_by_id(1) qry = GameProfile.select().join(Game).where( (GameProfile.profile == profile) & (Game.name == 'Global Timed')) self.assertEqual(2, len(profile.game_profiles) ) # should have 2: global timed and indefinite self.assertEqual(1, qry.count()) # just to make sure gp_old = qry.get() check_global_timed_game() # assert creates new GameProfile qry = GameProfile.select().join(Game).where( (GameProfile.profile == profile) & (Game.name == 'Global Timed')) self.assertEqual(1, qry.count()) gp_new = qry.get() # but the ids should not be the same self.assertNotEqual(gp_old.id, gp_new.id)
def main(): current_games = [ f'{platform}_{category}_{name}' for platform, category, name in iter_parse_played_games(get_games()) ] changed_count = 0 for game in Game.select(): name = f'{game.platform}_{game.category}_{game.name}' last_ignored = game.ignored game.ignored = name not in current_games if last_ignored != game.ignored: log.info( f'#{game.id} {game.name} ({game.platform}, {game.category}): {last_ignored} -> {game.ignored}' ) game.save() changed_count += 1 if changed_count: text = f'Изменений: {changed_count}' log.debug(text) add_notify(log.name, text)
def act_createGame(data): user = dbi.getXbyY('User', 'sid', data['sid']) if user.gameId: raise BadFieldException('alreadyInGame') map_ = dbi.getXbyY('Map', 'id', data['mapId']) descr = None if 'gameDescription' in data: descr = data['gameDescription'] randseed = math.trunc(time.time()) if 'randseed' in data: randseed = data['randseed'] ai = data['ai'] if 'ai' in data else 0 if ai > map_.playersNum: raise BadFieldException('tooManyPlayersForMap') newGame = Game(data['gameName'], descr, map_, randseed, data['ai'] if 'ai' in\ data else None) dbi.addUnique(newGame, 'gameName') initRegions(map_, newGame) if ai < map_.playersNum: user.game = newGame user.priority = 1 user.inGame = True dbi.flush(user) if not misc.TEST_MODE: data['randseed'] = randseed dbi.updateGameHistory(user.game, data) return {'result': 'ok', 'gameId': newGame.id}
def main(): init_db("carreritas.db") users = User.select() if not users.count(): create_random_user() users = User.select() _map = Map() game = Game(users[0], _map) frame = game.map.render(game.players, game.winners) frame.save("0.png") while True: player = game.next_player() game.play_turn(player) frame = game.map.render(game.players, game.winners) frame.save(f"{game.turn}.png") if game.is_turn_finished(): if game.is_game_finished(): winners = [p for p in game.players if p.is_winner] if len(winners) > 0: print(f"Hubo mas de un ganador: {winners}") else: print(f"Ganó el jugador {winners[0]}") else: game.turn += 1
def decodeAppMessage(obj): if obj.get('klass') == 'Message': return AppMessage.from_dict(obj) if obj.get('klass') == 'Game': return Game.from_dict(obj) if obj.get('klass') == 'UUID': return uuid.UUID(obj['uuid']) else: return obj
def handle(self, gameId): player = Player.byUser(self.user) if player is None: self.response.out.write("") return game = Game.byId(gameId) out = [player.email for player in game.players] self.response.out.write(json.dumps(out))
def handle(self, gameId): player = Player.byUser(self.user) if player is None: self.response.out.write("") return game = Game.byId(gameId) msg = self.request.get('msg') game.broadcast({ "sender": player.username, "message":msg})
def prepare_full_league_games(max_player): L.info('***** prepare full league games for %d players' % max_player) players = get_players(max_player) for p1 in players: for p2 in players: if p1.name == p2.name: break g = Game(p1.name, p2.name, 0) db.session.add(g) db.session.commit() L.info('prepare game#%d full league %s vs %s' % (g.id, p1.name, p2.name))
def create_game(log, platform: str, category: str, name: str, gist_file: GistFile) -> bool: # Проверяем, что игры с такой категорией нет в базе game = Game.get_or_none(name=name, platform=platform, category=category) if game: return False finish_datetime = None # Если игра уже добавлена как завершенная if is_finished(category): finish_datetime = gist_file.committed_at log.info(f'Added {name!r} ({platform} / {category})') Game.create( name=name, platform=platform, category=category, append_datetime=gist_file.committed_at, finish_datetime=finish_datetime, ) return True
def check_global_timed_game(): game = Game.get(Game.shareable_link == 'TIMED') if game.ends_at < datetime.utcnow(): # end global timed game, and start another profiles = [] for game_profile in GameProfile.select().where(GameProfile.game == game): profiles.append(game_profile.profile) send_notification(game_profile.profile, 'The global timed game has expired') game_profile.delete_instance(recursive=True) game.delete_instance(recursive=True) global_timed = Game.create(name='Global Timed', starting_cash=10000.00, shareable_link='TIMED', shareable_code='TIMED', ends_at=datetime.utcnow() + timedelta(minutes=1)) # CHANGEME for devel purposes, making it 1 min for now GameCoin.create(game=global_timed, coin=Coin.get()) for profile in profiles: GameProfile.create( game=global_timed, profile=profile, cash=global_timed.starting_cash )
def create_game(): game_form = form.GameCreateForm() if not game_form.validate_on_submit(): return jsonify(errors=game_form.errors) name = game_form.name.data map_name = game_form.map_name.data game = Game(name=name, map_name=map_name, state=collection.get(map_name, State.sample())) db.session.add(game) db.session.commit() return fl.redirect(fl.url_for("index"))
def update_game( game_id, name, starting_cash, ends_at, active_coins, ): game = Game.get_or_none(Game.id == game_id) if not game: raise BadRequest(f'A game with id {game_id} does not exist') game.name = name game.starting_cash = starting_cash game.ends_at = ends_at # delete all GameCoins for this game and just re-create GameCoin.delete().where(Game.id == game_id) create_gamecoins_for_game(game, active_coins) return game
def parse_game(data, session): """ adds an entry to the Game table """ competitions = data["gamepackageJSON"]["header"]["competitions"][0] # date of the game in datetime format date = competitions["date"] date = datetime.datetime.strptime( date, '%Y-%m-%dT%H:%MZ') - datetime.timedelta(hours=4) # the id's of the two teams playing team_0 = competitions["competitors"][0]["team"]["abbreviation"] team_1 = competitions["competitors"][1]["team"]["abbreviation"] # parse home and away teams, as well as game score if competitions["competitors"][0]["homeAway"] == "home": home, visitor = team_0, team_1 home_score = intf(competitions["competitors"][0]["score"]) visitor_score = intf(competitions["competitors"][1]["score"]) else: home, visitor = team_1, team_0 home_score = intf(competitions["competitors"][1]["score"]) visitor_score = intf(competitions["competitors"][0]["score"]) # parse winner and loser if competitions["competitors"][0]["winner"]: winner, loser = team_0, team_1 else: winner, loser = team_1, team_0 isLeague = competitions["conferenceCompetition"] g = session.query(Game).filter_by(date=date, home=home).first() if not g: g = Game(id=data["gameId"], date=date, home=home, visitor=visitor, winner=winner, loser=loser, home_score=home_score, visitor_score=visitor_score, isLeague=isLeague) session.add(g)
def new(): """Start a new game. Create a new Game object, quit current game if any, start the game, and redirect to / route. """ game = Game() if current_user.has_current_game: current_user.current_player.quit() game.add_player(current_user) game.start() return redirect('/')
def conn(): if isLoggedIn(): uid = session["uid"] gm.removeTable(uid) ng = gm.hasGameWithId(uid) u = User.query.get(uid) g = Game(u) if ng == None: ng = cGame(logic.Game(), uid, u.nick) ng.game.new_game() gm.addTable(ng) db.session.add(g) db.session.commit() join_room(room) else: #Already playing (prevent multiple login) return False emit("player_connect", (uid, u.nick), room=room) emit("bupdate", printBoard(ng), room=room) emit("load_others", gm.getGames(uid))
def create_game(name, starting_cash, shareable_link, shareable_code, ends_at, active_coins, profile): # bounds check, validate if ends_at < datetime.utcnow().replace(tzinfo=pytz.utc): raise BadRequest('Invalid game ending date') if starting_cash <= Decimal(0): raise BadRequest('Starting cash must be positive') game = Game.create( name=name, starting_cash=starting_cash, shareable_link=shareable_link, shareable_code=shareable_code, ends_at=ends_at, ) create_gamecoins_for_game(game, active_coins) GameProfile.create( game=game, profile=profile, cash=game.starting_cash, ) return game
def create_chat_message(profile_id, game_id, message): try: int(profile_id) int(game_id) assert len(message) > 0 except: raise BadRequest("Invalid parameters to create chat message") message = Message.create( game=game_id, profile=profile_id, content=message, # use default value for created_on ) game = Game.get_or_none(Game.id == game_id) if game is not None: print("Broadcaseting to game") broadcast_in_a_game(game, 'chat', '', False) return message
def setUp(self): super().setUp() with db.atomic() as txn: self.game = Game.create( name='Game', starting_cash=10000.00, shareable_link='aaaabbbbccccdddd', shareable_code='aaaa', ends_at=(datetime.utcnow().replace(tzinfo=pytz.utc) + timedelta(days=7)).isoformat()) profile = Profile.create(username='******', hashed_password='******') GameProfile.create(game=self.game, profile=profile, cash=-1.0) Message.create( game=self.game.id, profile=profile.id, content="first message", # use default value for created_on ) self.token = AuthToken.create(profile=profile, token='thevalidtoken').token
def edit(profile, game_id): # edit game validated_data: dict = GameCreateRequest.deserialize(request.json) update_game( game_id, validated_data['name'], validated_data['startingCash'], validated_data['endsOn'], active_coins=validated_data['activeCoins'], ) try: q = Game.update({ Game.ends_at: validated_data['endsOn'], Game.starting_cash: validated_data['startingCash'], Game.name: validated_data['title'] }).where(Game.id == request.args.get('id')) q.execute() except Exception as e: return "Failure to edit Game: {}".format(str(e)) return "Game id={} formatted".format(request.args.get('id'))
def handle(self, gameId): print "PlayJoin %s" % gameId game = Game.byId(gameId) if game is None: self.response.out.write("Invalid game") return player = Player.byUser(self.user) # Player joining this game fresh if player is None: player = Player.joinGame(self.user, game) # Player was in another game, leave it. if player.game.gameId != game.gameId: player.leaveGame() player = Player.joinGame(self.user, game) render(self, 'play.html', { 'me': player.user, 'token': player.token, 'game_key': player.game })
def manageGames(): print( "\n\nWelcome To the stadium ticket booking system!\nAdmin Menu\nManage Games\n" "1. View all Games\n" "2. Add Game\n" "3. Remove Game\n" "4. Edit Game\n" "5. Reset\n" "6. Exit\n" ) choice = int(input("Enter your choice: ")) game = Game() if choice == 1: game.viewGames() elif choice == 2: gameName = input('Enter game Name: ') date = input('Enter game Date: ') time = input('Enter game Time: ') game.addGame(gameName,date,time) elif choice == 3: gID = input('Enter game ID to remove: ') try: game.removeGame(gID) except: print('\nGame not found!\n') elif choice == 4: gID = input('Enter game ID to Edit: ') game.editGame(gID) elif choice == 5: game.resetTable() elif choice == 6: return else: print('The Choice you entered is invalid!\nPlease Try Again!!\n') manageGames() manageGames()
'14': 'XIV', '15': 'XV', } # В какой-то момент поменял платформу с PS на PS1, нужно играм с PS1 указать # на те же игры с PS # В другой момент писал 'PS 2', после поменял название категории на PS2 old_by_new_platforms = { 'PS': 'PS1', 'PS 2': 'PS2', 'PS 3': 'PS3', 'PS 4': 'PS4', } for old_platform, new_platform in old_by_new_platforms.items(): # Ищем игры с указанной платформой и без заданного root_alias for game in Game.select().where(Game.platform == new_platform, Game.root_alias.is_null()): root_game = Game.get_or_none(Game.platform == old_platform, Game.name == game.name, Game.category == game.category) # Если не найдено или если у найденной id больше, чем у требуемой игры if not root_game or root_game.id > game.id: continue print(f'In game #{game.id} setted root_alias from #{root_game.id}') game.root_alias = root_game game.save() # У некоторых игр арабские цифры в названии были заменены на римские for root_game in Game.select(): m = re.search(r'\d+', root_game.name) if not m:
def handle(self): self.redirect("/play/%s" % Game.create().gameId)