Beispiel #1
0
    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()
Beispiel #2
0
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...")
Beispiel #3
0
    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'
        )
Beispiel #4
0
def _create_event(team: Team, game: Game) -> Result[Event, ErrCode]:
    if not game.opening_whistle:
        return Result.from_failure(ErrCode.MISSING_OPENING_WHISTLE)

    venue = 'Heimspiel' if game.home_team == team else 'Auswärtsspiel'
    summary = f'{venue} - {game.opponent_of(team).short_name}'

    leg_title = game.leg_title()
    description = f'{leg_title} gegen {game.opponent_of(team).name}'
    if game.sports_hall:
        description += '\nSporthalle: ' + str(game.sports_hall.name)

    dated_games = game.other_games().filter(opening_whistle__isnull=False)
    for other in sorted(dated_games, key=lambda g: g.opening_whistle):
        if other.home_goals is not None:
            description += f'\n{other.leg_title()}: {other.home_goals}:{other.guest_goals} ({_outcome(other, team)})'

    start = game.opening_whistle
    end = start + timedelta(minutes=90)
    dtstamp = datetime.now()
    location = game.sports_hall.address if game.sports_hall else None
    uid = f'game/{game.number}@hbscorez.de'

    event = Event()
    event.add('summary', summary)
    event.add('description', description)
    event.add('dtstart', start)
    event.add('dtend', end)
    event.add('dtstamp', dtstamp)
    if location:
        event['location'] = vText(location)
    event['uid'] = uid

    return Result.from_value(event)
Beispiel #5
0
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})
Beispiel #6
0
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 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()
Beispiel #8
0
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))
Beispiel #9
0
    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 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']])
Beispiel #11
0
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)
Beispiel #12
0
    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')
Beispiel #13
0
    def receive(self, content, **kwargs):
        """
        Handle web socket message.

        Can be:
        1) New, valid move received. Add game log entry and update clients.
        or 2) Chat message.
        """
        game_id = kwargs['game_id']
        print('game-%s content: %s' % (game_id, content))
        game = Game.get_by_id(game_id)
        if content['message_type'] == 'new_move':
            # content contains keys 'move', 'board', and 'game_over', 'next_player'
            board_text = json.dumps(content['board'])
            game.board = board_text
            if 'extra_state' in content:
                game.extra_state = json.dumps(content['extra_state'])
            next_player = Player.get_by_id(
                Player.get_model_id(content['next_player']))
            game.current_turn = next_player
            if content['game_over']:
                game.completed = now()
            game.save()

            text = content['move']
            entry = GameLogEntry(game=game, text=text)
            entry.save()
            game_log = GameLogEntry.get_game_log_entries_for_game(game)
            serialized_data = GameLogEntry.serialize_entries(game_log)
            extra_state = json.loads(
                game.extra_state) if game.extra_state else ''
            data = {
                'message_type': 'new_move',
                'board': json.loads(game.board),
                'extra_state': extra_state,
                'move_text': content['move'],
                'current_turn': Player.get_player_id(game.current_turn.id),
                'game_log': serialized_data,
                'completed': Game.serialize_games([game])[0]['completed'],
            }
            Group('game-%s' % game_id).send({'text': json.dumps(data)})
        elif content['message_type'] == 'chat':
            player_id = content['player']
            player = Player.get_by_id(Player.get_model_id(player_id))
            new_chat_entry = ChatEntry(game=game,
                                       player=player,
                                       text=content['text'])
            new_chat_entry.save()
            chat_entries = ChatEntry.get_chat_entries_for_game(game)
            data = {
                'message_type': 'new_chat',
                'chat': ChatEntry.serialize_entries(chat_entries)
            }
            Group('game-%s' % game_id).send({'text': json.dumps(data)})
        else:
            print('Unknown message_type for %s' % game_id)
Beispiel #14
0
def game_add(request):
    if request.method == 'POST':
        Game.insert(
            title=request.POST['game_title'],
            genre_id=request.POST['genre_id'],
        )
        return redirect('games:index')
    else: # request.method == 'GET'
        context = {'genres': Genre.select_all()}
        return render(request, 'games/edit.html', context)
