def register(request): if request.method == "POST": form = RegistrationForm(request.POST) #?All of them seem to be connected with [email protected] why???? #*Maybe it's because no one was logged in at this point??? #!NOW I KNOW WHY. IT WAS BECAUSE I WAS LOGGED IN WITH [email protected] AND THE USER NEVER CHANGED. #*As proof, when I register when I am logged out, I runn into an attribute error at request.user.player.add #!SINCE THIS IS THE CASE I NEED TO CREATE THE PLAYER IN HOME PAGE if form.is_valid(): #*I think I can just redirect to login #!I have to differentiate between what is done at registration vs login n = form.cleaned_data['username'] p = Player(name=n, highscore=0) p.save() form.save() return redirect("/login") #*What I need to pass in the correct variables for register form = RegistrationForm() if request.user.is_authenticated: u = Player.objects.filter(name=request.user.get_username())[0] return render(request, "register/register.html", { "user": u, "logged_in": True, "form": form }) else: return render(request, "register/register.html", { "logged_in": False, "form": form, })
def register(request): username = request.POST.get('username','') password = request.POST.get('password','') repassword = request.POST.get('repassword','') email = request.POST.get('email','') nickname = request.POST.get('nickname','') if (username == ''): errors = '请输入您的密码' return render_to_response("index.html", {'message':'register','error2': errors}, context_instance=RequestContext(request)) try: p = User.objects.get(username = username) except User.DoesNotExist: if (password != repassword): errors = '两次输入密码不一致,请重新输入' return render_to_response("index.html", {'message':'register','error2': errors}, context_instance=RequestContext(request)) if (len(password) < 6): errors = '密码长度太短,请重新输入' return render_to_response("index.html", {'message':'register','error2': errors}, context_instance=RequestContext(request)) if nickname == '': errors = '请输入您的昵称' return render_to_response("index.html", {'message':'register','error2': errors}, context_instance=RequestContext(request)) if email == '': errors = '请输入您的邮箱' return render_to_response("index.html", {'message':'register','error2': errors}, context_instance=RequestContext(request)) user = User.objects.create_user(username = username,email = email,password = password) user.save() player = Player(user = user, nickname = nickname, signature = '', integration = 0, num_games = 0, is_forbidden = 0, status = 1) player.save() user = user = auth.authenticate(username = username, password = password) auth.login(request, user) return HttpResponseRedirect('/gamehall') else: errors = '用户名已被注册' return render_to_response("index.html", {'message':'register','error2': errors}, context_instance=RequestContext(request))
def test_all_players_in_game_give_the_same_value_to_the_table(self): """ Pre: Create 2 tables. 1 with players who give the same value. 2 with with 1 player who give less than other players Output: True if all players 'in game' give the same value to the pool. """ # Arrange player1 = Player(name=User(username='******'), state='start', round_money=10) player2 = Player(name=User(username='******'), state='start', round_money=10) player3 = Player(name=User(username='******'), state='start', round_money=10) player4 = Player(name=User(username='******'), state='start', round_money=9) table1 = Table(player1=player1, player2=player2, player3=player3, player4=player4) table2 = Table(player1=player1, player2=player2) # Act result1 = table1.all_players_in_game_give_the_same_value_to_the_table() result2 = table2.all_players_in_game_give_the_same_value_to_the_table() # Assertion self.assertIsInstance(result1, bool) self.assertFalse(result1) self.assertIsInstance(result2, bool) self.assertTrue(result2)
def test_init(self): me = Player(123, "", 0, False, []) others = [Player(222, "", 0, False, []), Player(111, "", 0, False, [])] game = Game(0, 0, me.id, [me] + others, None, None, []) self.assertEqual(me, game.me) self.assertEqual(others, game.enemies)
def game(request): """ receive a player name in a POST to create a new game return the newly created game object """ if request.method == 'POST': #create a new game game = Game() code = game.new_game() playername = request.data['player_name'] player = Player(name=playername) player.join_game(code) game_serializer = GameSerializer(game) player_serializer = PlayerSerializer(player) #return a json object containing both the game and the player's object return Response({ 'game': game_serializer.data, 'player': player_serializer.data }) elif request.method == 'GET': #retrieve info for an existing game if 'access_code' in request.query_params: game = Game.objects.get( access_code=request.query_params['access_code']) serializer = GameSerializer(game) return Response(serializer.data) else: return Response()
def test_all_players_in_game_make_decision(self): """ Pre: Create table with 2 players with 'start' and 'out' state and 2 players with 'raise' and 'check' state -> what means they made decisions. Output: True if all players 'in game' make a decision """ # Arrange player1 = Player(name=User(username='******'), state='start') player2 = Player(name=User(username='******'), state='out') player3 = Player(name=User(username='******'), state='raise') player4 = Player(name=User(username='******'), state='check') table1 = Table(player1=player1, player2=player2, player3=player3, player4=player4) table2 = Table(player3=player3, player4=player4) # Act result1 = table1.all_players_in_game_make_decision() result2 = table2.all_players_in_game_make_decision() # Assertion self.assertIsInstance(result1, bool) self.assertFalse(result1) self.assertIsInstance(result2, bool) self.assertTrue(result2)
def test_init_unknown_player_id(self): unknown_id = 42 players = [ Player(222, "", 0, False, []), Player(111, "", 0, False, []) ] self.assertRaises(UnknownPlayerIdException, Game, 0, 0, unknown_id, players, None, None, [])
def create_players(self, users): """Create a list of Player instances from a list of User instances for testing.""" players = [] for i, user in enumerate(users): player = Player(user=user, nickname=f'Swindle_{i}') player.save() players.append(player) return players
def create_test_game(): usernames = ['arthur', 'brian', 'blacknight', 'caesar', 'dickens', 'eric', 'francesc', 'gumby', 'herbert', 'king', 'lancelot', 'patsy', 'itsman','loony', 'nazifish', 'pepperpot'] for name in usernames: user = User.objects.create_user(username=name) Player.create_player(user=user).save() territories = ['Aglax', 'Brierhiel', 'Cesta', 'Drucea', 'Efea', 'Froynia', 'Gleol', 'Ova', 'Loflurg', 'Prainia', 'Qogrela', 'Smea', 'Uglia'] for territory_name in territories: Territory.objects.create(name=territory_name, land_area=10)
def _create_game(nb_player=4, game_name='test'): game = Game(name=game_name) game.save() user_names = ['Clément'] + ["bot_"+str(i) for i in range(nb_player-1)] players = [] for user_name in user_names: user = User(username=user_name) user.save() player = Player(user=user, game=game) player.save() players.append(player) return game, players
def populate_players(self, faker: Faker): teams = Team.objects.all() for team in teams: for i in range(10): player = Player(id=str(uuid.uuid4()), first_name=faker.first_name(), last_name=faker.last_name(), date_of_birth=faker.date(), country=faker.country(), height=round(decimal.Decimal(random.randrange(20000)) / 100, 2), weight=round(decimal.Decimal(random.randrange(20000)) / 100, 2), team=team) player.save() msg.good("Players data successfully populated")
def test_next_game_state_2_players(self): """Change current game state to the next from the game path""" # Arrange us1 = User(username='******') us1.save() us2 = User(username='******') us2.save() player1 = Player(name=us1, state='check') player1.save() player2 = Player(name=us2, state='check') player2.save() table = Table(player1=player1, player2=player2) # Act & Assertion self.assertEqual(table.game_state, 'ready') table.next_game_state() self.assertEqual(table.game_state, 'small_blind') table.next_game_state() self.assertEqual(table.game_state, 'give_2') table.next_game_state() self.assertEqual(table.game_state, 'give_3') table.next_game_state() self.assertEqual(table.game_state, 'give_1') table.next_game_state() self.assertEqual(table.game_state, 'give_1_again') table.next_game_state() self.assertEqual(table.game_state, 'winner') table.next_game_state() # In this plase should be 'again' but self.start_game_again() call # this table.next_game_state, so we jump to begin - 'ready' state self.assertEqual(table.game_state, 'ready')
def __add_player(self, user_id, game_id, order): player = Player( user_id=user_id, game_id=game_id, balance=settings.DEFAULT_GAME_SETTINGS['start_money'], jailed=0, position=0, active=True, jail_free_card=False, move=0, order=order, ) player.save() Proxy().load() return player
def test_add_player(self): """Add Player to free space in table""" # Arrange player1 = Player(name=User(username='******')) player2 = Player(name=User(username='******')) player3 = Player(name=User(username='******')) player4 = Player(name=User(username='******')) table = Table(player1=player1, player2=player2, player4=player4) # Act table.add_player(player3) # Assertion self.assertEqual(table.player3, player3)
def create_game(request): if Game.objects.filter(status=Game.UNINITIALIZED).count() > 100: return HttpResponse('There is too many game at once', status=500) elif Game.objects.exclude(id__in=Player.objects.all().values( 'game').distinct()).count() > 20: return HttpResponse('Please, join empty room', status=500) elif Game.objects.filter(id__in=Player.objects.filter(user=request.user).values('game')).\ filter(status=Game.UNINITIALIZED).count() > 5: return HttpResponse( 'You are in too much room at once, please leave one', status=500) game = Game(name=request.POST['name']) game.save() player = Player(user=request.user, game=game) player.save() return redirect('game_page', game_id=game.id)
def test_update_game_calls_send_actions(self): cells = [ Cell(0, 5, 10, Vec2(0, 0), Vec2(1, 1)), Cell(1, 5, 10, Vec2(0, 0), Vec2(1, 1)), Cell(2, 5, 10, Vec2(0, 0), Vec2(1, 1)) ] player = Player(0, "", 10, True, cells) game = Game(0, 0, 0, [player], Resources([], [], []), Map(0, 0), []) cells[0].target = Vec2(2, 2) cells[0].burst() cells[1].split() cells[1].trade(3) class MockApi: def send_actions(self, game_id, actions): self.actions = actions api = MockApi() update_game(api, game, lambda x: None) self.assertEqual(len(api.actions), 2) self.assertTrue(api.actions[0].target.almost_equals(Vec2(2, 2))) self.assertTrue(api.actions[0].burst) self.assertTrue(api.actions[1].split) self.assertEqual(3, api.actions[1].trade)
def new_game(request, session_id): form = NewGame() # Форма по созданию игры if request.method == 'POST': form = NewGame(request.POST) if form.is_valid() and form['number'].value(): if not Player.objects.filter(player_id=session_id): Player(player_id=session_id).save() Game(game_id=session_id, number=form['number'].value()).save() PlayerGameInfo(player_id=Player.objects.filter( player_id=session_id).values('id')[0]['id'], game_id=Game.objects.order_by('-id').filter( game_id=session_id).values('id')[0]['id'], is_owner=True).save() return redirect('game_created', game_id=Game.objects.order_by('-id').filter( game_id=session_id).values('id')[0]['id']) return render( request, 'new_game.html', { 'form': form, }, )
def get_success_url(self): if 'email_next' in self.request.session: next_url = self.request.session['email_next'] del self.request.session['email_next'] return next_url return get_puzzle_url(Player.get_player(self.request).last_puzzle)
def test_give_to_pool(self): """Give money from player.money to table.pool""" # Arrange us1 = User(username='******') us1.save() player1 = Player(name=us1, money=50) player1.save() table = Table(player1=player1, pool=0) # Act table.give_to_pool(player1, 10) # Assertion self.assertEqual(table.pool, 10) self.assertEqual(player1.money, 40)
def test_print_pretty_cards_cards(self): """ Input: String with cards separated by commas Output: Pretty cards as a string """ # Arrange player = Player('player') player.cards = str(Card.new('As')) + ',' + str(Card.new('9h')) # Act player_result = player.print_pretty_cards_cards() cards_result = 'A♠9♥' # Assertion self.assertEqual(player_result, cards_result) self.assertIsInstance(player_result, str)
def join(request): """ receive a player name and access code in a POST to join an existing game """ if request.method == 'POST': playername = request.data['player_name'] player = Player(name=playername) accesscode = request.data['access_code'] player.join_game(accesscode) game = Game.objects.get(access_code=accesscode) game_serializer = GameSerializer(game) player_serializer = PlayerSerializer(player) return Response({ 'game': game_serializer.data, 'player': player_serializer.data })
def create_player(user, game, players): """Create and return player. only return player if he is already created :param user: user who will be related to player :param game: game what will be related to player :return: Player object """ players = players.order_by('in_game_order') player = players.filter(user=user).first() if player is None: player = Player(user=user, name=user.username, game=game, chips=GameSerializer(game).data['starting_chips'], is_in_game=True) else: player.is_in_game = True # set player in_game_order if len(players) < 1: player.in_game_order = 1 else: player.in_game_order = players.reverse()[0].in_game_order + 1 # update number of connected players game.players_connected = len(players) game.save() player.save() return player.id
def find_player(request): if request.method == 'GET': player_name = request.GET.get('player-name') try: player = Player.objects.get(name=player_name) except ObjectDoesNotExist: player = Player(name=player_name, color='R').save() print("Player didn't exist, was created") return JsonResponse(player)
def get_players_by_ids(request): ids = request.GET.get('ids') ids = [int(id) for id in ids.split(',')] if len(ids) > 20: return HttpResponseBadRequest('Got more than 20 ids') players = Player.get_players_by_ids(ids) result = [player.to_dict() for player in players] return JsonResponse(result, safe=False)
def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success( request, f'Your account has been created! You are now able to log in') user = User.objects.get(username=username) #user = User.objects.get(username = request.POST['user']) #user.player_set.create(name = user.username) # set_create calismiyor player = Player(name=username) player.user = user player.save() return redirect('login') else: #Create empty form form = UserRegisterForm() return render(request, 'users/register.html', {'form': form})
def populate(): p = Player() u = Unit() c = City() for line in open("config_populate.txt"): split = line.split(" ") instruction = split[0] if "#" in instruction: continue if len(split) == 1: continue name = ' '.join(split[1:len(split)]).rstrip("\n") print(name) if instruction == "P": p = add_player(name) elif instruction == 'C': c = add_city(name, p) elif instruction == 'U': u = add_unit(name, p, c) p.add_unit(u)
def test_all_players_with_start_state(self): """ Pre: Create table with 2 players with 'start' state and 1 player with 'out' state Output: List with players who have 'start' status """ # Arrange player1 = Player(name=User(username='******'), state='start') player2 = Player(name=User(username='******'), state='out') player3 = Player(name=User(username='******'), state='start') table = Table(player1=player1, player2=player2, player3=player3) # Act result = table.all_players_with_start_state() to_compare = [player1, player3] # Assertion self.assertIsInstance(result, list) self.assertEqual(result, to_compare)
def add_player(self, nick: str, id: str) -> Player: existing_player: Player = self.get_player_by_nick(nick) if existing_player: logging.info( f"Player '{existing_player.nick}' reconnected with id '{id}'") existing_player.reconnect(id) return existing_player new_player = Player(nick, id) self.players.append(new_player) self.waiting_room.join(new_player) return new_player
def new_dispatch(self, request, *args, **kwargs): response = orig_dispatch(self, request, *args, **kwargs) player = Player.get_player(request) # Only allow proceeding to the current puzzle if the user provided # their email address if not player.email: request.session['email_next'] = request.path return redirect(reverse('email_form')) return response
def create_game(game_data): game = Game.objects.create(max_score=game_data['max_score']) for score in game_data['scores']: team_players_ids = [] for name in score['players']: team_players_ids.append(Player.get_by_name(name).id) team = Team.get_or_create_team(team_players_ids) game.teams.add(team) ScoreTeam.objects.create(team=team, game=game, score=score['score']) game.save() return game
def test_my_hand(self): """ Input: Cards from my profile as a string Output: Descripting poker hand as a string """ # Player Arrange table_cards = str(Card.new('3s')) + ',' \ + str(Card.new('2s')) + ',' \ + str(Card.new('As')) + ',' \ + str(Card.new('Ks')) + ',' \ + str(Card.new('Qs')) player_cards = str(Card.new('Js')) + ',' + str(Card.new('Ts')) table = Table(cards_on_table=table_cards) player = Player(table=table, cards=player_cards) # Player Act player_result = player.my_hand() # Treys Arrange board = [ Card.new('3s'), Card.new('2s'), Card.new('As'), Card.new('Ks'), Card.new('Qs') ] gamer = [Card.new('Js'), Card.new('Ts')] # Treys Act evaluator = Evaluator() score = evaluator.evaluate(board, gamer) classs = evaluator.get_rank_class(score) treys_result = evaluator.class_to_string(classs) # Assertion self.assertEqual(player_result, treys_result) self.assertIsInstance(player_result, str)
def index(request): player = get_player(request) if player is not None: # Delete old player and game objects if player.game and player == player.game.master: player.game.delete() player.delete() del request.session['player_pk'] if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): name = form.cleaned_data['player_name'] create_game = form.cleaned_data['create_game'] checkin = CheckIn() checkin.save() player = Player(name=name, rand_id=Player.generate_rand_id(), checkin=checkin) if create_game: checkin = CheckIn() checkin.save() bot = Bot() bot.save() game = Game(checkin=checkin, bot=bot) game.save() player.game = game player.index = 1 player.save() if create_game: game.master = player game.players.add(player) game.save() request.session['player_pk'] = player.pk request.session['player_rand_id'] = player.rand_id request.session['player_name'] = name if create_game: return redirect('/create-game') else: return redirect('/join-game') else: form = LoginForm(initial={'player_name': request.session.get('player_name', '')}) return render(request, 'game/index.html', {'form': form})
from game.models import Player import cjson with open('/game/static/game/json/players.json', 'r') as f: for line in f: data = cjson.decode(line) p = Player(name=data['PLAYER_NAME'], gp=data['GP'], min=data['MIN'], tov=data['TOV'], reb=data['REB'],\ fg3a=data['FG3A'], efg=data['EFG_PCT'], ast=data['AST'], ast_tov=data['AST_TOV'], fg3m=data['FG3M'],\ oreb=data['OREB'], fgm=data['FGM'], pf=data['PF'], pts=data['PTS'], fga=data['FGA'], ts=data['TS_PCT'],\ stl=data['STL'], fta=data['FTA'], blk=data['BLK'], dreb=data['DREB'], ftm=data['FTM'], stl_tov=data['STL_TOV'],\ ft=data['FT_PCT'], fg=data['FG_PCT'], fg3=data['FG3_PCT']) p.save()