def _check_game_state(game_id): """ Checks whether there's a victory condition, losing condition, or no more available moves """ print("\n\nInside check game state, game_id: " + game_id) moves = Move.query(Move.game_id == game_id).fetch() available_moves = Move.query(Move.available == True, Move.game_id == game_id).fetch() if len(moves) == 0: print("\n\n game_id not found {0} \n\n".format(game_id)) return "game_id_not_found" winner_id = GuessANumberApi._check_winning_condition(game_id) if winner_id != False: print("\n\n############### Game won by:" + winner_id + " ###############\n\n") return winner_id if len(available_moves) == 0: print( "\n\n Game Ended, No more moves left {0} \n\n".format(game_id)) return "no_more_moves" print("\n\nNo winners yet for game: {0} \n\n".format(game_id)) return "no_winners_yet"
def resetGameState(self, request): # Remove move ownership for all users # Resets move availablities to True game_id = request.game_id # for the moment, resets every move for provided game_id moves = Move.query().fetch() moves_deleted = Move.query(Move.game_id == game_id).fetch() game = Game.query(Game.game_id == game_id).get() if game == None: return StringMessage( message="No Game found for ID: {0} ".format(game_id)) print("game id is {0} {1}".format(game_id, moves[0].game_id)) # Deleting Game game.key.delete() # Deleting Moves for move in moves_deleted: print("Deleting moves, {0}".format(move)) move.key.delete() return StringMessage( message="Game Reset Complete, deleted {0} moves for Game: {1} ". format(len(moves_deleted), game_id))
def resetGameState(self, request): # Remove move ownership for all users # Resets move availablities to True game_id = request.game_id # for the moment, resets every move for provided game_id moves = Move.query().fetch() moves_deleted = Move.query(Move.game_id == game_id).fetch() game = Game.query(Game.game_id == game_id).get() if game == None: return StringMessage(message = "No Game found for ID: {0} ".format(game_id)) print("game id is {0} {1}".format(game_id, moves[0].game_id )) # Deleting Game game.key.delete() # Deleting Moves for move in moves_deleted: print("Deleting moves, {0}".format(move)) move.key.delete() return StringMessage(message = "Game Reset Complete, deleted {0} moves for Game: {1} ".format(len(moves_deleted), game_id))
def make_move(self, request): """Makes a move. Returns a game state with message""" game = utils.get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_over: return game.to_form('Game already over!') if not utils.valid_letter_guess(request.letter_guess, game.guessed_letters): return game.to_form('Sorry, %s is an invalid guess!' % request.letter_guess) game.attempts_remaining -= 1 game.guessed_letters = game.guessed_letters + request.letter_guess move = Move(game=game.key, move=request.letter_guess, move_index=game.attempts_allowed - game.attempts_remaining) move.put() if utils.guessed_letters_are_correct(game.guessed_letters, game.target): game.end_game(True) return game.to_form('You win!') if request.letter_guess in game.target: msg = 'That letter is in the word! Remaining %s' % utils.show_hyphenated_progress(game.guessed_letters, game.target) else: msg = 'Oops! That letter is not in the word! Remaining %s' % utils.show_hyphenated_progress(game.guessed_letters, game.target) if game.attempts_remaining < 1: game.end_game(False) return game.to_form(msg + ' Game over!') else: game.put() return game.to_form(msg)
def _check_game_state(game_id): """ Checks whether there's a victory condition, losing condition, or no more available moves """ print("\n\nInside check game state, game_id: " + game_id) moves = Move.query(Move.game_id == game_id).fetch() available_moves = Move.query(Move.available == True, Move.game_id == game_id).fetch() if len(moves) == 0: print("\n\n game_id not found {0} \n\n".format(game_id)) return "game_id_not_found" winner_id = GuessANumberApi._check_winning_condition(game_id) if winner_id != False: print("\n\n############### Game won by:" + winner_id + " ###############\n\n") return winner_id if len(available_moves) == 0: print("\n\n Game Ended, No more moves left {0} \n\n".format(game_id)) return "no_more_moves" print("\n\nNo winners yet for game: {0} \n\n".format(game_id)) return "no_winners_yet"
def guess_answer(self, request): """Guesses the answer. Returns a game state with message""" game = utils.get_by_urlsafe(request.urlsafe_game_key, Game) if game.game_over: return game.to_form('Game already over!') if not utils.valid_word_guess(request.word_guess): return game.to_form('Sorry, %s is an invalid guess!' % request.guess) game.attempts_remaining -= 1 move = Move(game=game.key, move=request.word_guess, move_index=game.attempts_allowed - game.attempts_remaining) move.put() if request.word_guess == game.target: game.end_game(True) return game.to_form('You win!') else: msg = 'Oops! That is not the word! Remaining %s' % utils.show_hyphenated_progress(game.guessed_letters, game.target) if game.attempts_remaining < 1: game.end_game(False) return game.to_form(msg + ' Game over!') else: game.put() return game.to_form(msg)
def linkCooldown(movesGraph, difficulty = 1) -> None: """Links cooldown moves in.""" movesGraph['twistedHeadToKnee'] = Move.twoSides("Twisted Head To Knee", "Take your %(same)s hand and grab the inside of your %(same)s foot.\ Lean sideways over your %(same)s leg.", 30, movesGraph['seatedMeditation'], movesGraph['staff'], movesGraph['lieOnBack']) movesGraph['preztel'] = Move.twoSides("Preztel", "Take your %(same)s foot and put it in front of your %(other)s knee. Pull your \ %(other)s knee towards you", 30, movesGraph['lieOnBack']) movesGraph['four'] = Move.twoSides("Four", "Four pose, %(same)s side", 30, movesGraph['supportedShoulderStand']) for i in movesGraph['four']: i.addLateMove(movesGraph['lieOnBack']) Move.moveReverse(movesGraph['four'], movesGraph['preztel'], movesGraph['twistedHeadToKnee']) movesGraph['child'].addMove(*movesGraph['childsPoseSideStretch']) movesGraph['downwardDog'].addMove(movesGraph['table'], movesGraph['child'], movesGraph['lieOnBack']) movesGraph['vinyasa'].addMove(movesGraph['child'], movesGraph['lieOnBack'], movesGraph['staff'], movesGraph['upwardDog']) movesGraph['staff'].addMove(movesGraph['hero']) movesGraph['seatedMeditation'].addMove(*movesGraph['cowFace']) movesGraph['seatedMeditation'].addMove(*movesGraph['seatedTwist']) movesGraph['seatedMeditation'].addMove(*movesGraph['twistedHeadToKnee']) movesGraph['mountain'].addMove(movesGraph['backBend'], *movesGraph['standingSideStretch']) movesGraph['mountain'].addMove(*movesGraph['standingTwist']) movesGraph['backBend'].removeMove(*movesGraph['standingSideStretch']) movesGraph['crow'].addMove(movesGraph['child']) movesGraph['lieOnBack'].addMove(*movesGraph['preztel']) movesGraph['supportedShoulderStand'].addMove(*movesGraph['four']) for i in movesGraph['birdOfParadise']: i.addMove(movesGraph['mountain']) for i in movesGraph['sidePlank']: i.addMove(movesGraph['lieOnFront']) for i in movesGraph['sidePlankLegUp']: i.addMove(movesGraph['lieOnFront']) for i in movesGraph['standingLegLift1']: i.addMove(movesGraph['mountain']) if difficulty >= 1: movesGraph['wheel'].promoteLate()
def mouse_move(self, request, *args, **kwargs): gameId=request.session['gameId'] statsDict = {} pos=int(request.POST['click']) try: games = Game.objects.filter(id=gameId) g=games[0] if isValidMouseMove(self, g , pos): move= Move(game=g,origin=g.mouse,target=pos) move.save() statsDict['message'] = "Movimiento realizado" statsDict['value'] =move.id statsDict['result'] = True g.mouse=pos g.catTurn=1 g.save() else: statsDict['message'] = "Movimiento no realizado" statsDict['value'] = -1 statsDict['result'] = True except Exception as e: #en caso de error reportalo statsDict['message'] = e.message statsDict['value'] = -1 statsDict['result'] = False return self.create_response(request, statsDict)
def test_move(self): # add game and check it game = Game.create(white='123', black='456', state='Ke1,ke8') self.assertTrue( abs((game.date_created - game.date_state).total_seconds()) < 1) self.assertEqual(game.next_color, WHITE) self.assertEqual(Game.select().count(), 1) self.assertEqual(Move.select().count(), 0) self.assertFalse(game.ended) # wait a second time.sleep(1) # add move and check game.add_move('K', 'e1-e2', 'Ke2,ke8') self.assertEqual(Move.select().count(), 1) # reload game game = Game.get(pk=game.pk) self.assertEqual(game.next_color, BLACK) self.assertEqual(game.state, 'Ke2,ke8') self.assertTrue( (game.date_state - game.date_created).total_seconds() > 1) self.assertAlmostEqual(game.moves.get().time_move, 1, places=1) self.assertFalse(game.ended) # add move with ending game game.add_move('k', 'e8-e7', 'Ke2,ke7', True) self.assertTrue(game.ended) self.assertEqual(game.winner, BLACK)
def make_move(request, game_id): if not request.user.is_authenticated(): return HttpResponse('Unauthorized', status=401) if request.method == 'POST': # make sure authed & joined try: json_data = json.loads(request.body) #so check that the pile is valid game = Game.objects.get(id = game_id) usernames = [player.username for player in list(game.players.all())] if (request.user.username not in usernames): return HttpResponseServerError("Error, you havent joined this game") #check that it's this users turn to go moves = game.move_set.all().order_by('date') if (len(moves) > 0 and moves.last().user.username == request.user.username): #then this user went last, error pls return HttpResponseServerError("Error, wait for the other play to move") #expecting a "move" # { # pile : 0 # taken : 5 # } # By default, this Manager is named FOO_set, where FOO is the source model name, lowercased. piles = game.pile_set.all() # Returns all pile objects related to game. pile_pos = json_data['pile'] if not (pile_pos >=0 and pile_pos < len(piles)): #invalid pile id return HttpResponseServerError("invalid pile id") pile_pull = game.pile_set.get(position=pile_pos) taken = int(json_data['taken']) if (taken > pile_pull.amount): return HttpResponseServerError("invalid, trying to take more than %s available" % (str(pile_pull.amount))) if (taken <= 0): return HttpResponseServerError("invalid, trying to take 0 or less") #we should be good #update the pile pile_pull.amount = pile_pull.amount - taken pile_pull.save() #create a move new_move = Move( #start at 0th move order = len(moves), game = game, pile = pile_pull, taken = taken, user = request.user ) new_move.save() return get_json(Game.objects.get(id = game_id)) except Game.DoesNotExist: return HttpResponseNotFound("Game doesnt exist") except Exception, e: return HttpResponseServerError("Malformed data!")
def pos_post(self, obj): move = Move( value=obj.total, type=1, obs=f"GERADO DA COMPRA {obj.id}", user=obj.user, ) move.save()
def defineStretches(movesGraph, difficulty = 1) -> None: """Add in a few stretches?""" movesGraph['upwardDogStretches'] = Move.twoSides('Upward Dog Stretch', 'Push your %(same)s shoulder forward', 10, movesGraph['upwardDog']) Move.moveReverse(movesGraph['upwardDogStretches']) movesGraph['halfSplits'] = Move.twoSides('Half Splits', 'Half Splits', 10) #add better description? movesGraph['splits'] = Move.twoSides('Splits', 'Splits, %(same)s foot forward', 10) if difficulty < 1: movesGraph['upwardDog'].addMove(*movesGraph['upwardDogStretches'])
def makeMove(self, request): """ Asigns specific move to a user for a specific game_id, as long as its available """ x = request.x y = request.y game_id = request.game_id user_id = request.user_id game = Game.query(Game.game_id == game_id).get() queried_move = Move.query(Move.x == x, Move.y == y, Move.game_id == game_id).fetch(1) if game == None : print("\n\nInvalid Move, Wrong Game ID\n\n") return StringMessage(message = "Invalid Move, Wrong Game ID" ) winner_id = GuessANumberApi._check_winning_condition(game_id) if winner_id != False: print("\n\n Game Won By {0} \n\n".format(winner_id)) return StringMessage(message = "\n\n Game Won By {0} \n\n".format(winner_id)) available_moves = Move.query(Move.available == True, Move.game_id == game_id).fetch() if len(available_moves) == 0: print("\n\n Game Ended, No more moves left {0} \n\n".format(game_id)) return "no_more_moves" if user_id == None or user_id not in [game.player1, game.player2]: print("\n\nInvalid move parameters\n\n") return StringMessage(message = "Invalid Move, Wrong User ID" ) if len(queried_move) == 0: print("\n\nInvalid move parameters\n\n") return StringMessage(message = "Invalid move parameters, Wrong Game ID or Move out of range" ) if user_id == game.last_play_user_id: print("\n\n This Player already moved\n\n") return StringMessage(message = "Invalid move, This Player already moved" ) move = queried_move[0] if move.available != True: print("\n\nMove already done by: {0} \n\n".format(move.user_id)) return StringMessage(message = "Move {0} has already been made by User with ID: : {1}" .format(move.description, move.user_id) ) move.user_id = user_id move.available = False move.put() game.last_play_user_id = user_id game.put() GuessANumberApi._show_game_picture(game_id) GuessANumberApi._check_game_state(game_id) return StringMessage(message = "Move {0} assign to {1} for game_id: {2}, x:{3} and y:{4}".format(move.description, user_id, game_id, x, y) )
def test_save_move_normal(self): ''' Tests a simple move to valid location. Expected: no exceptions. ''' game = Game.objects.get(id=1) player1 = Player.objects.get(id=1) move = Move(game=game, player=player1, position_x=1, position_y=1) move.save() from_db = Move.objects.get(id=1) self.assertEqual(from_db.position_x, 1)
def _show_game_picture(game_id): """ Print visual representation of game state """ moves = Move.query(Move.game_id == game_id).order(Move.x, Move.y).fetch() if len(moves) == 0: print("\n\nCant print game state, Invalid game_id {0}\n\n".format( game_id)) return StringMessage( message="Invalid move parameters. no game found") player1, player2 = GuessANumberApi._get_players_in_game(game_id) print("Current Players for Game ID {0}: {1}, {2}".format( game_id, player1, player2)) m_00 = Move.query(Move.x == 0, Move.y == 0, Move.game_id == game_id).fetch(1)[0] m_01 = Move.query(Move.x == 0, Move.y == 1, Move.game_id == game_id).fetch(1)[0] m_02 = Move.query(Move.x == 0, Move.y == 2, Move.game_id == game_id).fetch(1)[0] m_10 = Move.query(Move.x == 1, Move.y == 0, Move.game_id == game_id).fetch(1)[0] m_11 = Move.query(Move.x == 1, Move.y == 1, Move.game_id == game_id).fetch(1)[0] m_12 = Move.query(Move.x == 1, Move.y == 2, Move.game_id == game_id).fetch(1)[0] m_20 = Move.query(Move.x == 2, Move.y == 0, Move.game_id == game_id).fetch(1)[0] m_21 = Move.query(Move.x == 2, Move.y == 1, Move.game_id == game_id).fetch(1)[0] m_22 = Move.query(Move.x == 2, Move.y == 2, Move.game_id == game_id).fetch(1)[0] m_00 = m_00.user_id or m_00.description m_01 = m_01.user_id or m_01.description m_02 = m_02.user_id or m_02.description m_10 = m_10.user_id or m_10.description m_11 = m_11.user_id or m_11.description m_12 = m_12.user_id or m_12.description m_20 = m_20.user_id or m_20.description m_21 = m_21.user_id or m_21.description m_22 = m_22.user_id or m_22.description print("\n\n\n") print("TIC TAC TOE GAME") print("\n") print(" {0} | {1} | {2} ".format(m_00, m_01, m_02)) print("-----------------------------") print(" {0} | {1} | {2} ".format(m_10, m_11, m_12)) print("-----------------------------") print(" {0} | {1} | {2} ".format(m_20, m_21, m_22)) print("\n\n\n")
def test_simple_game(self): game = Game.objects.get() #create 3 piles - 2,3,4 for i, p in enumerate([2,3,4]): new_pile = Pile( position = i, amount = p, game = game ) new_pile.save() self.assertEqual(len(game.pile_set.all()), 3) #create a couple users user_one = User.objects.create_user("one", password="******") user_one.save() user_two = User.objects.create_user("two", password="******") user_two.save() #add them to the game game.players.add(user_one) game.players.add(user_two) game.save() #reget the game game = Game.objects.get() self.assertEqual(len(game.players.all()), 2) #test a basic set of three moves, each player taking the max on each for i, (user, take) in enumerate([(user_one, 2), (user_two, 3), (user_one, 4)]): pile = game.pile_set.get(position = i) self.assertEqual(pile.amount, take) pile.amount = 0 pile.save() #create a corresponding move new_move = Move( #start at 0th move order = i, game = game, pile = pile, taken = take, user = user ) new_move.save() #check it went user 1, user 2, user 1 moves = game.move_set.all().order_by('date') self.assertEqual(len(moves), 3) # print moves[0] # print moves[1] # print moves[2] self.assertEqual(moves[0].user, user_one) self.assertEqual(moves[1].user, user_two) self.assertEqual(moves[2].user, user_one)
def test_move(self): with self.app.test_request_context(): cases = [ (Move(figure='N', move='b2-c3'), 'Nb2-c3'), (Move(figure='k', move='e8-e7'), 'Ke8-e7'), (Move(figure='K', move='0-0-0'), '0-0-0'), (Move(figure='P', move='e2-e4'), 'e2-e4'), ] for move, expect in cases: self.assertEqual( serializers.MoveSerializer(move).calc(), expect)
def _show_game_picture(game_id): """ Print visual representation of game state """ moves = Move.query(Move.game_id == game_id).order(Move.x, Move.y).fetch() if len(moves) == 0: print("\n\nCant print game state, Invalid game_id {0}\n\n".format(game_id)) return StringMessage(message = "Invalid move parameters. no game found" ) player1,player2 = GuessANumberApi._get_players_in_game(game_id) print("Current Players for Game ID {0}: {1}, {2}".format(game_id, player1, player2) ) m_00 = Move.query(Move.x == 0, Move.y == 0, Move.game_id == game_id).fetch(1)[0] m_01 = Move.query(Move.x == 0, Move.y == 1, Move.game_id == game_id).fetch(1)[0] m_02 = Move.query(Move.x == 0, Move.y == 2, Move.game_id == game_id).fetch(1)[0] m_10 = Move.query(Move.x == 1, Move.y == 0, Move.game_id == game_id).fetch(1)[0] m_11 = Move.query(Move.x == 1, Move.y == 1, Move.game_id == game_id).fetch(1)[0] m_12 = Move.query(Move.x == 1, Move.y == 2, Move.game_id == game_id).fetch(1)[0] m_20 = Move.query(Move.x == 2, Move.y == 0, Move.game_id == game_id).fetch(1)[0] m_21 = Move.query(Move.x == 2, Move.y == 1, Move.game_id == game_id).fetch(1)[0] m_22 = Move.query(Move.x == 2, Move.y == 2, Move.game_id == game_id).fetch(1)[0] m_00 = m_00.user_id or m_00.description m_01 = m_01.user_id or m_01.description m_02 = m_02.user_id or m_02.description m_10 = m_10.user_id or m_10.description m_11 = m_11.user_id or m_11.description m_12 = m_12.user_id or m_12.description m_20 = m_20.user_id or m_20.description m_21 = m_21.user_id or m_21.description m_22 = m_22.user_id or m_22.description print("\n\n\n") print("TIC TAC TOE GAME") print("\n") print(" {0} | {1} | {2} ".format(m_00, m_01, m_02)) print("-----------------------------") print(" {0} | {1} | {2} ".format(m_10, m_11, m_12)) print("-----------------------------") print(" {0} | {1} | {2} ".format(m_20, m_21, m_22)) print("\n\n\n")
def make_play(self, request): """Makes a play. Returns a game state with message.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found!') if game.game_over: return game.to_form('Game already over!') # Get plays of AI and user, making sure they're valid. ai_play = random.choice(VALID_PLAYS) user_play = request.play.lower() if not user_play in VALID_PLAYS: msg = 'Uh-oh. You need to specify either Rock, Paper, or Scissors.' game.put() return game.to_form(msg) if user_play == ai_play: msg = 'Looks like we both picked {}. Play again!'.format( user_play.title()) game.moves.append(Move(play=user_play, ai_play=ai_play, result=msg)) game.put() return game.to_form(msg) # Attach plays to game attributes game.ai_play = ai_play game.play = user_play # Set other applicable game attributes, including outgoing message for form. if user_play == 'scissors' and ai_play == 'paper' or\ user_play == 'rock' and ai_play == 'scissors' or\ user_play == 'paper' and ai_play == 'rock': msg = """Congratulations, your {} beats my {}.\ You win!""".format(user_play.title(), ai_play.title()) game.message = msg game.moves.append(Move(play=user_play, ai_play=ai_play, result=msg)) game.put() game.end_game(True) return game.to_form(msg) else: msg = """Sorry, my {} beats your {}. You lose!"""\ .format(ai_play.title(), user_play.title()) game.message = msg game.moves.append(Move(play=user_play, ai_play=ai_play, result=msg)) game.put() game.end_game(False) return game.to_form(msg)
def linkHarder(movesGraph, difficulty=1) -> None: """Links some harder moves.""" if difficulty >= 2: for i in movesGraph['revolvedHalfMoon']: i.time += 5 movesGraph['downwardDog'].addLateMove(movesGraph['handstandHops']) movesGraph['vinyasa'].addMove(movesGraph['forwardFold']) Move.doubleAdd(movesGraph['runningMan'], movesGraph['chinStand']) Move.doubleAdd(movesGraph['triangle'], movesGraph['boundHalfMoon'], late=True) for i in movesGraph['cresent']: i.addLateMove(movesGraph['handstandHops']) movesGraph['crow'].addLateMove(movesGraph['crane']) if difficulty >= 1: movesGraph['vinyasa'].time = max(0, movesGraph['vinyasa'].time - 2) movesGraph['mountain'].time = max(0, movesGraph['mountain'].time - 2) for i in movesGraph['eagle']: i.time += 5 for i in movesGraph['halfMoon']: i.time += 5 movesGraph['star'].time += 5 movesGraph['chair'].time += 5 for i in movesGraph['warrior1']: i.time -= 2 for i in movesGraph['warrior2']: i.time -= 2 for i in movesGraph['chairTwist']: i.time += 5 movesGraph['forwardFold'].addMove(movesGraph['crow']) movesGraph['seatedMeditation'].addMove(movesGraph['frog']) movesGraph['staff'].addMove(movesGraph['frog']) movesGraph['child'].addLateMove(movesGraph['supportedHeadstand']) movesGraph['downwardDog'].addLateMove(movesGraph['supportedHeadstand']) Move.doubleAdd(movesGraph['threeLeggedDog'], movesGraph['pigeon']) for i in movesGraph['twoLeggedDog']: i.addLateMove(movesGraph['plank']) Move.moveReverse(movesGraph['sidePlank']) for i in movesGraph['warrior3']: i.time += 5*max(difficulty,0) for i in ['warrior1', 'warrior2', 'standingLegLift4', 'threeLeggedDog']: for j in movesGraph[i]: j.promoteLate() for i in ['star', 'mountain', 'downwardDog']: movesGraph[i].promoteLate() movesGraph['mountain'].promoteLate(n=max(1, difficulty+1))
def cat_move(self, request, *args, **kwargs): gameId=request.session['gameId'] pos=int(request.POST['click']) statsDict = {} try: if 'statusCat' in request.session and request.session['statusCat']!=-1: print("create move (cat)") games = Game.objects.filter(id=gameId) g=games[0] if(isValidCatMove(self, g, request.session['statusCat'] , pos)==True): move=Move(game=g,origin=request.session['statusCat'],target=pos) move.save() print("move", move) statsDict['message'] = "Movimiento realizado" statsDict['value'] = move.id statsDict['result'] = True if(g.cat1==request.session['statusCat']): g.cat1=pos elif(g.cat2==request.session['statusCat']): g.cat2=pos elif(g.cat3==request.session['statusCat']): g.cat3=pos else: g.cat4=pos g.catTurn=-1 g.save() else: print("error creating move") statsDict['message'] = "Movimiento no realizado" statsDict['value'] = -1 statsDict['result'] = True request.session['statusCat']=-1 else: request.session['statusCat']=pos statsDict['message'] = "origin" statsDict['value'] = pos statsDict['result'] = True except Exception as e: #en caso de error reportalo statsDict['message'] = e.message statsDict['value'] = -1 statsDict['result'] = False return self.create_response(request, statsDict)
def _get_players_in_game(game_id): moves = Move.query(Move.game_id == game_id).fetch() if len(moves) == 0: return StringMessage( message="Invalid move parameters. no game found") print("Getting players in game...") user_ids = [] for move in moves: user_id = move.user_id # print("checking for ID: {0}".format( user_id) ) if user_id not in user_ids and user_id != None: # print("ID: {0} was inserted".format( user_id) ) user_ids.append(user_id) print(user_ids) if len(user_ids) == 2: player1 = user_ids[0] player2 = user_ids[1] elif len(user_ids) == 1: player1 = user_ids[0] player2 = None else: player1 = None player2 = None print(player2, player1) return [player1, player2]
def historyForGame(self, game): """return list of moves from this game""" list = Move.query(Move.gameKey == game.key).fetch() for move in list: move.game = game move.user = self.getPlayer(game, move) return list
def linkEnding(movesGraph) -> None: #Allow me to just go from one arm balance to the opposite side, to increase the chances I get balanced Move.moveReverse(movesGraph['runningMan'], movesGraph['sideCrow'], movesGraph['flyingPigeon'], \ movesGraph['revolvedRunningMan'], movesGraph['chinStand'], movesGraph['twoLeggedDog'], \ movesGraph['oneLeggedPlank'], movesGraph['warrior1'], movesGraph['warrior2']) for i in movesGraph['runningMan']: i.addMove(movesGraph['child']) for i in movesGraph['revolvedRunningMan']: i.addMove(movesGraph['child']) for i in movesGraph['sideCrow']: i.addMove(movesGraph['child']) for i in movesGraph['flyingPigeon']: i.addMove(movesGraph['child']) for i in movesGraph['twoLeggedDog']: i.addMove(movesGraph['child'], movesGraph['downwardDog']) for i in movesGraph['threeLeggedDog']: i.addMove(movesGraph['plank']) i.time += 1 for i in movesGraph['pyramid']: i.addMove(movesGraph['wideLegForwardFold']) movesGraph['wideLegForwardFold'].addMove(*movesGraph['pyramid']) movesGraph['forwardFold'].addMove(*movesGraph['lowLunge'])
def _prepReminder(): games = Game.query( Game.gameCurrentMove < 9 and Game.gameCurrentMove > 0).fetch() remindees = '' if games: # If there are games ready for sign up, # format announcement and set it in memcache for each game for game in games: last_move = Move.query( Move.moveNumber==game.gameCurrentMove-1).get() if last_move: current_time = datetime.utcnow() if last_move.moveTime and (current_time - last_move.moveTime > timedelta(days=5)): next_player = Player.query(Player.displayName == game.nextPlayer).get() if next_player.mainEmail: print 'next_player.mainEmail', next_player.mainEmail remindees.join(next_player.displayName) mail.send_mail( 'noreply@{}.appspotmail.com' .format( app_identity.get_application_id()), next_player.mainEmail, 'Coming back to tic-tac-toe?', 'It has been 5 days since the last move on:\r\n\r\n{}' .format( game.name) ) return remindees
def _prepReminder(): games = Game.query(Game.gameCurrentMove < 9 and Game.gameCurrentMove > 0).fetch() remindees = '' if games: # If there are games ready for sign up, # format announcement and set it in memcache for each game for game in games: last_move = Move.query( Move.moveNumber == game.gameCurrentMove - 1).get() if last_move: current_time = datetime.utcnow() if last_move.moveTime and ( current_time - last_move.moveTime > timedelta(days=5)): next_player = Player.query( Player.displayName == game.nextPlayer).get() if next_player.mainEmail: print 'next_player.mainEmail', next_player.mainEmail remindees.join(next_player.displayName) mail.send_mail( 'noreply@{}.appspotmail.com'.format( app_identity.get_application_id()), next_player.mainEmail, 'Coming back to tic-tac-toe?', 'It has been 5 days since the last move on:\r\n\r\n{}' .format(game.name)) return remindees
def linkAerobics(movesGraph, difficulty = 1, aerobics = 0): """Adds in aerobics moves""" movesGraph['jumpingJacks'] = Move("Jumping Jacks", 0, "Jumping Jacks!", 40 + 20*difficulty, movesGraph['mountain'], countReps=True, countdown=True) movesGraph['runInPlace'] = Move("Running In Place", 0, "Run In Place", 40 + 20*difficulty, movesGraph['mountain'], movesGraph['jumpingJacks'], countdown=True) movesGraph['burpies'] = Move("Burpies!", 0, "Burpies", 30+10*difficulty, movesGraph['vinyasa'], movesGraph['forwardFold'], movesGraph['plank'], \ extended=Move.reDifficultyTimes([60,75,90], 10, difficulty+aerobics), countReps=True, countdown=True) movesGraph['situps'] = Move("Situps", 0, "Situps", 30 + 10*difficulty, movesGraph['vinyasa'], extended=Move.reDifficultyTimes([40,50],10,difficulty + aerobics//2), \ lateMove=set([movesGraph['boat']]), countReps=True) movesGraph['shuffle'] = Move("Shuffle", 0, "Shuffle", 30+10*difficulty, movesGraph['vinyasa']) #//TODO: better description movesGraph['highKnees'] = Move("High Knees", 0, "High Knees", 30+10*difficulty, movesGraph['vinyasa']) #linking here movesGraph['mountain'].addLateMove(movesGraph['jumpingJacks'], movesGraph['runInPlace'], movesGraph['burpies']) movesGraph['jumpingJacks'].addLateMove(movesGraph['runInPlace']) movesGraph['downwardDog'].addLateMove(movesGraph['burpies']) movesGraph['lieOnBack'].addLateMove(movesGraph['situps']) movesGraph['staff'].addLateMove(movesGraph['situps']) if aerobics >= 2: movesGraph['star'].addLateMove(movesGraph['jumpingJacks']) for i in movesGraph['eagle']: i.addLateMove(movesGraph['runInPlace']) if difficulty >= 1: movesGraph['seatedMeditation'].addLateMove(movesGraph['situps']) movesGraph['runInPlace'].addMove(movesGraph['vinyasa']) else: movesGraph['burpies'].addMove(movesGraph['mountain']) if aerobics + difficulty >= 3: movesGraph['mountain'].addLateMove(movesGraph['highKnees']) movesGraph['boat'].addLateMove(movesGraph['situps']) movesGraph['flatBack'].addLateMove(movesGraph['plank']) movesGraph['wideLegStance'].addLateMove(movesGraph['jumpingJacks']) movesGraph['jumpingJacks'].addMove(movesGraph['vinyasa'])
def get(self, user): args = parser.parse_args() initial_date = date.fromisoformat(args.initial_date) end_date = date.fromisoformat(args.end_date) data = Move.select().where( Move.submit_date.between(initial_date, end_date), Move.user == user) out = data.select(fn.SUM( Move.value).alias("total")).where(Move.type == 1) entry = data.select(fn.SUM( Move.value).alias("total")).where(Move.type == 0) out = out[0].total if out is None: out = 0 entry = entry[0].total if entry is None: entry = 0 return json_response( { "entry_sum": entry, "out_sum": out, "profit": (entry - out) }, 200)
def _get_players_in_game(game_id): moves = Move.query(Move.game_id == game_id).fetch() if len(moves) == 0: return StringMessage(message = "Invalid move parameters. no game found" ) print("Getting players in game...") user_ids = [] for move in moves: user_id = move.user_id # print("checking for ID: {0}".format( user_id) ) if user_id not in user_ids and user_id != None: # print("ID: {0} was inserted".format( user_id) ) user_ids.append(user_id) print(user_ids) if len(user_ids) == 2: player1 = user_ids[0] player2 = user_ids[1] elif len(user_ids) == 1: player1 = user_ids[0] player2 = None else: player1 = None player2 = None print(player2, player1) return [player1, player2]
def make_move(self, request): """ Makes a move. Returns a game state with message First check for exceptional cases where the game is already over, an invalid card index was specified, the card chosen has already been uncovered, or that the second card in a move is the same as the first. If the card is the first card in a move, set this to the game entity's previous_choice. If the card is the second in a move, append the previous and current card to history and create a message containing whether the two cards have been matched. If all cards are matched, end the game. """ game = self._get_by_urlsafe(request.urlsafe_game_key, Game) card = request.card if game.game_over: return game.to_form('Game already over!') if card not in xrange(len(game.cards)): raise endpoints.BadRequestException( 'Index is beyond bounds of the current game') if (game.cards[card] in game.uncovered_pairs): raise endpoints.BadRequestException( 'The card chosen has already been uncovered') if game.previous_choice is not None and card == game.previous_choice: raise endpoints.BadRequestException( 'Cannot choose the same card as the first card in a move') if game.previous_choice is None: message = 'You uncover a card' game.current_choice = card response = game.to_form('You uncover a card') # Set this after getting response to avoid intefering with the # previous_choice logic in Game.to_form game.previous_choice = card else: game.current_choice = card game.history.append(Move(card_1=game.previous_choice, card_2=card)) if game.cards[game.previous_choice] == game.cards[card]: message = 'Matched!' game.uncovered_pairs.append(game.cards[card]) if game.num_uncovered_pairs == game.num_pairs: game.end_game() message = 'You win!' else: message = 'Not matched' response = game.to_form(message) game.previous_choice = None # Sets the last_move time game.last_move = datetime.datetime.now() game.email_sent = False game.put() return response
def get_game_history(self, request): ''' returns the usual GameForm, plus all related positions and all moves ''' game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: return endpoints.NotFoundException("Game not found") game_key = game.key game = game.to_form("") ships = Ship.query(ancestor=game_key).order(-Ship.created).fetch() ship_forms = [] for s in ships: position_forms = [] positions = Position.query(ancestor=s.key).fetch() for p in positions: position_forms.append(XYMessage(x=p.x, y=p.y, hit=p.hit)) ship_forms.append( ShipMessage(player=s.player.get().name, ship=s.ship, created_date=s.created, positions=position_forms)) moves = Move.query(ancestor=game_key).order(-Move.created).fetch() move_forms = [] for m in moves: move_forms.append( MoveMessage(player=m.player.get().name, x=m.x, y=m.y, created_date=m.created)) form = FullGameInfo(game=game, ships=ship_forms, moves=move_forms) return form
def getGameHistory(self, request): """ shows a list of all the moves for each game""" game_key = ndb.Key(urlsafe=request.websafeGameKey) moves = Move.query(ancestor=game_key).fetch() if not moves: raise endpoints.NotFoundException('No moves found') else: return MovesForm(items=[move._copyMoveToForm for move in moves])
def test_moves_1(self): move = Move.get_id(1) p = {c.name: getattr(move, c.name) for c in move.__table__.columns} self.assertEqual(p["MOVE_ID"], 1) self.assertEqual(p["MOVE_NAME"], "Pound") self.assertEqual(p["MOVE_POWER"], 40) self.assertEqual(p["MOVE_ACCURACY"], 100) self.assertEqual(p["MOVE_PP"], 35)
def get_moves(self, request): """Gets all moves for a particular game""" try: game_key = ndb.Key(urlsafe=request.urlsafe_game_key) except: raise endpoints.NotFoundException('Bad Key, Game not found!') moves = Move.query(ancestor=game_key).order(Move.number) return MoveForms(items=[move.to_form() for move in moves])
def gameover(self): board = [[128, 64, 32, 16], [64, 32, 16, 8], [32, 16, 8, 4], [16, 8, 1, 0]] boardString = move_logic.serialize_board(board) allempty = [[3, 3]] allemptyString = move_logic.serialize_board(allempty) move = Move( belongs_to=None, moveNumber=100, board=boardString, allempty=allemptyString, serverSecret= "a04aa4256d3fb3847c9a594975fd26efbdebac31bd17b88b0b39be592567230b", serverSecretHashed= "aa1e27d29a4e17d308534ceb6c2774d9ec4f2b9ef1022a49d66a3770ca424a13", clientSecret="", clientSecretHashed= "fee9aa280f017fd716c496afe03a6291bf9a0fe80f07a9026efc4257b71fe848", ) move.save() game = Game(belongs_to=None, lastMove=move, gameover=False, result=None, gameid="jakasgra") game.save() move.belongs_to = game move.save() returned = negotiate_second( game, "b7d64a5f92b663560a3f000a947fae7cad549a5c2e396a4828c5151fd5034ce4") self.assertEqual(returned["valid"], True) self.assertEqual(returned["gameover"], False)
def test_moves_3(self): moves = Move.get_all() p = [] for move in moves: p.append({c.name: getattr(move, c.name) for c in move.__table__.columns}) self.assertEqual(p[0]["MOVE_ID"], 1) self.assertEqual(p[0]["MOVE_NAME"], "Pound") self.assertEqual(p[1]["MOVE_ID"], 2) self.assertEqual(p[1]["MOVE_NAME"], "Karate-chop")
def move_player_and_opponent(i, j): player = get_player() game = get_game(player) board = get_board(game) mcts_player = get_mcts_player(2) mcts_human_hint = get_mcts_player(1) hint, move_probs = mcts_human_hint.get_action(board, return_prob=True) # print(move_probs) move = int(i) * board.height + int(j) score = move_probs[move] board.do_move(move) player_move = Move(game=game, player_move=True, location=move, score=score, hint_location=hint, raw_move_scores=str(move_probs), is_hint=False) db.session.add(player_move) db.session.commit() # check if the game has ended end, winner = board.game_end() if end: game.player_won = winner == 1 db.session.add(game) db.session.commit() session.pop('game_id', None) return redirect("/", code=302) move = mcts_player.get_action(board) board.do_move(move) opponent_move = Move(game=game, player_move=False, location=int(move)) db.session.add(opponent_move) db.session.commit() end, winner = board.game_end() if end: game.player_won = winner == 1 db.session.add(game) db.session.commit() session.pop('game_id', None)
def send(request): ''' Updates latest move in database. Responds with id of last player and move id Expects the following POST parameters: member_id message ''' # TODO modify for muti ip. Works from different IP addresses but not from same one fb_id = request.session['fb_id'] player_id = request.GET.get('player_id') game_id = request.GET.get('game_id') try: moveid = int( request.GET.get('moveid') ) cellid = int( request.GET.get('cellid') ) tileid = int( request.GET.get('tileid') ) rot = int( request.GET.get('rot') ) turnsInHand = int( request.GET.get('turnsInHand') ) loops = int( request.GET.get('loops') ) except: cellid = EMPTYBOARD fp = open( 'send_data.txt', 'w' ) g = Game.objects.get(name=game_id) m = Move( game=g, player=player_id, cell=cellid, tile=tileid, rotation=rot, turnsInHand=turnsInHand, loops=loops ) #m = Move( game=g, player=101, cell=cellid, tile=101, rotation=101 ) m.save() print >> fp, "==================" print >> fp, "cell", m.cell print >> fp, "tile", m.tile print >> fp, "rot", m.rotation print >> fp, "turns", m.turnsInHand print >> fp, "loops", m.loops #r.say(request.user, p['message']) #return HttpResponse(p) print >> fp, "Send complete:", fb_id, player_id, game_id fp.close() return HttpResponse( simplejson.dumps( { "playerids": player_id, "moveid": m.id } ), mimetype='application/javascript' )
def test_pile_move_added(self): game = Game.objects.get() new_pile = Pile( position = 0, amount = 3, game = game ) new_pile.save() new_move = Move( #start at 0th move order = 0, game = game, pile = new_pile, taken = 2 ) new_move.save() self.assertEqual(len(game.pile_set.all()), 1) self.assertEqual(len(game.move_set.all()), 1)
def put(self, user, path_id): path_obj = (Path.select().where(Path.user == user, Path.id == path_id).get()) path_obj.last_ship_date = date.today() move = Move( value=path_obj.total, type=0, obs=f"GERADO DA VENDA DA ROTA {path_obj.id}", user=user, ) path_obj.save() move.save() result = {"msg": "sucesso"} return json_response(result, 200)
def get_game_history(self, request): """get moves history for each game requested""" url_safe_key = request.urlsafe_game_key game = get_by_urlsafe(url_safe_key, Game) moves = Move.query(Move.game == game.key) moves_list = [] for move in moves: moves_list.append(move.to_form()) return MoveForms(items=moves_list)
def _random_moves( self, poke_species: PokemonSpecies) -> tuple[Move, Move, Move, Move]: if len(poke_species.learn_set) == 0: raise ValueError("Can't pick random moves from an empty learn set") move_infos = random.sample(poke_species.learn_set, min(len(poke_species.learn_set), 4)) # noinspection PyTypeChecker return tuple( Move(move_info, pp=move_info.total_pp) for move_info in move_infos)
def test_source_insert_5(self): s = Move(name = "rest", power = "10", accuracy = "10", type = "psychic", pp = "10") session.add(s) session.commit() r = session.query(Move).filter_by(name = "rest").one() self.assertEqual(str(r.name), 'rest') session.query(Move).filter_by(name = "rest").delete() session.commit()
def test_source_insert_6(self): s = Move(name = 'ice-punch', power = "75", accuracy = "100", type = "ice", pp = "15") session.add(s) session.commit() r = session.query(Move).filter_by(name = 'ice-punch').one() self.assertEqual(str(r.name), 'ice-punch') session.query(Move).filter_by(name = 'ice-punch').delete() session.commit()
def test_source_insert_4(self): s = Move(name = "scratch", power = "40", accuracy = "100", type ="normal", pp = "35" ) session.add(s) session.commit() r = session.query(Move).filter_by(name = "scratch").one() self.assertEqual(str(r.name), 'scratch') session.query(Move).filter_by(name = 'scratch').delete() session.commit()
def test_moves_4(self): move = Move.get("Water-pulse") p = {c.name: getattr(move, c.name) for c in move.__table__.columns} self.assertEqual(p["MOVE_ID"], 352) self.assertEqual(p["MOVE_NAME"], "Water-pulse") self.assertEqual(p["MOVE_TYPE"], "Water") self.assertEqual(p["MOVE_CATEGORY"], "Special") self.assertEqual(p["MOVE_POWER"], 60) self.assertEqual(p["MOVE_ACCURACY"], 100) self.assertEqual(p["MOVE_PP"], 20) self.assertEqual(p["MOVE_DESCRIPTION"], "Inflicts regular damage. Has a 20% chance to confuse the target.")
def negotiate_first(game, resolved_board, allempty, clientSecretHashed): previousMove = game.lastMove if previousMove.clientSecret == "": raise UnfinishedMove("I was expecting client secret now.") previousNumber = previousMove.moveNumber serverSecret = rand256hex() serverSecretHashed = sha256(serverSecret) move = Move( belongs_to = game, moveNumber = previousNumber + 1, board = move_logic.serialize_board(resolved_board), allempty = move_logic.serialize_board(allempty), serverSecret = serverSecret, serverSecretHashed = serverSecretHashed, clientSecret = "", clientSecretHashed = clientSecretHashed ) move.save() game.lastMove = move game.save() return move
def record_roll(player, roll: 'Roll', game_id: str, is_winning_play: bool, roll_num: int): session = session_factory.create_session() move = Move() move.player_id = player.id move.roll_id = roll.id move.game_id = game_id move.is_winning_play = is_winning_play move.roll_number = roll_num session.add(move) session.commit() session.close()
def test_moves_6(self): move = Move.get("Psychic") p = {c.name: getattr(move, c.name) for c in move.__table__.columns} self.assertEqual(p["MOVE_ID"], 94) self.assertEqual(p["MOVE_NAME"], "Psychic") self.assertEqual(p["MOVE_TYPE"], "Psychic") self.assertEqual(p["MOVE_CATEGORY"], "Special") self.assertEqual(p["MOVE_POWER"], 90) self.assertEqual(p["MOVE_ACCURACY"], 100) self.assertEqual(p["MOVE_PP"], 10) self.assertEqual( p["MOVE_DESCRIPTION"], "Inflicts regular damage. Has a 10% chance to lower the target's Special Defense by one stage.", )
def test_moves_5(self): move = Move.get("Aurora-beam") p = {c.name: getattr(move, c.name) for c in move.__table__.columns} self.assertEqual(p["MOVE_ID"], 62) self.assertEqual(p["MOVE_NAME"], "Aurora-beam") self.assertEqual(p["MOVE_TYPE"], "Ice") self.assertEqual(p["MOVE_CATEGORY"], "Special") self.assertEqual(p["MOVE_POWER"], 65) self.assertEqual(p["MOVE_ACCURACY"], 100) self.assertEqual(p["MOVE_PP"], 20) self.assertEqual( p["MOVE_DESCRIPTION"], "Inflicts regular damage. Has a 10% chance to lower the target's Attack by one stage.", )
def test_moves_4(self): move = Move.get("Rock-tomb") p = {c.name: getattr(move, c.name) for c in move.__table__.columns} self.assertEqual(p["MOVE_ID"], 317) self.assertEqual(p["MOVE_NAME"], "Rock-tomb") self.assertEqual(p["MOVE_TYPE"], "Rock") self.assertEqual(p["MOVE_CATEGORY"], "Physical") self.assertEqual(p["MOVE_POWER"], 50) self.assertEqual(p["MOVE_ACCURACY"], 80) self.assertEqual(p["MOVE_PP"], 10) self.assertEqual( p["MOVE_DESCRIPTION"], "Inflicts regular damage. Has a 100% chance to lower the target's Speed by one stage.", )
def mouse_move(self, request, args): id = request.session['gameId'] games = Game.objects.filter(id=id) statsDict = {} game = games[0] uclick = request.POST['click'] click = int(uclick) try: if (UserResource.isValidMouseMove(self, game, game.mouse, click) == True): cm = Move(origin=game.mouse, target=click, game=game) cm.save() game.mouse = click statsDict['message'] = "La posicion es valida" statsDict['value'] = cm.id statsDict['result'] = True game.catTurn = 1 request.session['amIcat'] = -1 game.save() else: statsDict['message'] = "La posicion final no es valida" statsDict['value'] = -1 statsDict['result'] = False except Exception as e: #en caso de error reportalo statsDict['message'] = e.message statsDict['value'] = -1 statsDict['result'] = False return self.create_response(request, statsDict)
def test_time_left_2(self): # add game, moves and check them game = Game.create(white='123', black='456', state='Ke1,ke8', type_game=TYPE_SLOW, time_limit=10) Move.create(game=game, number=1, figure='K', move='e1-e2', time_move=9, color=WHITE) Move.create(game=game, number=2, figure='k', move='e8-e7', time_move=3, color=BLACK) Move.create(game=game, number=3, figure='K', move='e2-e3', time_move=5, color=WHITE) Move.create(game=game, number=4, figure='k', move='e7-e8', time_move=6, color=BLACK) self.assertFalse(game.ended) self.assertAlmostEqual(game.time_left(WHITE), 10, places=1) self.assertAlmostEqual(game.time_left(BLACK), 10, places=1) # shift date_state in limit self.assertFalse(game.is_time_over()) game.date_state = datetime.now() - timedelta(seconds=3) self.assertAlmostEqual(game.time_left(WHITE), 7, places=1) self.assertAlmostEqual(game.time_left(BLACK), 10, places=1) self.assertFalse(game.is_time_over()) # shift date_state out limit game.date_state = datetime.now() - timedelta(seconds=10) self.assertTrue(game.is_time_over()) self.assertTrue(game.ended) self.assertEqual(game.winner, BLACK) self.assertFalse(game.is_time_over())
def cancel_game(self, request): """ Delete an unfinished game """ game_id = request.game_id game = Game.query(Game.game_id == game_id).get() if game == None: return StringMessage(message = "No Game found for ID: {0} ".format(game_id)) if game.finished == True: return StringMessage(message = "Can't delete a game thats already finished") # for the moment, resets every move for provided game_id moves = Move.query().fetch() moves_deleted = Move.query(Move.game_id == game_id).fetch() print("game id is {0} {1}".format(game_id, moves[0].game_id )) # Deleting Game game.key.delete() # Deleting Moves for move in moves_deleted: move.key.delete() return StringMessage(message = "Game Reset Complete, deleted {0} moves for Game: {1} ".format(len(moves_deleted), game_id))
def _get_players_in_game(game_id): """ returns player ids from a game """ moves = Move.query(Move.game_id == game_id).fetch() if len(moves) == 0: return StringMessage(message = "Invalid move parameters. no game found" ) print("Getting players in game...") user_ids = [] game = Game.query(Game.game_id == game_id).get() user_ids.append(game.player1) user_ids.append(game.player2) return user_ids
def add_move(i, j): player = get_player() game = get_game(player) human = False if len(game.moves) % 2 == 0: human = True board = get_board(game) if human: mcts_player = get_mcts_player(1) else: mcts_player = get_mcts_player(2) hint, move_probs = mcts_player.get_action(board, return_prob=True) # print(move_probs) move = int(i) * board.height + int(j) score = move_probs[move] board.do_move(move) player_move = Move(game=game, player_move=human, location=move, score=score, hint_location=hint, raw_move_scores=str(move_probs), is_hint=False) db.session.add(player_move) db.session.commit() # check if the game has ended end, winner = board.game_end() if end: game.player_won = winner == 1 db.session.add(game) db.session.commit() session.pop('game_id', None) # return redirect("/", code=302) if player_move.player_move and game.player_is_white: color = 'white' elif not player_move.player_move and not game.player_is_white: color = 'white' else: color = 'black' return {'end': end, 'winner': winner, 'score': score, 'color': color}
def make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) kind = "X" if game.whose_turn == game.user_name_x else "O" # if game.whose_turn == game.user_name_x: # kind = "X" # else: # kind = "O" # if abs(request.move_x)>2 or (request.move_y)>2: if request.move_x not in range(3) or request.move_y not in range(3): raise endpoints.BadRequestException( 'x & y coordinates must be 0, 1, or 2') move = Move(parent=game.key, kind=kind, number=game.number_of_moves + 1, x=request.move_x, y=request.move_y) return make_move_2(game=game, player=request.user_name, move=move)
def test_time_left_3(self): # add game, moves and check them game = Game.create(white='123', black='456', state='Ke1,ke8', time_limit=10) Move.create(game=game, number=1, figure='K', move='e1-e2', time_move=9, color=WHITE) Move.create(game=game, number=2, figure='k', move='e8-e7', time_move=3, color=BLACK) Move.create(game=game, number=3, figure='K', move='e2-e3', time_move=5, color=WHITE) Move.create(game=game, number=4, figure='k', move='e7-e8', time_move=6, color=BLACK) self.assertFalse(game.ended) self.assertIsNone(game.time_left(WHITE)) self.assertIsNone(game.time_left(BLACK)) self.assertFalse(game.is_time_over()) # shift date_state out limit game.date_state = datetime.now() - timedelta(days=1000) self.assertIsNone(game.time_left(WHITE)) self.assertIsNone(game.time_left(BLACK)) self.assertFalse(game.is_time_over()) self.assertIsNone(game.winner)