Beispiel #15
0
def game_edit(request, game_id):
    if request.method == 'POST':
        Game.update(game_id,
            title=request.POST['game_title'],
            genre_id=request.POST['genre_id'],
        )
        return redirect('games:index')
    else: # request.method == 'GET'
        context = {'game': Game.select(game_id), 'genres': Genre.select_all()}
        return render(request, 'games/edit.html', context)
Beispiel #16
0
    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()
Beispiel #17
0
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))
Beispiel #18
0
 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)
Beispiel #19
0
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,)))
Beispiel #20
0
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)
Beispiel #21
0
    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()
Beispiel #22
0
 def test_create_game_already_in_game(self):
     first_game = Game._create_game(self.alice)
     second_game = Game._create_game(self.alice)
     self.assertEquals(first_game.turn, None)
     self.assertEquals(first_game.player1, self.alice)
     self.assertEquals(first_game.player2, None)
     self.assertEquals(first_game.winner, None)
     self.assertEquals(Game.current_game(self.alice), second_game)
     self.assertEquals(second_game.turn, None)
     self.assertEquals(second_game.player1, self.alice)
     self.assertEquals(second_game.player2, None)
     self.assertEquals(second_game.winner, None)
Beispiel #23
0
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))
Beispiel #24
0
    def setUpTestData(self):
        self.reqfactory = RequestFactory()

        # dummy platform for testing POST
        self.test_plat = Platform(name='Test Platform', display_color='ffffff')
        self.test_plat.save()

        # dummy game for testing POST
        self.test_game = Game(name='Test Game',
                              platform=self.test_plat,
                              start_date='2015-03-21',
                              end_date='2015-04-02')
        self.test_game.save()
Beispiel #25
0
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)
Beispiel #26
0
    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")
Beispiel #27
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()
Beispiel #28
0
    def map(self, row):
        # Ensure that we have a game object to map to
        try:
            game = Game.objects.get(external_id=row['id'])
        except Game.DoesNotExist:
            game = Game()

        # Do the mapping...
        game.name = row['name']
        game.external_id = row['id']
        game.description = row['deck'] or ''
        game.release_date = row['original_release_date'][:10]

        return game
Beispiel #29
0
    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)')
Beispiel #30
0
    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
Beispiel #31
0
    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)
Beispiel #32
0
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
Beispiel #33
0
    def setUpTestData(cls):
        super().setUpTestData()
        cls.game = Game(name="BS F-Zero Grand Prix 2")
        cls.game.save()
        cls.ct1 = ChartType(name="CT1",
                            game=cls.game,
                            format_spec=[],
                            order_ascending=True)
        cls.ct1.save()
        cls.cg_mc4 = ChartGroup(name="Mute City IV",
                                order_in_parent=1,
                                game=cls.game)
        cls.cg_mc4.save()
        cls.cg_bb2 = ChartGroup(name="Big Blue II",
                                order_in_parent=2,
                                game=cls.game)
        cls.cg_bb2.save()

        cls.chart_mc4c = Chart(name="Course Time",
                               order_in_group=1,
                               chart_group=cls.cg_mc4,
                               chart_type=cls.ct1)
        cls.chart_mc4c.save()
        cls.chart_mc4l = Chart(name="Lap Time",
                               order_in_group=2,
                               chart_group=cls.cg_mc4,
                               chart_type=cls.ct1)
        cls.chart_mc4l.save()
        cls.chart_bb2c = Chart(name="Course Time",
                               order_in_group=1,
                               chart_group=cls.cg_bb2,
                               chart_type=cls.ct1)
        cls.chart_bb2c.save()
Beispiel #34
0
 def test_stalemate(self):
     """
     BBBABBB
     AAABAAA
     BBBABBB
     AAABAAA
     BBBABBB
     AAABAAA
     """
     game = Game._create_game(self.alice)
     game.join(self.bob)
     for _ in range(3):
         game.move(self.alice, 0)
         game.move(self.bob, 0)
         game.move(self.alice, 1)
         game.move(self.bob, 1)
         game.move(self.alice, 2)
         game.move(self.bob, 2)
         game.move(self.alice, 4)
         game.move(self.bob, 3)
         game.move(self.alice, 3)
         game.move(self.bob, 4)
         game.move(self.alice, 5)
         game.move(self.bob, 5)
         game.move(self.alice, 6)
         game.move(self.bob, 6)
     self.assertEqual(game.stalemate, True)
     self.assertEqual(game.winner, None)
