def test_should_not_allow_scouts_to_jump_over_pieces(self): from_pos = {'x': 5, 'y': 5} to_positions = [{ 'x': 9, 'y': 5 }, { 'x': 2, 'y': 5 }, { 'x': 5, 'y': 8 }, { 'x': 5, 'y': 2 }] inTheWayPositions = [{ 'x': 8, 'y': 5 }, { 'x': 4, 'y': 5 }, { 'x': 5, 'y': 6 }, { 'x': 5, 'y': 3 }] notInTheWayPositions = [{ 'x': 9, 'y': 6 }, { 'x': 1, 'y': 5 }, { 'x': 5, 'y': 9 }, { 'x': 5, 'y': 0 }] for i in xrange(len(to_positions)): game = models.Game() game.set_piece(from_pos, fixtures.SCOUT) game.set_piece(inTheWayPositions[i], 1) self.assertRaisesRegexp(models.InvalidMove, 'Can not jump over pieces.', game.check_move, from_pos, to_positions[i]) for i in xrange(len(to_positions)): game = models.Game() game.set_piece(from_pos, fixtures.SCOUT) game.set_piece(notInTheWayPositions[i], fixtures.FLAG) game.check_move(from_pos, to_positions[i])
def test_should_allow_one_space_adjacent_move_not_diagonally(self): from_pos = {'x': 5, 'y': 5} valid_moves = [{ 'x': from_pos['x'] + 1, 'y': from_pos['y'] }, { 'x': from_pos['x'] - 1, 'y': from_pos['y'] }, { 'x': from_pos['x'], 'y': from_pos['y'] - 1 }, { 'x': from_pos['x'], 'y': from_pos['y'] + 1 }] invalid_moves = [{ 'x': from_pos['x'] - 1, 'y': from_pos['y'] + 1 }, { 'x': from_pos['x'] + 1, 'y': from_pos['y'] - 1 }, { 'x': from_pos['x'] + 1, 'y': from_pos['y'] + 1 }, { 'x': from_pos['x'] - 1, 'y': from_pos['y'] - 1 }, { 'x': from_pos['x'], 'y': from_pos['y'] + 2 }, { 'x': from_pos['x'] + 2, 'y': from_pos['y'] }] for to_pos in valid_moves: game = models.Game() game.set_piece(from_pos, fixtures.MARSHAL) move = game.check_move(from_pos, to_pos) self.assertEqual(move, move_types.MOVE) for to_pos in invalid_moves: game = models.Game() game.set_piece(from_pos, fixtures.MARSHAL) self.assertRaisesRegexp(models.InvalidMove, 'Illegal movement.', game.check_move, from_pos, to_pos)
def post(self): namespace_manager.set_namespace(users.get_current_user().user_id()) import logging logging.warn(users.get_current_user().user_id()) pointLevel = self.request.get('pointLevel') real_points = int(pointLevel) userCaster = self.request.get('userCaster') userFaction = self.request.get('userFaction') opponentName = self.request.get('opponentName') opponentFaction = self.request.get('opponentFaction') opponentCaster = self.request.get('opponentCaster') date = self.request.get('date') logging.error(date) try: real_date = datetime.strptime(date, '%m/%d/%Y') except (ValueError): real_date = datetime.strptime(date, '%Y-%m-%d') result = self.request.get('result') result_types = self.get_game_results_from_result_name(result) game = models.Game(date=real_date, player_faction=userFaction, player_warcaster=userCaster, opponent_name=opponentName, opponent_faction=opponentFaction, opponent_warcaster=opponentCaster, size=real_points, result=result, won=result_types[0], draw=result_types[1], teaching=result_types[2]) game.put() self.redirect('/record')
def test_attacking_miner(self): from_pos = {'x': 5, 'y': 5} to_pos = {'x': 5, 'y': 6} rules = { '1': MOVE_TYPES.ATTACK_LOST, '2': MOVE_TYPES.ATTACK_LOST, '3': MOVE_TYPES.ATTACK_LOST, '4': MOVE_TYPES.ATTACK_LOST, '5': MOVE_TYPES.ATTACK_LOST, '6': MOVE_TYPES.ATTACK_LOST, '7': MOVE_TYPES.ATTACK_LOST, '8': MOVE_TYPES.ATTACK_DRAW, '9': MOVE_TYPES.ATTACK_WON, 'S': MOVE_TYPES.ATTACK_WON, 'B': MOVE_TYPES.ATTACK_WON, 'F': MOVE_TYPES.CAPTURE } for key, result in rules.iteritems(): game = models.Game() game.set_piece(from_pos, FIXTURES.MINER) game.set_piece(to_pos, {'rank': key, 'side': 1}) self.assertEqual(game.check_move(from_pos, to_pos), result)
def test_shot_msg(self): # Create second player mock_sock_2 = Mock() player_2 = models.Player(mock_sock_2, "18958") player_2.gameId = 234 conn_2 = Mock() conn_2.fileobj = mock_sock_2 conn_2.data = player_2 shot_1 = ["SHOT", "234", "12345", "5", "2"] # Miss shot_2 = ["SHOT", "234", "12345", "8", "8"] # Hit boat shot_3 = ["SHOT", "234", "12345", "8", "7"] # Sink boat shot_4 = ["SHOT", "234", "12345", "5", "7"] # Sink last boat msg_parts = shot_1 + shot_2 + shot_3 + shot_4 mock_sock_2.recv.side_effect = encode_msg(msg_parts) # Set up game game = models.Game(234, 2) self.manager.gameDict[234] = game # Add players to game game.players["12345"] = self.player game.players["18958"] = player_2 game.turnArray = list(game.players.values()) # shuffle(game.turnArray) game.turn = 0 # Set up player's board exp_board = [[0, 0, 0, 0, 0, 0, 15, 0], [0, 0, 13, 0, 0, 0, 15, 0], [0, 0, 13, 0, 0, 0, 15, 0], [0, 0, 13, 0, 0, 0, 15, 0], [0, 0, 0, 0, 14, 0, 5, 0], [0, 0, 0, 0, 14, 0, 0, 0], [0, 0, 0, 0, 14, 0, 0, 0], [12, 12, 12, 0, 14, 0, 1, 1]] self.player.set_up_game(8, [0,2,3,3,4,5]) self.player.gameId = 234 self.player.board.plot = exp_board self.player.liveBoats = 2 self.player.boatHealth = [0, 2, 0, 0, 0, 1] self.player.set_status = "ready" # Test method for i in range(4): process_read_request(self.manager, conn_2) for i in self.out_msgs: print(i) print(self.player.board.plot)
def test_attacking_spy(self): from_pos = {'x': 5, 'y': 5} to_pos = {'x': 5, 'y': 6} rules = { '1': move_types.ATTACK_WON, '2': move_types.ATTACK_LOST, '3': move_types.ATTACK_LOST, '4': move_types.ATTACK_LOST, '5': move_types.ATTACK_LOST, '6': move_types.ATTACK_LOST, '7': move_types.ATTACK_LOST, '8': move_types.ATTACK_LOST, '9': move_types.ATTACK_LOST, 'S': move_types.ATTACK_DRAW, 'B': move_types.ATTACK_LOST, 'F': move_types.CAPTURE } for key, result in rules.iteritems(): game = models.Game() game.set_piece(from_pos, fixtures.SPY) game.set_piece(to_pos, {'rank': key, 'side': 1}) self.assertEqual(game.check_move(from_pos, to_pos), result)
def post(self): try: game_type_id = request.json.get('game_type_id') if game_type_id is None: abort(400, "No [game_type_id] provided.") game_type_id = int( game_type_id) if game_type_id.isdigit() else None if game_type_id is None: abort(400, "[game_type_id] must be an integer.") if game_type_id < 0 or game_type_id >= len(game_types): abort( 400, f"[game_type_id] of [{game_type_id}] not a supported game." ) game = models.Game(host_user_id=g.current_user.id, game_type_id=str(game_type_id), datetime_created=datetime.datetime.now(), game_state_id=0) db.session.add(game) db.session.commit() return game, 201 except Exception as e: logger.error(e) abort(500, e)
def post(self): user = users.get_current_user() toEmail = self.request.get('invited') if toEmail: prefs = models.Prefs.gql('where userEmail = :1', toEmail).get() if prefs: invite = models.Invite(toUser=prefs.user, toEmail=toEmail) invite.put() notify.sendInvite(user, invite) else: invite = models.Invite(toEmail=toEmail) invite.put() notify.sendInviteEmail(user, invite) if self.request.get('submit') == 'Delete': invites = self.request.get_all('select') for i in invites: invite = db.get(i) invite.delete() if self.request.get('submit') == 'Accept': invites = self.request.get_all('select') for i in invites: invite = db.get(i) if invite: invite.status = models.INVITE_ACCEPTED if invite.fromPlayAs == models.PLAYAS_RANDOM: invite.fromPlayAs = random.choice( [models.PLAYAS_WHITE, models.PLAYAS_BLACK]) invite.put() if invite.fromPlayAs == models.PLAYAS_WHITE: game = models.Game(whitePlayer=invite.fromUser, blackPlayer=invite.toUser) else: game = models.Game(whitePlayer=invite.toUser, blackPlayer=invite.fromUser) game.put() notify.sendYourMove(game.whitePlayer, game.blackPlayer, str(game.key())) if self.request.get('submit') == 'Reject': invites = self.request.get_all('select') for i in invites: invite = db.get(i) if invite: invite.status = models.INVITE_REJECTED invite.put() self.redirect('/')
def post(self, g_id=None): self.game_config(g_id) if not self.game: self.game = models.Game() self.game.setup() user = self.get_current_user() self.game.add_user(user) self.redirect("/game/" + str(self.game.id))
def get_games_for_date_range(self, startDate, endDate): result = self.call('schedule', 'startDate={}&endDate={}&expand=schedule.linescore'.format(startDate.date().isoformat(), endDate.date().isoformat())) dates = result["dates"] if len(dates) == 0: return [] else: # Return the games sorted by game state so those finished or in progress # come first. The API returns them sorted but in case this changes we # sort them here return sorted((models.Game(game_data) for date in dates for game_data in date['games']), key=lambda x: x.game_state, reverse=True)
def test_should_not_allow_flags_to_move(self): from_pos = {'x': 5, 'y': 5} game = models.Game() game.set_piece(from_pos, FIXTURES.FLAG) self.assertRaisesRegexp(models.InvalidMove, 'Flags cannot be moved.', game.check_move, from_pos, { 'x': from_pos['x'], 'y': from_pos['y'] + 1 })
def postgame(self): key = self.params['info']['remoteaddr'] + ':' + str( self.params['port']) game = models.Game(key_name='game:' + key, addr=self.params['info']['remoteaddr'], port=int(self.params['port']), data=pickle.dumps(self.params)) game.put() self.response.out.write('Game updated\n')
def end_game(loser_username, winner_username): opponent = user_repository.get_user_by_username(loser_username) winner = user_repository.get_user_by_username(winner_username) winner_id = user_repository.get_user_id(winner_username) db_game = models.Game(winner_id) winner.games.append(db_game) opponent.games.append(db_game) db.session.commit()
def test_should_not_allow_bombs_to_move(self): from_pos = {'x': 5, 'y': 5} game = models.Game() game.set_piece(from_pos, fixtures.BOMB) self.assertRaisesRegexp(models.InvalidMove, 'Bombs cannot be moved.', game.check_move, from_pos, { 'x': from_pos['x'], 'y': from_pos['y'] + 1 })
def test_should_allow_scouts_to_move_straight_in_any_direction(self): from_pos = {'x': 5, 'y': 5} valid_moves = [{ 'x': from_pos['x'] + 4, 'y': from_pos['y'] }, { 'x': from_pos['x'] - 5, 'y': from_pos['y'] }, { 'x': from_pos['x'], 'y': from_pos['y'] + 4 }, { 'x': from_pos['x'], 'y': from_pos['y'] - 5 }] invalid_moves = [{ 'x': from_pos['x'] + 4, 'y': from_pos['y'] + 1 }, { 'x': from_pos['x'] - 5, 'y': from_pos['y'] + 4 }, { 'x': from_pos['x'] - 2, 'y': from_pos['y'] + 4 }, { 'x': from_pos['x'] + 4, 'y': from_pos['y'] - 5 }] for to_pos in valid_moves: game = models.Game() game.set_piece(from_pos, fixtures.SCOUT) for to_pos in invalid_moves: game = models.Game() game.set_piece(from_pos, fixtures.SCOUT) self.assertRaisesRegexp(models.InvalidMove, 'Illegal movement.', game.check_move, from_pos, to_pos)
def test_should_not_allow_movement_onto_unmovable_block(self): from_pos = {'x': 5, 'y': 5} block_pos = {'x': 6, 'y': 5} game = models.Game() game.set_piece(from_pos, fixtures.MARSHAL) game.set_piece(block_pos, 1) self.assertRaisesRegexp(models.InvalidMove, 'Can not move onto an unmoveable block.', game.check_move, from_pos, block_pos)
def test_should_not_allow_movement_onto_friendly_piece(self): from_pos = {'x': 5, 'y': 5} to_pos = {'x': from_pos['x'], 'y': from_pos['y'] + 1} game = models.Game() game.set_piece(from_pos, fixtures.MARSHAL) game.set_piece(to_pos, fixtures.SCOUT) self.assertRaisesRegexp(models.InvalidMove, 'Can not move onto friendly piece.', game.check_move, from_pos, to_pos)
def create_match(db: Session, game: schemas.GameCreate): #fake_hashed_password = user.password + "notreallyhashed" db_new_game = models.Game(id=game.id, league_id=game.league_id, radiant_score=game.radiant_score, dire_score=game.dire_score, duration=game.duration, is_valid=game.is_valid) db.add(db_new_game) db.commit() db.refresh(db_new_game) return db_new_game
def games(): form = AddGameForm(request.form) if request.method == 'POST' and form.validate(): if models.Game.query.filter_by( name=form.game_name.data.lower()).first(): flash('Game already exists') else: game = models.Game(form.game_name.data) models.db.session.add(game) models.db.session.commit() return redirect(url_for('games')) return render_template('games.html', games=models.Game.query.all(), form=form)
def process_game(input_dir, output_file_dir, game_id, lineups_file_name): lineups = pd.read_csv(filepath_or_buffer=lineups_file_name, sep='\t') game = models.Game(output_file_dir, game_id, lineups) file = open(f'{input_dir}/{game_id}.csv', "r") line_number = 0 index = [] for f in file: line_arr = f.replace("\"", "").lower().split(",") if line_number == 0: index = line_arr else: line_dict = dict(zip(index, line_arr)) # period change if int(line_dict['event_msg_type']) == 13: game.new_period() # substitution if int(line_dict['event_msg_type']) == 8: person1 = line_dict['person1'] person2 = line_dict['person2'] time = line_dict['pc_time'] game.substitute(person1, person2, time) # score if int(line_dict['event_msg_type']) == 1 or \ (int(line_dict['event_msg_type']) == 3 and int(line_dict['option1']) == 1): team_id = line_dict['team_id'] option1 = int(line_dict['option1']) pc_time = int(line_dict['pc_time']) game.score(team_id, option1, pc_time) # possession completed if int(line_dict['event_msg_type']) == 0: pc_time = int(line_dict['pc_time']) game.new_possession(pc_time) line_number += 1
def _create_game(setup): for row in setup: for piece in row: piece['side'] = 0 new_game = models.Game() new_game.red_hash = uuid.uuid4().hex[:6] new_game.blue_hash = uuid.uuid4().hex[:6] new_game.join_hash = uuid.uuid4().hex[:6] new_game.set_red_setup(setup) # Set the water. new_game.set_blocks() new_game.put() return new_game
def put(self, game_id): parsed_args = parser.parse_args() word_status = parsed_args['word_status'] wrong_letters = parsed_args['wrong_letters'] num_wrong_letters = parsed_args['num_wrong_letters'] game_status = parsed_args['game_status'] game = models.Game(game_id=game_id, word_status=word_status, wrong_letters=wrong_letters, num_wrong_letters=num_wrong_letters, game_status=game_status) session.add(game) session.commit() return game
def test_setb_msg(self): # Create message msg_parts = [] msg_parts += ("SETB|123|1|8|7|8|8".split("|")) msg_parts += ("SETB|123|2|8|1|8|2|8|3".split("|")) msg_parts += ("SETB|123|3|2|3|3|3|4|3".split("|")) msg_parts += ("SETB|123|4|5|5|6|5|7|5|8|5".split("|")) msg_parts += ("SETB|123|5|1|7|2|7|3|7|4|7|5|7".split("|")) # Create game game = models.Game(123, 2) # Associate game with game manager self.manager.gameDict[123] = game # Prepare player for game self.player.set_up_game(8, [0,2,3,3,4,5]) # load messages self.mock_sock.recv.side_effect = encode_msg(msg_parts) # Test method for i in range(5): self.assertNotEqual(self.player.get_status(), "ready") process_read_request(self.manager, self.conn) # Check Board exp_board = [[0, 0, 0, 0, 0, 0, 5, 0], [0, 0, 3, 0, 0, 0, 5, 0], [0, 0, 3, 0, 0, 0, 5, 0], [0, 0, 3, 0, 0, 0, 5, 0], [0, 0, 0, 0, 4, 0, 5, 0], [0, 0, 0, 0, 4, 0, 0, 0], [0, 0, 0, 0, 4, 0, 0, 0], [2, 2, 2, 0, 4, 0, 1, 1]] self.assertEqual(exp_board, self.player.board.plot) self.assertEqual(self.player.boatHealth, self.player.boatArray) self.assertEqual(self.player.get_status(), "ready")
def post(self, game_id): actions = { 'fire': self.fire, 'addplayer': self.addplayer, 'startgame': self.startgame, } logging.info(game_id) if game_id: req = json.loads(self.request.body) game = models.Game.all().filter('game_id = ', game_id).get() try: logging.info(str(req)) actions[req['action']](game, **req['args']) except AttributeError: self.abort(404) else: game = models.Game() game.put() self.json_response({ 'player': game.player(game.player_ids[0]), 'game_state': game.game_state })
import sys # Define screen constants SCREEN_WIDTH = 900 SCREEN_HEIGHT = 700 # Color constants object color = models.ColorConstants() # Init pygame pygame.init() # Define the screen (and it's properties) size = [SCREEN_WIDTH, SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("MG's Tower of Hanoi for Python") # Create main menu object menu = models.MainMenu(SCREEN_WIDTH, SCREEN_HEIGHT) # Create game object game = models.Game(SCREEN_WIDTH, SCREEN_HEIGHT) # Discs' move variables done = False drag = False drop = False move = False game_over = False init_game = False disc_index = None last_pos = [0, 0] # Moves counter moves_counter = 0 # Manage how fast the screen updates clock = pygame.time.Clock() # -------- Main Game Loop ----------- while not done:
def GamePlay(): """literally game hanoi-nya.""" global username # Create main menu object menu = models.MainMenu(GAME_WIDTH, GAME_HEIGHT) # Create game object game = models.Game(GAME_WIDTH, GAME_HEIGHT) # Discs' move variables done = False drag = False drop = False move = False game_over = False init_game = False disc_index = None last_pos = [0, 0] # Moves counter moves_counter = 0 play_time = 0 # -------- Main Game Loop ----------- while not done: # --- Main event loop for event in pg.event.get(): if event.type == pg.QUIT: done = True elif event.type == pg.MOUSEBUTTONDOWN: drag = True drop = False if init_game: if not game_over: for i in range(0, game.n_discs): if game.discs[i].is_clicked(): current_pos = game.discs[i].current_pos pos_length = len(game.pos[current_pos].discs) if game.discs[i] == game.pos[ current_pos].discs[pos_length - 1]: disc_index = i last_pos = [ game.discs[i].rect.x, game.discs[i].rect.y ] move = True else: # ranking hasil user game_data['hof'] = adt.algo_addSorted( game_data['hof'], game.n_discs, [username, play_time, moves_counter]) # masukkan ke database adt.data_write(game_data) if menu.btn_quit.is_clicked(): done = True GameHomePage() if menu.btn_play_again.is_clicked(): game.sprites_list.remove(game.discs) game.pos[2].discs = [] moves_counter = 0 game.discs = [] game.draw_discs() game_over = False if menu.btn_return.is_clicked(): menu.sprites_list.remove([ menu.btn_play_again, menu.btn_return, menu.btn_quit ]) menu.sprites_list.add([menu.btn_discs, menu.label]) game.sprites_list.remove(game.discs) init_game = False else: start_ticks = pg.time.get_ticks( ) # Waktu semenjak pg.init() dimulai for i in range(0, len(menu.btn_discs)): if menu.btn_discs[i].is_clicked(): game.set_n_discs(menu.btn_discs[i].value) game.sprites_list.remove(game.discs) game.discs = [] game.pos[2].discs = [] moves_counter = 0 game.draw_discs() init_game = True game_over = False break elif event.type == pg.MOUSEBUTTONUP: drag = False drop = True gameDisplay.fill(adt.color_use("background")) pgImage((10, 10), (80, 80), BUTTON_BACK, GameHomePage) if init_game: pgImage((10, 10), (80, 80), BUTTON_BACK, GameHomePage) pgText( game_dict[lang]['play_info'].format(str(moves_counter), str(round(play_time, 1))), (GAME_WIDTH / 2, 120), 20) if game_over: start_ticks = pg.time.get_ticks( ) # Waktu semenjak pg.init() dimulai part 2, bisa lebih efisien enggak ya? menu.sprites_list.draw(gameDisplay) if len(game.pos[2].discs) == game.n_discs: if moves_counter == game.min_moves: pgText(game_dict[lang]['congrats_min'], (GAME_WIDTH / 2, GAME_HEIGHT / 3), 20) else: pgText(game_dict[lang]['congrats_aja'], (GAME_WIDTH / 2, GAME_HEIGHT / 3), 20) else: play_time = (pg.time.get_ticks() - start_ticks) / 1000 # Actual timer if drag: if move: pos = pg.mouse.get_pos() game.discs[disc_index].rect.x = pos[0] - ( game.discs[disc_index].width / 2) game.discs[disc_index].rect.y = pos[1] - ( game.discs[disc_index].height / 2) elif drop: if move: current_pos = game.discs[disc_index].current_pos new_pos = None change = False turn_back = True position = pg.sprite.spritecollideany( game.discs[disc_index], game.pos_sprites_list) if position is not None: new_pos = position.pos_index if new_pos != current_pos: disc_length = len(position.discs) if disc_length == 0: turn_back = False change = True elif game.discs[disc_index].id > position.discs[ disc_length - 1].id: turn_back = False change = True if change: moves_counter = moves_counter + 1 game.pos[current_pos].discs.remove( game.discs[disc_index]) game.discs[disc_index].current_pos = new_pos game.pos[new_pos].discs.append( game.discs[disc_index]) new_pos_length = len(game.pos[new_pos].discs) game.discs[disc_index].rect.x = game.pos[new_pos].rect.x - \ ((game.DISC_WIDTH/(game.discs[disc_index].id+1)/2)-(game.DISC_HEIGHT/2)) game.discs[disc_index].rect.y = ( game.BOARD_Y - game.DISC_HEIGHT) - (game.DISC_HEIGHT * (new_pos_length - 1)) # Check if the game is over if len(game.pos[2].discs) == game.n_discs: game_over = True menu.sprites_list.add([ menu.btn_play_again, menu.btn_quit, menu.btn_return ]) menu.sprites_list.remove( [menu.label, menu.btn_discs]) # ngatur kalau dilepas diudara if turn_back: game.discs[disc_index].rect.x = last_pos[0] game.discs[disc_index].rect.y = last_pos[1] move = False game.sprites_list.draw(gameDisplay) else: menu.sprites_list.draw(gameDisplay) # update gameDisplay. pg.display.flip() gameClock.tick(60) pg.quit()
def games_get(): my_scraper = scraper.NBADataScraper() seasons = models.Season.query.all() for season in seasons: if season.season_start > 1995: # Play-by-play data on NBA.com doesn't go back further than the '96-'97 season game_number = 0 while game_number <= 1230: game = models.Game() # Fetch Game Info game_number_string = str(game_number) game_id = "00000"[:-len(game_number_string)] + game_number_string game_id = "002{season_id}{game_id}".format(str(season.season_start)[-2:], game_id) # Game Data teams = [] game_refs = [] players = [] game_total_headers, game_total_data = my_scraper.get_game_boxscore(game_id, season.season_code, resultSetsIndex=1) for team in game_total_data: teams.append({i[0]: i[1] for i in zip(game_total_headers[0], team)}) ref_headers, refs = my_scraper.get_game_misc_stats(game_id, resultSetsIndex=2) for ref in refs: game_refs.append({i[0]: i[1] for i in zip(ref_headers[0], ref)}) game_info_headers, game_info_data = my_scraper.get_game_misc_stats(game_id, resultSetsIndex=4) for game_info_row in game_info_data: game_info = {i[0]: i[1] for i in zip(game_info_headers[0], game_info_row)} summery_headers, summery = my_scraper.get_game_misc_stats(game_id, resultSetsIndex=0) for summery_row in summery: summery_data = {i[0]: i[1] for i in zip(summery_headers[0], summery_row)} new_game = models.Game() new_game.season_id = season.season_id new_game.nba_game_id = game_id home_team = models.Team.query.filter_by(nba_team_id=summery_data["HOME_TEAM_ID"]).first() new_game.home_team_id = home_team.team_id visiting_team = models.Team.query.filter_by(nba_team_id=summery_data["VISITOR_TEAM_ID"]).first() new_game.visiting_team_id = visiting_team.team_id for team in teams: if team["TEAM_ID"] == home_team.team_id: new_game.home_team_score = team["PTS"] else: new_game.visiting_team_score = team["PTS"] new_game.home_team_win = True if new_game.home_team_score > new_game.visiting_team_score else False new_game.periods = summery_data["LIVE_PERIOD"] # 2015-10-28T00:00:00 new_game.game_date = datetime.datetime\ .strptime(summery_data["GAME_DATE_EST"], "%Y-%b-%dT%R:%M:%S").date() new_game.attendance = game_info["ATTENDANCE"] new_game.game_length = game_info["GAME_TIME"] for ref in refs: ref_db = models.Ref.query.filter_by(ref_nba_id=ref["OFFICIAL_ID"]).first() if not ref_db: ref_db = models.Ref() ref_db.ref_nba_id = ref["OFFICIAL_ID"] ref_db.first_name = ref["FIRST_NAME"] ref_db.last_name = ref["LAST_NAME"] ref_db.add_object() new_game.ref_one = models.Ref.query.filter_by(ref_nba_id=refs[0]["OFFICIAL_ID"]).first().ref_id new_game.ref_two = models.Ref.query.filter_by(ref_nba_id=refs[1]["OFFICIAL_ID"]).first().ref_id new_game.ref_three = models.Ref.query.filter_by(ref_nba_id=refs[2]["OFFICIAL_ID"]).first().ref_id game_player_headers, game_player_data = my_scraper.get_game_boxscore(game_id, season.season_code) for player in game_player_data: players.append({i[0]: i[1] for i in zip(game_player_headers[0], player)}) # Play by Play Data headers, data = my_scraper.get_game_pbp(game_id, season.season_code) home_score = 0 visitor_score = 0 for event in data: event = {i[0]: i[1] for i in zip(headers[0], event)} new_event = models.GameEvent() new_event.game_id = game.game_id for item in event: attr = new_event.get_attr_title(item) if attr: setattr(new_event, attr, event[item]) score = event["SCORE"].split('-') if score: home_score = int(score[1]) visitor_score = int(score[0]) new_event.home_score = home_score new_event.visitor_score = visitor_score new_event.score_margin = home_score - visitor_score game_time = event["PCTIMESTRING"].split(':') new_event.game_minutes = int(game_time[0]) new_event.game_seconds = int(game_time[1]) period = new_event.period overtime_periods = 0 quarter_length = 12 if period > 4: overtime_periods = period - 4 period = 5 quarter_length = 5 elapsed_seconds = (720 * (period - 1)) + (300 * overtime_periods) + \ ((quarter_length * 60) - ((new_event.game_minutes * 60) + new_event.game_seconds)) new_event.game_time_elapsed_minutes = elapsed_seconds // 60 new_event.game_time_elapsed_seconds = elapsed_seconds % 60 new_event.home_event = event["HOMEDESCRIPTION"] new_event.neutral_event = event["NEUTRALDESCRIPTION"] new_event.visitor_event = event["VISITORDESCRIPTION"] new_event.add_object() game_number += 1
def db_start(): engine = create_engine('sqlite:///tmp/test.db', convert_unicode=True) db.create_all() db.session.commit() user = models.User() user.username = "******" user.password = sha256_crypt.encrypt("pppp1234") user.email = '*****@*****.**' user.job = "szef projektu" user.admin = True user.poweruser = True user.organizer = True user.birthdate = "01.01.1999" user.about = "Jestem dobrym adminem" user.why = "Chcę organizować gamejam, poniewż uważam, że jest to jest to idealna forma rozwoju dla młodych ludzi." db.session.add(user) db.session.commit() user = models.User() user.username = "******" user.password = sha256_crypt.encrypt("pppp1234") user.email = '*****@*****.**' user.job = "szef projektu" user.admin = True user.poweruser = True user.organizer = True user.birthdate = "01.01.1999" user.about = "Jestem dobrym adminem" user.why = "Chcę organizować gamejam, poniewż uważam, że jest to jest to idealna forma rozwoju dla młodych ludzi." db.session.add(user) db.session.commit() user = models.User() user.username = "******" user.password = sha256_crypt.encrypt("wikwoj") user.email = '*****@*****.**' user.job = "pierwszy user" user.admin = False user.poweruser = True user.organizer = True user.birthdate = "01.01.1889" user.about = "Jestem dobrym szefem" user.why = "Chcę zwyciężyć każdy jam" db.session.add(user) db.session.commit() user = models.User() user.username = "******" user.password = sha256_crypt.encrypt("marek") user.email = '*****@*****.**' user.job = "programista" user.admin = False user.poweruser = True user.organizer = False user.birthdate = "01.01.1889" db.session.add(user) db.session.commit() user = models.User() user.username = "******" user.password = sha256_crypt.encrypt("stefan") user.email = '*****@*****.**' user.job = "dzwiękowiec" user.admin = False user.poweruser = True user.birthdate = "01.01.1889" db.session.add(user) db.session.commit() team = models.Team() team.name = "BestTeam" team.master = "patryk" team.master_email = '*****@*****.**' team.contributors = ['adam', 'innygosc', 'jakiskoles'] team.gameinjams = ['Jam testowy', 'Pierwszy jam', 'Ten jam nie istnieje'] db.session.add(team) db.session.commit() team = models.Team() team.name = "DrużynaWygrywów" team.master = "wikwoj" team.master_email = '*****@*****.**' team.contributors = ['wikwoj', 'bedegralwgre', 'jestemhardkorem'] team.gameinjams = [ 'Jam testowy', 'Szybki jam', 'Ten jam nie istnieje', 'Global game jam' ] db.session.add(team) db.session.commit() team = models.Team() team.name = "MonsterCouch" team.master = "marek" team.master_email = '*****@*****.**' team.contributors = ['Krzyś', 'artur', 'Helena'] team.gameinjams = [ 'Pierwszy jam', 'Szybki jam', 'Ten jam nie istnieje', 'Global game jam' ] db.session.add(team) db.session.commit() team = models.Team() team.name = "LameTeam" team.master = "stefan" team.master_email = '*****@*****.**' team.contributors = ['Chyzio', 'Zyzio', 'Dyzio'] team.gameinjams = ['Pierwszy jam', 'Szybki', 'Global game jam'] db.session.add(team) db.session.commit() message = models.Message() message.title = 'testowa wiadomość' message.adresser = 'patryk' message.author = 'wikwoj' message.content = 'No hej' message.created = datetime.now() db.session.add(message) db.session.commit() jam = models.Jam() jam.title = "Jam testowy" jam.master = "patryk" jam.theme = "destruction" jam.description = "Jam o rozwalaniu" jam.master_email = '*****@*****.**' jam.teams = ['BestTeam', "DrużynaWygrywów"] jam.active = False db.session.add(jam) db.session.commit() game = models.Game() game.title = "Demolition n' Destruction" game.team = "BestTeam" game.description = 'gra o rozwalaniu i zniszczeniu' game.jam = 'Jam testowy' game.path = "Demolition n' Destruction.zip" db.session.add(game) db.session.commit() game = models.Game() game.title = "Diablo Origins" game.team = "DrużynaWygrywów" game.description = 'gra o niszczniu potworów' game.jam = 'Jam testowy' game.path = "Diablo Origins.zip" db.session.add(game) db.session.commit() jam = models.Jam() jam.title = "Pierwszy jam" jam.master = "patryk" jam.theme = "destruction" jam.description = "Jam o rozwalaniu" jam.master_email = '*****@*****.**' jam.teams = ['BestTeam', "MonsterCouch", 'LameTeam'] db.session.add(jam) db.session.commit() game = models.Game() game.title = "Doom 0" game.team = "BestTeam" game.description = 'Prequel Doom' game.jam = 'Pierwszy jam' game.path = "Doom 0.zip" db.session.add(game) db.session.commit() game = models.Game() game.title = "Jabba The Hutt - Fat worm story" game.team = "MonsterCouch" game.description = 'Przemierzaj pustynię Tatooine pod postacią grubego robaka i zjadaj szturmowców' game.jam = 'Pierwszy jam' game.path = "Jabba The Hutt - Fat worm story.zip" db.session.add(game) db.session.commit() game = models.Game() game.title = "Devil ain't cry" game.team = "LameTeam" game.description = 'Doprowadź diabła do płaczu' game.jam = 'Pierwszy jam' game.path = "devil ain't cry.zip" db.session.add(game) db.session.commit() jam = models.Jam() jam.title = "Szybki jam" jam.master = "wikwoj" jam.theme = "Stranger things" jam.description = "Jam o dziwnych i zwariowanych grach" jam.master_email = '*****@*****.**' jam.teams = ['DrużynaWygrywów', 'MonsterCouch', 'LameTeam'] db.session.add(jam) db.session.commit() game = models.Game() game.title = "Lightsaber tactics" game.team = "DrużynaWygrywów" game.description = 'Platformowa gra 2D, w której poruszasz się zbuntowanym rycerzem Jedi i zabijasz młodych adeptów' game.jam = 'Szybki jam' game.path = "Lightsaber tactics.zip" db.session.add(game) db.session.commit() game = models.Game() game.title = "Quit now" game.team = "MonsterCouch" game.description = 'Ciężka gra platformowa' game.jam = 'Szybki jam' game.path = "Quit now.zip" db.session.add(game) db.session.commit() game = models.Game() game.title = "Worms arena" game.team = "LameTeam" game.description = 'Bijesz się na areni będąc robakiem' game.jam = 'Szybki jam' game.path = "worms arena.zip" db.session.add(game) db.session.commit() jam = models.Jam() jam.title = "Ten jam nie istnieje" jam.master = "patryk" jam.theme = "matrix" jam.description = "Jam o niebyciu" jam.master_email = '*****@*****.**' jam.teams = ['DrużynaWygrywów', 'BestTeam', 'MonsterCouch'] jam.active = False db.session.add(jam) db.session.commit() game = models.Game() game.title = "Satelite destroyer" game.team = "BestTeam" game.description = 'Jako operator działa niszcz zbliżające się satelity wroga' game.jam = 'Ten jam nie istnieje' game.path = "Satelite destroyer.zip" db.session.add(game) db.session.commit() game = models.Game() game.title = "Wolfenstein: the old order" game.team = "DrużynaWygrywów" game.description = 'Gra, w której musisz zabić Wiliama Josepha Blazkowicza' game.jam = 'Ten jam nie istnieje' game.path = "Wolfenstein the old order!.zip" db.session.add(game) db.session.commit() game = models.Game() game.title = "Path of Neo" game.team = "MonsterCouch" game.description = 'Symulator Wiary' game.jam = 'Ten jam nie istnieje' game.path = "Path of neo.zip" db.session.add(game) db.session.commit() jam = models.Jam() jam.title = "Global game jam" jam.master = "wikwoj" jam.theme = "Wszystkie gry" jam.description = "Jam, w ktorym tolerowane sa wszystkie gatunki gier" jam.master_email = '*****@*****.**' jam.teams = ['DrużynaWygrywów', "MonsterCouch", 'LameTeam'] jam.active = False db.session.add(jam) db.session.commit() game = models.Game() game.title = "Military trucks" game.team = "MonsterCouch" game.description = 'Prosta gra wyścigowa z pojazdami wojskowymi' game.jam = 'Global game jam' game.path = "Military trucks.tar.zip" db.session.add(game) db.session.commit() game = models.Game() game.title = "Battle of tatooine" game.team = "DrużynaWygrywów" game.description = 'Jako operator działa niszcz zbliżające się statki wroga' game.jam = 'Global game jam' game.path = "Battle of tatooine.zip" db.session.add(game) db.session.commit() game = models.Game() game.title = "Shoot fast! Don't die!" game.team = "LameTeam" game.description = 'Multiplayer FPS typu arena' game.jam = 'Global game jam' game.path = "Shoot fast! Don't die!.zip" db.session.add(game) db.session.commit()