def setUpTestData(cls): super().setUpTestData() cls.game = Game(name="F-Zero") cls.game.save() ct1 = ChartType(name="CT1", game=cls.game, format_spec=[], order_ascending=True) ct1.save() cls.cg_kl = ChartGroup(name="Knight League", order_in_parent=1, game=cls.game) cls.cg_kl.save() cls.cg_ql = ChartGroup(name="Queen League", order_in_parent=2, game=cls.game) cls.cg_ql.save() cls.cg_mc1 = ChartGroup(name="Mute City I", order_in_parent=1, game=cls.game, parent_group=cls.cg_kl) cls.cg_mc1.save() cls.chart_mc1c = Chart(name="Course Time", order_in_group=1, chart_group=cls.cg_mc1, chart_type=ct1) cls.chart_mc1c.save() game_2 = Game(name="F-Zero: Maximum Velocity") game_2.save() ChartGroup(name="Pawn Cup", order_in_parent=1, game=game_2).save()
def submit_game(request): cur_user = Account.objects.get(id=request.user.id) if cur_user.account_type == 'player': #no permission if user is not a developer return render(request, 'unpermitted.html') else: if request.method == 'POST': form = SubmitForm(request.POST, request.FILES) if form.is_valid(): #insert the new game into db game = Game(title=form.cleaned_data.get('title'), description=form.cleaned_data.get('description'), price=form.cleaned_data.get('price'), genre=form.cleaned_data.get('genre'), link=form.cleaned_data.get('link'), developer=cur_user) #check if preview pic was submitted and if so, add it to the game if form.cleaned_data['preview_pic'] is not None: game.preview_pic = form.cleaned_data['preview_pic'] game.save() #make dev also an owner game.owners.add(cur_user) return HttpResponseRedirect('/accounts/profile/') else: form = SubmitForm() return render(request, 'submit.html', {'form': form})
def post(self, request): body = request.body if not body.decode('UTF-8'): return Response(status=status.HTTP_400_BAD_REQUEST) body = json.loads(body) host_uuid = body.get("host_uuid") if not host_uuid: return Response("host_uuid field is needed", status=status.HTTP_400_BAD_REQUEST) host = get_object_or_404(User, id=host_uuid) quiz_uuid = body.get("quiz_uuid") if not quiz_uuid: return Response("quiz_uuid field is needed", status=status.HTTP_400_BAD_REQUEST) quiz = get_object_or_404(Quiz, uuid=quiz_uuid) game_name = body.get("game_name") if not game_name: return Response("game_name field is needed", status=status.HTTP_400_BAD_REQUEST) name_taken = Game.objects.filter(game_name=game_name) if name_taken: return Response("Name is taken, choose a new name", status=status.HTTP_400_BAD_REQUEST) new_game = Game(game_name=game_name, host=host, quiz=quiz) new_game.save() new_game.init_game() return Response(GameSerializer(new_game).data, status=status.HTTP_201_CREATED)
def test_saves_retrieves_games(self): a_player = Player() a_player.save() first_game = Game() first_game.text = "a_score : a_player" first_game.player = a_player first_game.save() second_game = Game() second_game.text = "b_score : b_player" second_game.player = a_player second_game.save() saved_player = Player.objects.first() self.assertEqual(saved_player, a_player) saved_games = Game.objects.all() self.assertEqual(saved_games.count(), 2) first_saved_game = saved_games[0] second_saved_game = saved_games[1] self.assertEqual(first_saved_game.text, "a_score : a_player") self.assertEqual(second_saved_game.text, "b_score : b_player") self.assertEqual(first_saved_game.player, a_player) self.assertEqual(second_saved_game.player, a_player)
class TeamPresenterTestCase(TestCase): def setUp(self): self.game = Game() self.game.save() self.user = User.objects.create_user('user', '', 'password') self.player = Player(user=self.user) self.player.save() self.team = Team(player=self.player, game=self.game) self.team.save() def test_from_team(self): presenter = TeamPresenter.from_team(team=self.team, game=self.game) self.assertEqual(presenter.player.username, self.user.username) self.assertTrue(presenter.is_next) self.assertEqual(presenter.winner, self.team.winner) self.assertEqual(presenter.alive, self.team.alive) self.assertEqual(len(presenter.tiles), GAME_SIZE) self.assertEqual(len(presenter.tiles[0]), GAME_SIZE) def test_make_tiles(self): tiles = TeamPresenter.make_tiles(team=self.team, game=self.game) self.assertEqual(len(tiles), GAME_SIZE) for i in range(0, GAME_SIZE): self.assertEqual(len(tiles[i]), GAME_SIZE)
def send_contractor_on_game(self, character): game = Game( scenario=self.scenario, title="title", creator=self.user2, gm=self.user2, created_date=timezone.now(), scheduled_start_time=timezone.now(), actual_start_time=timezone.now(), end_time=timezone.now(), status=GAME_STATUS[6][0], cell=self.cell, ) game.save() attendance = Game_Attendance( relevant_game=game, notes="notes", outcome=WIN, attending_character=character, ) game_invite = Game_Invite(invited_player=character.player, relevant_game=game, as_ringer=False, ) attendance.save() game_invite.attendance = attendance game_invite.save() game.give_rewards() return attendance
def create(self, request): serializer = GameSerializer(data=request.data) if serializer.is_valid(): user = request.user player = user.player player.hosted_count += 1 player.game_count += 1 if request.data['nickname'] != "": player.nickname = request.data['nickname'] elif player.nickname == "": player.nickname = player.user.username player.save() new_game = Game() new_game.host = player new_game.name = request.data['name'] new_game.motto = request.data['motto'] new_game.passcode = request.data['passcode'] new_game.save() new_game_player_detail = GamePlayerDetail() new_game_player_detail.game = new_game new_game_player_detail.player = player new_game_player_detail.save() return Response({'status': 'game set', 'game_id': new_game.id}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def new_game(request): """ Creates a new game. player_id should already be stored inside cookie. """ private = (request.POST['isPrivate'] == 'on' if 'isPrivate' in request.POST else False) game_type = request.POST['gameType'] player_id = sessions.get_player_id(request.session) player = Player.get_by_id(Player.get_model_id(player_id)) game = Game(game_type=game_type, creator=player, private=private, current_turn=player) game.save() game_id = Game.get_game_id(game.id) game.game_id = game_id game.save() text = 'Game created' entry = GameLogEntry(game=game, text=text) entry.save() # Send a ws message to the lobby group Group('lobby').send({'text': json.dumps(Game.get_all_games_list())}) return HttpResponseRedirect(reverse('games:game', args=(game.id,)))
def create(self, request): serializer = GameSerializer(data=request.data) if serializer.is_valid(): user = request.user player = user.player player.hosted_count += 1 player.game_count += 1 if request.data['nickname'] != "": player.nickname = request.data['nickname'] elif player.nickname == "": player.nickname = player.user.username player.save() new_game = Game() new_game.host = player new_game.name = request.data['name'] new_game.motto = request.data['motto'] new_game.passcode = request.data['passcode'] new_game.save() new_game_player_detail = GamePlayerDetail() new_game_player_detail.game = new_game new_game_player_detail.player = player new_game_player_detail.save() return Response({'status': 'game set', 'game_id': new_game.id}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class IsTeamNextTestCase(TestCase): def setUp(self): self.game = Game() self.game.save() self.user1 = User.objects.create_user('user1', '', 'password') self.user2 = User.objects.create_user('user2', '', 'password') self.user3 = User.objects.create_user('user3', '', 'password') self.player1 = Player(user=self.user1) self.player2 = Player(user=self.user2) self.player3 = Player(user=self.user3) self.player1.save() self.player2.save() self.player3.save() self.team1 = Team(player=self.player1, game=self.game, last_turn=1) self.team2 = Team(player=self.player2, game=self.game, last_turn=2) self.team3 = Team(player=self.player3, game=self.game, last_turn=3) self.team1.save() self.team2.save() self.team3.save() def test_team_is_next(self): self.assertTrue(is_team_next(self.team1, self.game)) def test_team_is_not_next(self): self.assertFalse(is_team_next(self.team2, self.game)) self.assertFalse(is_team_next(self.team3, self.game)) def test_non_alive_team(self): self.team1.alive = False self.team1.save() self.assertTrue(is_team_next(self.team2, self.game))
def create_game(self, fake, teams, round_number): home_teams = teams[1::2] away_teams = teams[0::2] for i in range(len(home_teams)): home_score = fake.random_int(min=0, max=186, step=1) away_score = fake.random_int(min=0, max=186, step=1) winning_team = home_teams[ i] if home_score > away_score else away_teams[i] home = home_teams[i] if round_number == 'QF' else home_teams[ i].game_winning_team away = away_teams[i] if round_number == 'QF' else away_teams[ i].game_winning_team winner = winning_team if round_number == 'QF' else winning_team.game_winning_team try: game = Game(home_team=home, away_team=away, game_played=True, game_winning_team=winner, round_number=round_number, home_team_score=home_score, away_team_score=away_score, date=fake.date_time_this_decade(before_now=True, after_now=False, tzinfo=None)) except ObjectDoesNotExist: raise CommandError('games populated') game.save() self.stdout.write( self.style.SUCCESS( '%s Game %s Vs %s => winner : %s ' % (round_number, home.id, away.id, winner.id)))
def invite(hometeam,awayteam): game=Game(player_1=hometeam, player_2=awayteam) game.save() message = client.messages.create(to=hometeam, from_="+16502156107", body="Your game has started. Make your first move...")
def test_ship_creation(self): """Test that Ship instances are created correctly.""" game = Game() game.save() user = User(username='******', password='******') user.save() player = Player(user=user) player.save() team = Team(player=player, game=game) team.save() ship = Ship( team=team, x=0, y=0, length=3, direction=Ship.CARDINAL_DIRECTIONS['WEST'] ) self.assertTrue(isinstance(ship, Ship)) self.assertEqual( str(ship), 'Game 1 - user\'s 3L at (0, 0) facing West' )
def handle(self, *args, **options): g = Game(name="F-Zero GX") g.save() gx_time_spec = [ dict(multiplier=60, suffix="'"), dict(multiplier=1000, suffix='"', digits=2), dict(digits=3)] course = ChartType( game=g, name="Course Time", format_spec=gx_time_spec, order_ascending=True) course.save() lap = ChartType( game=g, name="Lap Time", format_spec=gx_time_spec, order_ascending=True) lap.save() speed = ChartType( game=g, name="Speed", format_spec=[dict(suffix=" km/h")], order_ascending=False) speed.save() machine = FilterGroup( game=g, name="Machine", show_by_default=True, order_in_game=1, description="Racing machine used for the run.", kind=FilterGroup.Kinds.SELECT.value) machine.save() setting = FilterGroup( game=g, name="Setting", show_by_default=True, order_in_game=2, description="Acceleration/max speed setting used for the run." " 0% all the way at the left, 100% all the way at" " the right.", kind=FilterGroup.Kinds.NUMERIC.value) setting.save() Filter(name="0%", numeric_value=0, filter_group=setting).save() Filter(name="100%", numeric_value=100, filter_group=setting).save() checks = FilterGroup( game=g, name="Checkpoint skips", show_by_default=False, order_in_game=3, description="Whether checkpoint skipping" " was used in the run or not.", kind=FilterGroup.Kinds.SELECT.value) checks.save() Filter(name="Yes", filter_group=checks).save() Filter(name="No", filter_group=checks).save() for ct in [course, lap, speed]: ct.filter_groups.add(machine, setting) for ct in [course, lap]: ct.filter_groups.add(checks) call_command('chart_import') call_command( 'filter_import', 'fzc_data_import/data/gx_machine_filters.csv') call_command( 'record_player_import_for_fzc', *[options[arg_name] for arg_name in ['mysql_host', 'mysql_port', 'mysql_dbname', 'mysql_user']])
def test_game_id(self): self._test_field_type(Game, 'Game', 'id', models.AutoField) game = Game(title=self.randstr, id=self.randint) game.save() self.assertEquals( game.id, self.randint, "Testing if id %s equals assigned id %s" % (game.id, self.randint)) game.delete()
def import_report(game: Game, path: str): tables = tabula.read_pdf(path, output_format='json', **{'pages': [1, 2], 'lattice': True}) game.spectators = parse_report.parse_spectators(tables[0]) game.save() import_scores(tables[2], game=game, team=game.home_team) import_scores(tables[3], game=game, team=game.guest_team)
def post(self, request, *args, **kwargs): if request.user.is_authenticated(): form = CreateGameForm(request.POST, max_players=MAX_PLAYERS) if form.is_valid(): opponent_usernames = [] for i in range(0, MAX_PLAYERS): field_name = 'opponent_username_{}'.format(i) opponent_usernames.append(form.cleaned_data[field_name]) try: opponent_users = [] for opponent_username in opponent_usernames: if len(opponent_username) > 0: opponent_users.append( User.objects.get(username=opponent_username)) except User.DoesNotExist: error_message = 'User does not exist! '\ 'Are you sure the username is correct?' messages.error(request, error_message) context = {'form': form} return render(request, self.template_name, context) user_player = Player.objects.get(user=request.user) opponent_players = [ Player.objects.get(user=opponent_user) for opponent_user in opponent_users ] # Create a game plus teams and ships for both players # Creation in Game -> Team -> Ships order is important # to satisfy ForeignKey dependencies. game = Game() game.save() user_team = Team(player=user_player, game=game, last_turn=-2) opponent_teams = [ Team(player=opponent_player, game=game, last_turn=-1) for opponent_player in opponent_players ] user_team.save() for opponent_team in opponent_teams: opponent_team.save() user_ships = make_ships(user_team, Ship.LENGTHS) for opponent_team in opponent_teams: opponent_ships = make_ships(opponent_team, Ship.LENGTHS) for user_ship in user_ships: user_ship.save() for opponent_ship in opponent_ships: opponent_ship.save() return HttpResponseRedirect(reverse('game', args=[game.id])) else: messages.error(request, 'Invalid form.') context = {'form': form} return render(request, self.template_name, context) else: return HttpResponseRedirect('/login')
def new_game(request): game = Game( title = 'New Game', description = 'Write a description here', author = request.user, pubDate = datetime.datetime.now(), lastEditDate = datetime.datetime.now()) game.save() return render_to_response('build.html',{'game_id':game.id}, context_instance=RequestContext(request))
def test_game_slugify_on_save(self): """ Tests the slug generated when saving a Game. """ # Author is a required field in our model. # Create a user for this test and save it to the test database. user = User() user.save() # Create and save a new page to the test database. game = Game(name="My Test Game", description="test") game.save()
def save_game(request): if request.method == 'POST': info = json.loads(request.body); newGame = Game(title=info.get('title'), description=info.get('description')) newGame.pubDate = datetime.datetime.now() newGame.author = User.objects.get(username='******') newGame.numberQuestions = 0 newGame.save() pdb.set_trace() return HttpResponse(request.body, mimetype="application/json")
def import_report(game: Game, path: Path): [spectators_table, _, home_table, guest_table] = \ tabula.read_pdf(path.absolute(), output_format='json', pages=[1, 2], lattice=True) # type: ignore[arg-type] # see https://github.com/chezou/tabula-py/pull/315 game.spectators = parse_report.parse_spectators(spectators_table) game.save() import_scores(home_table, game=game, team=game.home_team) import_scores(guest_table, game=game, team=game.guest_team)
def create(request): if request.method == "POST": game = Game() game.name = request.POST['name'] game.player_one = request.user.get_profile() couch = couchdb.Server(settings.COUCHDB_HOST) db = couch[settings.COUCHDB_NAME] game.couch_id = db.create({'game': db['game_start']['game']}) game.save() return HttpResponseRedirect(game.get_absolute_url()) else: raise Http404
def save(request, company_id, office_id): game_name = request.POST.get('name') game_mode = request.POST.get('mode') game_updated = timezone.now() game = Game(office_id=office_id, name=game_name, mode=game_mode, updated=game_updated) game.save() return HttpResponseRedirect('/company/' + str(company_id) + '/office/' + str(office_id) + '/game/' + str(game.id))
def test_archive_game_death(self): self.assertEquals(self.char_user1_cell.unspent_rewards().count(), 0) self.assertEquals(self.char_user1_cell.unspent_gifts().count(), 0) self.assertEquals(self.char_user1_cell.completed_games().count(), 0) self.assertEquals(self.char_user1_cell.number_of_victories(), 0) self.assertEquals(self.char_user1_cell.number_of_losses(), 0) self.assertEquals(self.char_user1_cell.stats_snapshot.sources.count(), 0) self.assertEquals(self.char_user1_cell.exp_earned(), EXP_NEW_CHAR) self.assertEquals( self.user1.rewarded_player .filter(rewarded_character=None, is_charon_coin=True) .filter(is_void=False).all().count(), 0) game = Game( title="title", creator=self.user2, gm=self.user2, created_date=timezone.now(), scheduled_start_time=timezone.now(), actual_start_time=timezone.now(), end_time=timezone.now(), status=GAME_STATUS[6][0], cell=self.cell, ) game.save() attendance = Game_Attendance( relevant_game=game, notes="notes", outcome=OUTCOME[2][0], # death attending_character=self.char_user1_cell, ) game_invite = Game_Invite(invited_player=self.user1, relevant_game=game, as_ringer=False, ) attendance.save() game_invite.attendance = attendance game_invite.save() game.give_rewards() self.assertEquals(self.char_user1_cell.unspent_rewards().count(), 0) self.assertEquals(self.char_user1_cell.unspent_gifts().count(), 0) self.assertEquals(self.char_user1_cell.completed_games().count(), 1) self.assertEquals(self.char_user1_cell.number_of_victories(), 0) self.assertEquals(self.char_user1_cell.number_of_losses(), 0) self.assertEquals(self.char_user1_cell.stats_snapshot.sources.count(), 0) self.assertEquals(self.char_user1_cell.exp_earned(), EXP_NEW_CHAR) self.assertEquals(self.char_user1_cell.is_dead(), True) self.assertEquals( self.user1.rewarded_player .filter(rewarded_character=None, is_charon_coin=True) .filter(is_void=False).all().count(), 1)
def post(self, request, *args, **kwargs): if request.user.is_authenticated(): form = CreateGameForm(request.POST, max_players=MAX_PLAYERS) if form.is_valid(): opponent_usernames = [] for i in range(0, MAX_PLAYERS): field_name = "opponent_username_{}".format(i) opponent_usernames.append(form.cleaned_data[field_name]) try: opponent_users = [] for opponent_username in opponent_usernames: if len(opponent_username) > 0: opponent_users.append(User.objects.get(username=opponent_username)) except User.DoesNotExist: error_message = "User does not exist! " "Are you sure the username is correct?" messages.error(request, error_message) context = {"form": form} return render(request, self.template_name, context) user_player = Player.objects.get(user=request.user) opponent_players = [Player.objects.get(user=opponent_user) for opponent_user in opponent_users] # Create a game plus teams and ships for both players # Creation in Game -> Team -> Ships order is important # to satisfy ForeignKey dependencies. game = Game() game.save() user_team = Team(player=user_player, game=game, last_turn=-2) opponent_teams = [ Team(player=opponent_player, game=game, last_turn=-1) for opponent_player in opponent_players ] user_team.save() for opponent_team in opponent_teams: opponent_team.save() user_ships = make_ships(user_team, Ship.LENGTHS) for opponent_team in opponent_teams: opponent_ships = make_ships(opponent_team, Ship.LENGTHS) for user_ship in user_ships: user_ship.save() for opponent_ship in opponent_ships: opponent_ship.save() return HttpResponseRedirect(reverse("game", args=[game.id])) else: messages.error(request, "Invalid form.") context = {"form": form} return render(request, self.template_name, context) else: return HttpResponseRedirect("/login")
def create_game(request): if request.method == 'POST': form = make_game_form(user=request.user, game_status=GAME_STATUS[0][0])(request.POST) if form.is_valid(): game = Game( title=form.cleaned_data['title'], creator=request.user, gm=request.user, required_character_status=form. cleaned_data['required_character_status'], hook=form.cleaned_data['hook'], created_date=timezone.now(), scheduled_start_time=form.cleaned_data['scheduled_start_time'], open_invitations=form.cleaned_data['open_invitations'], status=GAME_STATUS[0][0], cell=form.cleaned_data['cell']) if form.cleaned_data['scenario']: game.scenario = form.cleaned_data['scenario'] with transaction.atomic(): game.save() if form.cleaned_data['invite_all_members']: for member in game.cell.cellmembership_set.exclude( member_player=game.gm): game_invite = Game_Invite( invited_player=member.member_player, relevant_game=game, invite_text=game.hook, as_ringer=False) game_invite.save() game_invite.notify_invitee(request, game) game_url = reverse('games:games_view_game', args=(game.id, )) messages.add_message( request, messages.SUCCESS, mark_safe( "Your Game has been created Successfully." "<br>" "<a href='" + game_url + "'> Click Here</a> " "if you do not want to invite anyone else at this time.")) return HttpResponseRedirect( reverse('games:games_invite_players', args=(game.id, ))) else: print(form.errors) return None else: # Build a game form. form = make_game_form(user=request.user, game_status=GAME_STATUS[0][0]) context = { 'form': form, } return render(request, 'games/edit_game.html', context)
def test_team_creation(self): """Test that Team instances are created correctly.""" game = Game() game.save() user = User.objects.create_user('user', '', 'password') player = Player(user=user) player.save() team = Team(player=player, game=game) self.assertTrue(isinstance(team, Team)) self.assertEqual(str(team), 'Game 1 - user (last_turn=0)')
def _create_tags(self): f = open(r'C:/Users/Sam/.spyder-py3/chessData.txt','r') line = f.readline() string = "" while line: if ("split" in line): tlisp = Game(pgn = string) tlisp.save() string = "" line = f.readline() continue if ('[' not in line): string += line line = f.readline()
def update(self, instance: Game, validated_data: Dict[str, Any]): # Todo request の値が None のときに例外を発行 x = validated_data.pop('x') y = validated_data.pop('y') # validate メソットだと instance の情報がないためここで検証 if not instance.winner == WinnerChoices.EMPTY.value[0]: raise serializers.ValidationError('有効な座標ではありません') if not instance.valid_reversing(x, y): raise serializers.ValidationError('有効な座標ではありません') instance.reversing(x, y) instance.save() return instance
def create_game(game_num, roster_soup): # pull team name data from txt - first two instances of class teamHeading teams = roster_soup.find_all("td", class_="teamHeading") away_name = teams[0].text.encode("utf-8") home_name = teams[1].text.encode("utf-8") # Creates TeamGame objects home, away away = TeamGame.objects.create(team=Team.objects.get(name=away_name)) home = TeamGame.objects.create(team=Team.objects.get(name=home_name)) game = Game(game_id=game_num, team_home=home, team_away=away, date=import_date(roster_soup)) game.save() return game
def import_games(csv_file): with open(csv_file, 'r') as file: csv_reader = csv.DictReader(file) for row in csv_reader: g = Game() g.location = row["location"] g.name = row["name"] hour = row["time"].split(":")[0] minute = row["time"].split(":")[1] year = row["date"].split("-")[0] month = row["date"].split("-")[1] day = row["date"].split("-")[2] g.date = date(int(year), int(month), int(day)) g.time = time(int(hour), int(minute)) g.save()
def mutate_and_get_payload(root, info, **input): if input.get("collectionname"): collection, created = Collection.objects.get_or_create(collectionname=input.get("collectionname")) game=Game(name=input.get("name"), price=input.get("price"), datereleased=input.get("datereleased"), collection=collection ) else: game=Game(name=input.get("name"), price=input.get("price"), datereleased=input.get("datereleased"), ) game.save() return addGame(game=game)
def test_game_requires_players(self): arena = make_a_whole_arena() course = make_course(arena)[0] player = make_players()[0] game = Game( course=course, creator=player, created=datetime.now(), ) game.save() game.players = [player] game.start() # Check that game doesn't finish without players self.assertRaises(ValidationError, game.finish)
def test_archive_game_gm_rewards_ratio(self): self.assertEquals(self.user2.experiencereward_set.filter(rewarded_character=None).all().count(), 0) self.assertEquals( self.user2.rewarded_player.filter(rewarded_character=None, is_charon_coin=False).filter(is_void=False).all().count(), 0) game = Game( title="title", creator=self.user2, gm=self.user2, created_date=timezone.now(), scheduled_start_time=timezone.now(), actual_start_time=timezone.now(), end_time=timezone.now(), status=GAME_STATUS[6][0], cell=self.cell, ) game.save() attendance = Game_Attendance( relevant_game=game, notes="notes", outcome=WIN, attending_character=self.char_user1_cell, ) game_invite = Game_Invite(invited_player=self.user1, relevant_game=game, as_ringer=False, ) attendance.save() game_invite.attendance = attendance game_invite.save() attendance = Game_Attendance( relevant_game=game, notes="notes", outcome=DEATH, attending_character=self.char_user2_cell, ) game_invite = Game_Invite(invited_player=self.user2, relevant_game=game, as_ringer=False, ) attendance.save() game_invite.attendance = attendance game_invite.save() game.give_rewards() self.assertEquals(self.user2.experiencereward_set.filter(rewarded_character=None).all().count(), 1) self.assertEquals(self.user2.rewarded_player.filter(rewarded_character=None, is_charon_coin=False).filter(is_void=False).all().count(), 1)
def test_archive_game_victory_not_in_cell(self): self.assertEquals(self.char_user2_nocell.unspent_rewards().count(), 0) self.assertEquals(self.char_user2_nocell.unspent_gifts().count(), 0) self.assertEquals(self.char_user2_nocell.completed_games().count(), 0) self.assertEquals(self.char_user2_nocell.number_of_victories(), 0) self.assertEquals(self.char_user2_nocell.number_of_losses(), 0) self.assertEquals(self.char_user2_nocell.stats_snapshot.sources.count(), 0) self.assertEquals(self.char_user2_nocell.exp_earned(), EXP_NEW_CHAR) self.assertEquals(self.user2.game_invite_set.filter(attendance__is_confirmed=False).exclude(is_declined=True).all().count(), 0) game = Game( title="title", creator=self.user1, gm=self.user1, created_date=timezone.now(), scheduled_start_time=timezone.now(), actual_start_time=timezone.now(), end_time=timezone.now(), status=GAME_STATUS[6][0], cell=self.cell, ) game.save() attendance = Game_Attendance( relevant_game=game, notes="notes", outcome=OUTCOME[0][0], # victory attending_character=self.char_user2_nocell, is_confirmed = False, ) game_invite = Game_Invite(invited_player=self.user2, relevant_game=game, as_ringer=False, ) attendance.save() game_invite.attendance = attendance game_invite.save() game.give_rewards() self.assertEquals(self.char_user2_nocell.unspent_rewards().count(), 0) self.assertEquals(self.char_user2_nocell.unspent_gifts().count(), 0) self.assertEquals(self.char_user2_nocell.completed_games().count(), 0) self.assertEquals(self.char_user2_nocell.number_of_victories(), 0) self.assertEquals(self.char_user2_nocell.number_of_losses(), 0) self.assertEquals(self.char_user2_nocell.stats_snapshot.sources.count(), 0) self.assertEquals(self.char_user2_nocell.exp_earned(), EXP_NEW_CHAR) self.assertEquals(self.user2.game_invite_set.filter(attendance__is_confirmed=False).exclude(is_declined=True).all().count(), 1)
def create_game(game_num, roster_soup): #pull team name data from txt - first two instances of class teamHeading teams = roster_soup.find_all('td', class_="teamHeading") away_name = teams[0].text.encode('utf-8') home_name = teams[1].text.encode('utf-8') #Creates TeamGame objects home, away away = TeamGame.objects.create(team=Team.objects.get(name=away_name)) home = TeamGame.objects.create(team=Team.objects.get(name=home_name)) game = Game(game_id=game_num, team_home=home, team_away=away, date=import_date(roster_soup)) game.save() return game
class ModelTestCase(TestCase): def setUp(self): self.game_id = "1" self.game_home_team = "1" self.game_away_team = "2" self.game_start_date = "2019-05-16" self.game_start_time = "2019-05-16T08:24:00" self.gameList = Game(home_team=self.game_home_team, away_team=self.game_away_team, start_date=self.game_start_date, start_time=self.game_start_time) def test_model_can_create_a_game(self): """Test the game model can create a game.""" old_count = Game.objects.count() self.gameList.save() new_count = Game.objects.count() self.assertNotEqual(old_count, new_count)
def _create_games(self, n=1): if Color.objects.count() < Game.AVAILABLE_COLORS: print "Impossible to create games. No enough colors." print "ESCAPING..." return print "Populating Games" for i in range(n): available_colors = Color.objects.all().order_by('?')[:Game.AVAILABLE_COLORS] game = Game() game.initial_amount = random.randint(0, 100) game.percentage = random.randint(0, 100) game.payment = random.uniform(0, 5) game.start_date = timezone.now() game.end_date = game.start_date + datetime.timedelta(days=random.randint(3, 30)) game.save() game.available_colors.add(*available_colors) print "SUCCESS"
def create_game(game): """ Create game object from Steam API call """ from games.models import Game slug = slugify(game['name'])[:50] LOGGER.info("Adding %s to library" % game['name']) steam_game = Game( name=game['name'], steamid=game['appid'], slug=slug, ) if game['img_logo_url']: steam_game.get_steam_logo(game['img_logo_url']) steam_game.get_steam_icon(game['img_icon_url']) try: steam_game.save() except Exception as ex: LOGGER.error("Error while saving game %s: %s", game, ex) raise return steam_game
def create_game(game): """ Create game object from Steam API call """ from games.models import Game slug = slugify(game['name'])[:50] LOGGER.info("Adding %s to library" % game['name']) steam_game = Game( name=game['name'], steamid=game['appid'], slug=slug, ) if game['img_logo_url']: steam_game.get_steam_logo(game['img_logo_url']) steam_game.get_steam_icon(game['img_icon_url']) try: steam_game.save() except Exception as ex: LOGGER.error("Error while saving game %s: %s", game, ex) raise return steam_game
def _create_tags(self): quoted = re.compile('"[^"]*"') f = open(r'C:/Users/Sam/Desktop/ChessVisualizer-master/backend/src/games/management/commands/chessData.txt','r') line = f.readline() string = "" white = "" black = "" whiteelo = "" blackelo = "" date = "" event = "" result = "" while line: if ("split" in line): tlisp = Game(pgn = string, white = white, black = black, whiteelo = whiteelo, blackelo = blackelo, date = date, event = event, result = result) tlisp.save() string = "" line = f.readline() continue if ('[' in line or ']' in line): event = quoted.findall(line)[0] line = f.readline() line = f.readline() date = quoted.findall(line)[0] line = f.readline() line = f.readline() line = f.readline() result = quoted.findall(line)[0] line = f.readline() white = quoted.findall(line)[0] line = f.readline() black = quoted.findall(line)[0] line = f.readline() line = f.readline() whiteelo = quoted.findall(line)[0] line = f.readline() blackelo = quoted.findall(line)[0] f.readline() f.readline() if ('[' not in line): string += line line = f.readline()
def test_game_creation(self): """Test that Game instances are created correctly.""" game = Game() game.save() user1 = User.objects.create_user('user1', '', 'password') user2 = User.objects.create_user('user2', '', 'password') player1 = Player(user=user1) player2 = Player(user=user2) player1.save() player2.save() team1 = Team(player=player1, game=game) team2 = Team(player=player2, game=game) team1.save() team2.save() self.assertTrue(isinstance(game, Game)) self.assertEqual(str(game), '1 - user1 user2')
def test_shot_creation(self): """Test that Shot instances are created correctly.""" game = Game() game.save() attacking_user = User.objects.create_user( 'attacking_user', '', 'password' ) defending_user = User.objects.create_user( 'defending_user', '', 'password' ) attacking_user.save() defending_user.save() attacking_player = Player(user=attacking_user) defending_player = Player(user=defending_user) attacking_player.save() defending_player.save() attacking_team = Team(player=attacking_player, game=game) defending_team = Team(player=defending_player, game=game) attacking_team.save() defending_team.save() shot = Shot( game=game, attacking_team=attacking_team, defending_team=defending_team, x=0, y=0 ) self.assertTrue(isinstance(shot, Shot)) self.assertEqual( str(shot), 'Game 1 - attacking_user attacked defending_user (0, 0)' )
class PlayerPresenterTestCase(TestCase): def setUp(self): self.user = User.objects.create_user("user1", "", "password") self.player = Player(user=self.user) self.player.save() self.winning_game = Game() self.losing_game = Game() self.in_progress_game = Game() self.winning_game.save() self.losing_game.save() self.in_progress_game.save() self.winning_team = Team(game=self.winning_game, player=self.player, alive=True, winner=True) self.losing_team = Team(game=self.losing_game, player=self.player, alive=False, winner=False) self.in_progress_team = Team(game=self.in_progress_game, player=self.player, alive=True, winner=False) self.winning_team.save() self.losing_team.save() self.in_progress_team.save() def test_from_player(self): presenter = PlayerPresenter.from_player(self.player) self.assertEqual(presenter.username, self.user.username) self.assertEqual(presenter.win_count, 1) self.assertEqual(presenter.loss_count, 1) self.assertEqual(presenter.in_progress_count, 1)
def new_game(request): #Create a new game game = Game( title = 'New Game', description = 'Write a description here', author = request.user, pubDate = datetime.datetime.now(), lastEditDate = datetime.datetime.now()) game.save() layer = Layer( gameID = game, layerID = 0, goal = 0, target = 1, timeLimit = 5, instruction = '"edit this instruction"', background = '"#a4c4c3"', xGrav = 0, yGrav = 10) layer.save() return redirect('/build/' + str(game.id))
class GamePresenterTestCase(TestCase): def setUp(self): self.game = Game() self.game.save() self.user1 = User.objects.create_user('user1', '', 'password') self.user2 = User.objects.create_user('user2', '', 'password') self.player1 = Player(user=self.user1) self.player2 = Player(user=self.user2) self.player1.save() self.player2.save() self.team1 = Team(player=self.player1, game=self.game) self.team2 = Team(player=self.player2, game=self.game) self.team1.save() self.team2.save() def test_from_game(self): presenter = GamePresenter.from_game(self.game) self.assertEqual(presenter.id, self.game.id) self.assertEqual(len(presenter.teams), 2)
def create(request): #penser à tester si le joueur enregistré n'a pas déjà n parties maximum de crées à son actif if request.method == "POST": try: chosen_name = request.POST["name"] if not re.search('^[a-zA-Z0-9_]*$',chosen_name): raise "WrongNameError" selected_map = MapPatron.objects.get(id=request.POST['map']) except (KeyError,"WrongNameError"): return render(request, 'games/create.html', { 'error_message': "You didn't select an existing map/invalid game name. Only characters a-z A-Z and 0-9 are accepted.", }) else: g = Game(name=chosen_name,start_date=timezone.now(),map=selected_map) g.save() return HttpResponseRedirect(reverse('games:lobby', args=(g.id,))) else: list_maps = MapPatron.objects.all() return render_to_response('games/create.html', { 'list_maps': list_maps },context_instance=RequestContext(request))
class IsTeamNextTestCase(TestCase): def setUp(self): self.game = Game() self.game.save() self.user1 = User.objects.create_user('user1', '', 'password') self.user2 = User.objects.create_user('user2', '', 'password') self.user3 = User.objects.create_user('user3', '', 'password') self.player1 = Player(user=self.user1) self.player2 = Player(user=self.user2) self.player3 = Player(user=self.user3) self.player1.save() self.player2.save() self.player3.save() self.team1 = Team(player=self.player1, game=self.game, last_turn=1) self.team2 = Team(player=self.player2, game=self.game, last_turn=2) self.team3 = Team(player=self.player3, game=self.game, last_turn=3) self.team1.save() self.team2.save() self.team3.save() def test_team_is_next(self): self.assertTrue(is_team_next(self.team1, self.game)) def test_team_is_not_next(self): self.assertFalse(is_team_next(self.team2, self.game)) self.assertFalse(is_team_next(self.team3, self.game)) def test_non_alive_team(self): self.team1.alive = False self.team1.save() self.assertTrue(is_team_next(self.team2, self.game))
class HomeViewTestCase(TestCase): def setUp(self): self.game1 = Game() self.game2 = Game() self.game1.save() self.game2.save() self.user1 = User.objects.create_user('user1', '', 'password') self.user2 = User.objects.create_user('user2', '', 'password') self.player1 = Player(user=self.user1) self.player2 = Player(user=self.user2) self.player1.save() self.player2.save() self.team_game1 = Team( player=self.player1, game=self.game1 ) self.team_game2 = Team( player=self.player1, game=self.game2, alive=False ) self.team_game1.save() self.team_game2.save() def test_logged_out(self): url = reverse('home') resp = self.client.get(url) self.assertEqual(resp.status_code, 200) pq = PyQuery(resp.content) self.assertIn('You\'re not logged in', pq('h3').text()) links = [e.attr('href') for e in pq('.container a').items()] self.assertIn(reverse('login'), links) self.assertIn(reverse('signup'), links) def test_logged_in_with_matches(self): self.client.login( username=self.user1.username, password='******' ) url = reverse('home') resp = self.client.get(url) self.assertEqual(resp.status_code, 200) pq = PyQuery(resp.content) # Assert links to 'Create New Game' plus ongoing games are shown self.assertIn('Your Active Games', pq('h3').text()) links = [e.attr('href') for e in pq('.container a').items()] self.assertIn(reverse('game', args=[self.game1.id]), links) self.assertNotIn(reverse('game', args=[self.game2.id]), links) self.assertIn(reverse('create_game'), links) def test_logged_in_without_matches(self): self.client.login( username=self.user2.username, password='******' ) url = reverse('home') resp = self.client.get(url) self.assertEqual(resp.status_code, 200) pq = PyQuery(resp.content) # Assert only link to 'Create New Game' is shown self.assertEqual(len(pq('.container a')), 1) links = [e.attr('href') for e in pq('.container a').items()] self.assertIn(reverse('create_game'), links)
class TilePresenterTestCase(TestCase): def setUp(self): self.game = Game() self.game.save() self.user1 = User.objects.create_user('user1', '', 'password') self.user2 = User.objects.create_user('user2', '', 'password') self.player1 = Player(user=self.user1) self.player2 = Player(user=self.user2) self.player1.save() self.player2.save() self.team1 = Team(player=self.player1, game=self.game) self.team2 = Team(player=self.player2, game=self.game) self.team1.save() self.team2.save() self.ship = Ship( team=self.team2, x=3, y=3, length=3, direction=Ship.CARDINAL_DIRECTIONS['SOUTH'] ) self.ship.save() self.shot_miss = Shot( game=self.game, attacking_team=self.team1, defending_team=self.team2, x=2, y=3 ) self.shot_miss.save() self.shot_hit = Shot( game=self.game, attacking_team=self.team1, defending_team=self.team2, x=3, y=5 ) self.shot_hit.save() def test_from_team(self): presenter = TilePresenter.from_team( x=0, y=1, team=self.team2, game=self.game ) self.assertEqual(presenter.x, 0) self.assertEqual(presenter.y, 1) self.assertEqual(presenter.name, 'A1') self.assertTrue(presenter.is_empty) self.assertFalse(presenter.is_hit) def test_from_team_with_miss(self): presenter = TilePresenter.from_team( x=2, y=3, team=self.team2, game=self.game ) self.assertEqual(presenter.x, 2) self.assertEqual(presenter.y, 3) self.assertEqual(presenter.name, 'C3') self.assertTrue(presenter.is_empty) self.assertTrue(presenter.is_hit) def test_from_team_with_ship(self): presenter = TilePresenter.from_team( x=3, y=4, team=self.team2, game=self.game ) self.assertEqual(presenter.x, 3) self.assertEqual(presenter.y, 4) self.assertEqual(presenter.name, 'D4') self.assertFalse(presenter.is_empty) self.assertFalse(presenter.is_hit) def test_from_team_with_hit_ship(self): presenter = TilePresenter.from_team( x=3, y=5, team=self.team2, game=self.game ) self.assertEqual(presenter.x, 3) self.assertEqual(presenter.y, 5) self.assertEqual(presenter.name, 'D5') self.assertFalse(presenter.is_empty) self.assertTrue(presenter.is_hit)
try: gt = GameTag.objects.filter(name=tag).get() except GameTag.DoesNotExist: gt = GameTag(name=tag) gt.save(); gametags.append(gt) try: g = Game(category=gc, longdescription=unicode(long_desc), gameurl = gameurl, embed = embed.group('embed'), title = embed.group('title'), instructions = instructions, shortdescription= embed.group('shortdescription'), icon = rot+(embed.group('icon')[1:]), maker = gm) g.save() for tag in gametags: g.tags.add(tag) except UnicodeDecodeError: print 'Cant decode with unicode' except NoDetails: print "No details for %s." % embed.group(2) else: nxt = re.match(".*<a href='([^']+)'> Next",game) if nxt: nxt = nxt.group(1)