Beispiel #35
0
    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()
Beispiel #36
0
def put_games():
    category1 = Category.query.get(1)
    category2 = Category.query.get(2)

    new_game = Game("FIFA19")
    new_game.categories.append(category1)
    new_game.categories.append(category2)
    db.session.add(new_game)

    new_game = Game("SubwayRunner")
    new_game.categories.append(category2)
    db.session.add(new_game)

    db.session.commit()

    return "Games Created!"
Beispiel #37
0
 def test_winning_move_diagonal_upper_right(self):
     """
     000A000
     000BA00
     000AAA0
     000BBBA
     000AAAB
     B00BBBA
     """
     game = Game._create_game(self.alice)
     game.join(self.bob)
     game.move(self.alice, 6)
     game.move(self.bob, 6)
     game.move(self.alice, 6)
     game.move(self.bob, 5)
     game.move(self.alice, 5)
     game.move(self.bob, 5)
     game.move(self.alice, 5)
     game.move(self.bob, 4)
     game.move(self.alice, 4)
     game.move(self.bob, 4)
     game.move(self.alice, 4)
     game.move(self.bob, 0)
     game.move(self.alice, 4)
     game.move(self.bob, 3)
     game.move(self.alice, 3)
     game.move(self.bob, 3)
     game.move(self.alice, 3)
     game.move(self.bob, 3)
     self.assertEqual(game.winner, None)
     game.move(self.alice, 3)
     self.assertEqual(game.winner, self.alice)
Beispiel #38
0
 def connect(self, message, **kwargs):
     player_id = sessions.get_player_id(message.http_session)
     message.channel_session['player_id'] = player_id
     print('Player %s connected to lobby' % player_id)
     player = Player.get_by_id(Player.get_model_id(player_id))
     data = Game.get_all_games_list()
     Group('lobby').send({'text': json.dumps(data)})
Beispiel #39
0
 def test_winning_move_diagonal_upper_left(self):
     """
     000A000
     00AB000
     0AAA000
     ABBB000
     BAAA000
     ABBB00B
     """
     game = Game._create_game(self.alice)
     game.join(self.bob)
     game.move(self.alice, 0)
     game.move(self.bob, 0)
     game.move(self.alice, 0)
     game.move(self.bob, 1)
     game.move(self.alice, 1)
     game.move(self.bob, 1)
     game.move(self.alice, 1)
     game.move(self.bob, 2)
     game.move(self.alice, 2)
     game.move(self.bob, 2)
     game.move(self.alice, 2)
     game.move(self.bob, 6)
     game.move(self.alice, 2)
     game.move(self.bob, 3)
     game.move(self.alice, 3)
     game.move(self.bob, 3)
     game.move(self.alice, 3)
     game.move(self.bob, 3)
     self.assertEqual(game.winner, None)
     game.move(self.alice, 3)
     self.assertEqual(game.winner, self.alice)
Beispiel #40
0
 def test_get_with_token(self):
     game = Game._create_game(self.alice)
     game.join(self.bob)
     column = Column.objects.get(game=game, index=0)
     slot = Slot.objects.get(column=column, index=Game.row_count - 1)
     slot.player = self.alice
     slot.save()
     self.assertEquals(game.get_board()[Game.row_count - 1][0], self.alice)
Beispiel #41
0
def get_info(request, id):
    user = UserProfile.objects.filter(id=id).first()
    if user is not None:  # user of given id exists
        user_stats = Game.get_user_stats(user)
        return Response(user_stats, status=200)
    else:  # user of given id doesn't exist
        return Response({'error': "User of given id doesn't exist."},
                        status=404)
Beispiel #42
0
 def test_move_taking_turns(self):
     game = Game._create_game(self.alice)
     game.join(self.bob)
     self.assertEquals(game.turn, self.alice)
     game.move(self.alice, 0)
     self.assertEquals(game.turn, self.bob)
     game.move(self.bob, 1)
     self.assertEquals(game.turn, self.alice)
Beispiel #43
0
 def setUp(self):
     self.duke = School(abbrev="DUKE", name="Duke")
     self.maryland = School(abbrev="MARY", name="Maryland")
     self.season = Season(year=2012, start_date="2011-11-01", 
                          end_date="2012-04-15")
     self.duke_2012 = Team(school=self.duke, season=self.season)
     self.maryland_2012 = Team(school=self.maryland, season=self.season)
     self.game = Game(team=self.duke_2012, opponent=self.maryland_2012)
Beispiel #44
0
    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)
Beispiel #45
0
 def test_create_game(self):
     game = Game._create_game(self.alice)
     self.assertEquals(game.turn, None)
     self.assertEquals(game.player1, self.alice)
     self.assertEquals(game.player2, None)
     self.assertEquals(game.winner, None)
     self.assertEquals(Column.objects.filter(game=game).count(), Game.column_count)
     for col in Column.objects.filter(game=game):
         self.assertEquals(Slot.objects.filter(column=col).count(), Game.row_count)
Beispiel #46
0
def move(request, column_number):
    game = Game.current_game(request.user)
    if game is None:
        return Response({"detail": "Not currently in a game."}, 400)
    try:
        game.move(request.user, column_number)
    except IllegalMove as exception:
        return Response({"detail": str(exception)}, 400)
    return Response(GameSerializer(game).data, 200)
    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()
Beispiel #48
0
    def post(self):
        args = self.reqparse.parse_args(strict=True)
        abort_if_no_auth(args['token'])

        new_game = Game(args['title'])
        db.session.add(new_game)
        db.session.commit()

        return {"result": new_game.id}, 201
Beispiel #49
0
 def test_move_full_column(self):
     game = Game._create_game(self.alice)
     game.join(self.bob)
     game.move(self.alice, 0)
     game.move(self.bob, 0)
     game.move(self.alice, 0)
     game.move(self.bob, 0)
     game.move(self.alice, 0)
     game.move(self.bob, 0)
     self.assertRaises(IllegalMove, game.move, self.alice, 0)
Beispiel #50
0
def game_message_list(request):
    """
    List all messages for the current game this user is in.
    """
    game = Game.current_game(request.user)
    if not game:
        return Response({"detail": "You are not in a game."}, 400)
    game_messages = GameMessage.objects.filter(game=game)
    serializer = GameMessageSerializer(game_messages, many=True)
    return Response(serializer.data)
Beispiel #51
0
 def test_winning_move_horizontal(self):
     game = Game._create_game(self.alice)
     game.join(self.bob)
     game.move(self.alice, 0)
     game.move(self.bob, 0)
     game.move(self.alice, 1)
     game.move(self.bob, 1)
     game.move(self.alice, 2)
     game.move(self.bob, 2)
     game.move(self.alice, 3)
     self.assertEqual(game.winner, self.alice)
    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')
Beispiel #53
0
 def test_leave_stalemate(self):
     self.client.credentials(HTTP_AUTHORIZATION='Token ' + str(self.alice.auth_token))
     self.client.post(reverse("games:start"))
     self.client.credentials(HTTP_AUTHORIZATION='Token ' + str(self.bob.auth_token))
     self.client.post(reverse("games:start"))
     game = Game.current_game(self.alice)
     game.stalemate = True
     game.save()
     response = self.client.post(reverse("games:forfeit"))
     self.assertEquals(response.status_code, 200)
     self.assertEquals(response.data["winner"], None)
    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)'
        )
Beispiel #55
0
 def test_move_stacking_tokens(self):
     game = Game._create_game(self.alice)
     game.join(self.bob)
     game.move(self.alice, 0)
     game.move(self.bob, 0)
     game.move(self.alice, 0)
     board = game.get_board()
     self.assertEquals(board[Game.row_count - 1][0], self.alice)
     self.assertEquals(board[4][0], self.bob)
     self.assertEquals(board[3][0], self.alice)
     self.assertEquals(game.winner, None)
     self.assertEquals(game.stalemate, False)
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)