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 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 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 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 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 pos_post(self, obj): move = Move( value=obj.total, type=1, obs=f"GERADO DA COMPRA {obj.id}", user=obj.user, ) move.save()
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 _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 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 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 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 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 create_move(): move = load_json('pokemon_moves.json') for next_move in move: print(next_move) name = next_move power = move[next_move]['power'] accuracy = move[next_move]['accuracy'] type = move[next_move]['type'] pp = move[next_move]['pp'] newMove = Move(name=name, power=power, accuracy=accuracy, type=type, pp=pp) # After I create the book, I can then add it to my session. session.add(newMove) # commit the session to my DB. session.commit()
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 parse_moves(session): # get name of file movefile = os.path.join(os.path.expanduser(cfg.CURRENT_DIR), cfg.MOVELOG) # read the file, write lines to database, and save lines that were not # written to the database # TODO may need to check if file is already open using a file lock if os.path.isfile(movefile): f = open(movefile, 'r+') lines_to_save = [] last_location = (0, 0) last_time = 0.0 for line in f: try: text = ast.literal_eval(line.rstrip()) time = text['time'] location = text['location'] # throttle mouse tracking to 10Hz if location == last_location or time - last_time < 0.1: continue move = Move(time, location[0], location[1]) session.add(move) last_location = location last_time = time except: print "Could not save " + str( text ) + " to the database. Saving for the next round of parsing." lines_to_save.append(text) # write lines that did not make it into the database to the start of the # file and delete the rest of the file f.seek(0) for line in lines_to_save: f.write(line) f.truncate() f.close()
def cat_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 'select' not in request.session: #Si no existe la creamos request.session['select'] = 0 if (request.session['select'] == 0): #Comprueba pos.inicial request.session['select'] = 1 #Cambiamos para que la siguiente llamada se meta en pos.final print("ORGIGEN", click) flag = 0 #Comprobamos si existe algun gato en esta posicion if (game.cat1 == click): request.session['catnumber'] = 1 flag = 1 elif (game.cat2 == click): request.session['catnumber'] = 2 flag = 1 elif (game.cat3 == click): request.session['catnumber'] = 3 flag = 1 elif (game.cat4 == click): request.session['catnumber'] = 4 flag = 1 if (flag == 0): statsDict['message'] = "Error en pos inicial" statsDict['value'] = -1 statsDict['result'] = False else: cm = Move(origin=click, game=game) cm.save() request.session['moveId'] = int(cm.id) #Guardamos la id statsDict['message'] = "La posicion es valida" statsDict['value'] = cm.id statsDict['result'] = True request.session['origin'] = click #Guardamos la posicion de origen para usarla en la siguiente llamada return self.create_response(request, statsDict) elif (request.session['select'] == 1): #Comprueba pos. final request.session['select'] = 0 moveId = int(request.session['moveId']) cms = Move.objects.filter(id=moveId) cm = cms[0] cm.target = click cm.save() print("DESTINO", request.session['origin'], click) if (UserResource.isValidCatMove(self, game, request.session['origin'], click) == True): if (request.session['catnumber'] == 1): game.cat1 = click elif (request.session['catnumber'] == 2): game.cat2 = click elif (request.session['catnumber'] == 3): game.cat3 = click elif (request.session['catnumber'] == 4): game.cat4 = click game.catTurn = -1 request.session['amIcat'] = 1 game.save() statsDict['message'] = "La posicion es valida" statsDict['value'] = cm.id statsDict['result'] = True else: statsDict['message'] = "La posicion final no es valida" statsDict['value'] = -1 statsDict['result'] = False game.catTurn = 1 game.save() 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 make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) player = User.by_name(request.user_name) # preflight checks for valid request if not player: raise endpoints.BadRequestException('User not found!') if game.status == 'game over': raise endpoints.BadRequestException('Game already over!') if game.status == 'setting up': raise endpoints.BadRequestException( 'Game not ready yet! Place your ships.') if game.p1 != player.key and game.p2 != player.key: raise endpoints.BadRequestException( 'The specified user is not playing the specified game.') # determine who is making a move and if it's really their turn if game.p1 == player.key: opponent = game.p2.get() if game.status == 'p2 move': raise endpoints.BadRequestException('Error: It is ' + opponent.name + '\'s turn!') else: opponent = game.p1.get() if game.status == 'p1 move': raise endpoints.BadRequestException('Error: It is ' + opponent.name + '\'s turn!') ## coordinates x = int(request.x) y = int(request.y) if x not in range(BOARD_SIZE) or y not in range(BOARD_SIZE): raise endpoints.BadRequestException( 'Attempted move is off the board.') # attempt move if Move.get_move(game, player, x, y): raise endpoints.BadRequestException('You already made that move') # we have determined player is making a valid move, so switch whose turn it is if game.status == 'p1 move': game.status = 'p2 move' else: game.status = 'p1 move' game.put() # create a Move object move = Move(parent=game.key, player=player.key, x=x, y=y) move.put() # check for hits ships = Ship.query(ancestor=game.key).filter( Ship.player == opponent.key).fetch() position = None # position that was hit, if any ship = None # ship that was hit, if any to_put = [] for s in ships: position = Position.query(ancestor=s.key).filter( Position.x == x, Position.y == y).get() if position: position.hit = True position.put() positions = Position.query(ancestor=s.key).fetch() hit_positions = [p for p in positions if p.hit == True] if positions == hit_positions: s.sunk = True s.put() sunk_ships = [sunk for sunk in ships if sunk.sunk == True] if sunk_ships == ships: game.status = 'game over' game.winner = player.key game.put() # send game-over email message = '{} sunk {}! The game is over and {} won!'.format( player.name, s.ship, player.name) self.sendEmail(player, game, message) self.sendEmail(opponent, game, message) # return game over MoveResponse return MoveResponse( hit=True, ship=s.ship, sunk=True, message='Hit! Sunk! Game over! You win!') #return sunk ship message message = 'Your turn! {} sunk your {}!'.format( player.name, s.ship) self.sendEmail(opponent, game, message) return MoveResponse(hit=True, ship=s.ship, sunk=True, message="Hit! Sunk " + s.ship + "!") # hit message sent to opponent message = 'Your turn! {} hit your {}!'.format( player.name, s.ship) self.sendEmail(opponent, game, message) # return hit message return MoveResponse(hit=True, ship=s.ship, sunk=False, message="Hit on " + s.ship + "!") message = 'Your turn! {} missed at {}, {}!'.format(player.name, x, y) self.sendEmail(opponent, game, message) # no match for a ship at x, y, so return a Miss message return MoveResponse(hit=False, message='Miss at ' + str(x) + ' , ' + str(y) + '!')
def makeMove(self, request): """ authenticated player makes a move, implemented by creating a move, updating Game and Player """ g_key = ndb.Key(urlsafe=request.websafeGameKey) game = g_key.get() # set up for a move m_id = Move.allocate_ids(size=1, parent=g_key)[0] m_key = ndb.Key(Move, m_id, parent=g_key) player = Player.query(Player.displayName == request.player_name).get() next_player_name = game.playerTwo if player.displayName == game.playerOne else game.playerOne next_player = Player.query( Player.displayName == next_player_name).get() print('next_player', next_player_name) if game.gameOver: raise endpoints.UnauthorizedException('This game is already over.') # check if game is signed up by two players and by the current player elif game.playerOne is None or game.playerTwo is None: raise endpoints.UnauthorizedException( 'Need 2 signed-up players to start') elif not player: raise endpoints.NotFoundException('no player found') elif player.displayName not in [game.playerTwo, game.playerOne]: raise endpoints.UnauthorizedException('You did not sign up') # check if the player had played the last move elif player.displayName != game.nextPlayer is not None: raise endpoints.UnauthorizedException( "Player {}, it is your opponent {}'s turn".format( player.displayName, game.nextPlayer)) elif game.board[request.positionTaken] != '': raise endpoints.UnauthorizedException('The game board position {} \ is already taken'.format(request.positionTaken)) else: data = {} data['key'] = m_key data['moveNumber'] = game.gameCurrentMove + 1 data['playerName'] = player.displayName data['positionTaken'] = request.positionTaken Move(**data).put() move = m_key.get() # Update Game on the position affected by the move, and player game.gameCurrentMove += 1 game.board[request.positionTaken] = request.player_name setattr(game, 'nextPlayer', next_player_name) if game._isWon: setattr(game, 'gameWinner', getattr(player, 'displayName')) # if no win and game.gameCurrentMove >= 9, it is a tie; # declare the winner as 'tie' if game.gameCurrentMove > 9: setattr(game, 'gameWinner', 'tie') if game._isWon or game.gameCurrentMove > 9: setattr(game, 'gameOver', True) player.gamesInProgress.remove(g_key.urlsafe()) player.gamesCompleted.append(g_key.urlsafe()) next_player.gamesInProgress.remove(g_key.urlsafe()) next_player.gamesCompleted.append(g_key.urlsafe()) # if no winner at step before 9, send a move invite to the opponent game.put() player.put() next_player.put() return game._copyGameToForm
def f(q): # auxiliary function required for the target of the process moves = [Move(coordinates=Coordinates(), axes=split_rotation)]*n for move in moves: q.put(move)
def cat_move(request, origen, destino, gameID): context_dict = {} #Buscamos el juego con el id que nos han pasado por parametro games = Game.objects.filter(id=gameID) #Si el juego existe if games.exists(): game = games[0] #Comprobamos si es el turno del gato if (game.catTurn == True): #Comprobamos que el origen se corresponda con ningun otro gato ni con ningun raton if ((game.cat1 == origen) or (game.cat2 == origen) or (game.cat3 == origen) or (game.cat4 == origen)): if ((game.cat1 != destino) and (game.cat2 != destino) and (game.cat3 != destino) and (game.cat4 != destino) and (game.mouse != destino)): #Comprobamos que el movimiento que va a realizar el gato es correcto if ((destino < 64) and (destino > origen)): #Comprobamos que el destino es correcto if ((destino == origen + 9) or (destino == origen + 7)): #Comprobamos si el origen esta en el borde de la izquierda del tablero if (origen % 8 == 0): #Comprobamos que el movimiento del gato sea de la manera correcta if (destino == origen + 9): move = Move(origin=origen, target=destino, game=game) if (game.cat1 == origen): game.cat1 = move.target game.catTurn = False move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del gato context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game elif (game.cat2 == origen): game.cat2 = move.target game.catTurn = False move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del gato context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game elif (game.cat3 == origen): game.cat3 = move.target game.catTurn = False move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del gato context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game elif (game.cat4 == origen): game.cat4 = move.target game.catTurn = False move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del gato context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game else: context_dict[ 'Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None else: context_dict[ 'Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #Comprobamos si el origen esta en el borde de la derecha del tablero elif (origen % 8 == 7): #Comprobamos que el movimiento del gato sea de la manera correcta if (destino == origen + 7): move = Move(origin=origen, target=destino, game=game) if (game.cat1 == origen): game.cat1 = move.target game.catTurn = False move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del gato context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game elif (game.cat2 == origen): game.cat2 = move.target game.catTurn = False move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del gato context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game elif (game.cat3 == origen): game.cat3 = move.target game.catTurn = False move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del gato context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game elif (game.cat4 == origen): game.cat4 = move.target game.catTurn = False move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del gato context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game else: game.catTurn = False move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del gato context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game else: context_dict[ 'Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #Este movimiento se crea debido a que no se encuentra en ninguna situacion anterior. else: move = Move(origin=origen, target=destino, game=game) if (game.cat1 == origen): game.cat1 = move.target game.catTurn = False move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del gato context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game elif (game.cat2 == origen): game.cat2 = move.target game.catTurn = False move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del gato context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game elif (game.cat3 == origen): game.cat3 = move.target game.catTurn = False move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del gato context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game elif (game.cat4 == origen): game.cat4 = move.target game.catTurn = False move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del gato context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game else: context_dict[ 'Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #El destino se no esta dentro del tablero else: context_dict['Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #El movimiento que va a realizar es incorrecto else: context_dict[ 'Error'] = 'you must move to a contiguous diagonal place' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #El destino se corresponde con la posicion de algun gato o raton else: context_dict['Error'] = 'cannot be a cat in the target' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #El origen no se corresponde con la posicion de algun gato o raton else: context_dict['Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #No es el turno del gato else: context_dict['Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #No hay ningun juego con ese id else: context_dict['Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None return context_dict
def mouse_move(request, destino, gameID): context_dict = {} #Buscamos el juego con el id que nos han pasado por parametro games = Game.objects.filter(id=gameID) #Si el juego existe if games.exists(): game = games[0] #Comprobamos si es el turno del raton if (game.catTurn == False): #Comprobamos si el destino al que vamos se corresponde con la posicion de un gato if ((destino != game.cat1) and (destino != game.cat2) and (destino != game.cat3) and (destino != game.cat4)): #Comprobamos que el movimiento que va a realizar el raton es el correcto if ((destino == game.mouse - 9) or (destino == game.mouse - 7) or (destino == game.mouse + 9) or (destino == game.mouse + 7)): #Comprobamos que el movimiento a realizar se hace dentro del tablero if ((destino >= 0) and (destino < 64)): #Comprobamos si el raton esta en el borde de la derecha del tablero if game.mouse % 8 == 7: #Comprobamos que el movimiento no se salga del tablero if ((destino == game.mouse + 7) or (destino == game.mouse - 9)): move = Move(origin=game.mouse, target=destino, game=game) game.mouse = move.target game.catTurn = True move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del raton context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game else: context_dict['Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #Comprobamos si el raton esta en el borde de la izquierda del tablero elif game.mouse % 8 == 0: #Comprobamos que el movimiento del raton no se salga del tablero if ((destino == game.mouse + 9) or (destino == game.mouse - 7)): move = Move(origin=game.mouse, target=destino, game=game) game.mouse = move.target game.catTurn = True move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del raton context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game #Si el movimiento del raton se sale del tablero else: context_dict['Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #Este movimiento se crea debido a que no se encuentra en ninguna situacion anterior else: move = Move(origin=game.mouse, target=destino, game=game) game.mouse = move.target game.catTurn = True move.save() game.save() #Guardamos el movimiento y tambien la pueva posicion del raton context_dict['Created'] = True context_dict['Move'] = move context_dict['Game'] = game #El movimiento a realizar no se hace dentro del tablero else: context_dict['Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #El movimiento que va a realizar el raton es incorrecto else: context_dict['Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #Al destino al que vamos esta ocupado por un gato else: context_dict['Error'] = 'cannot be a cat in the target' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #No es el turno del raton else: context_dict['Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None #No existe ningun juego con ese identificador else: context_dict['Error'] = 'Cannot create a move' context_dict['Created'] = False context_dict['Move'] = None context_dict['Game'] = None return context_dict
def connection(self, server_ip, server_port): import socket # inner functions of connection sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((server_ip, server_port)) print('Listening at', sock.getsockname()) # Starts listening at client (robot) i = 0 while 1: # start_time = time.time() if self.stop_communication_event.is_set(): self.stop_communication_event.clear() break data, address = sock.recvfrom(MAX_BYTES) if i > 0: self.wait_robot_event.set() xml_send_string = data.decode('ascii') # xml_send is the xml file sent from Kuka to PC xml_send = Xml.fromstring(xml_send_string) # get sensor data - feed the queue if i == 0: # first received xml from pc only contains ipoc value ipoc = xml_send.find('IPOC').text data = Data() i += 1 else: data = get_data_from_send_xml(xml_send) ipoc = str(data.ipoc) if data.delay > 0: self.lost_packages += 1 try: self.data_deque.append(data) except Exception as error: self.data_deque.append(Data()) print('Sensor data queue received null data object: '.join(str(error))) # xml_receive is the xml file sent from PC to Kuka if self.move_queue.empty(): if ~self.move_event.is_set(): self.move_event.set() move = Move(coordinates=Coordinates(), axes=Axes()) else: if self.move_event.is_set(): self.move_event.clear() move = self.move_queue.get() if data.delay > 0: self.move_queue.put(move) if self.impedance_control_x is not None and self.impedance_control_y is not None and self.impedance_control_z is not None: move.x += self.impedance_control_x.correction(data.ftc.x) move.y += self.impedance_control_y.correction(data.ftc.y) move.z += self.impedance_control_z.correction(-(-30-data.ftc.z)) xml_receive = generate_receive_xml(move, self.dig_out, ipoc) sock.sendto(xml_receive, address) # print("---Delay: %d --- Move: %s ---" % (data.delay, str(self.move_event.is_set()), )) if data.delay > 20: print('Danger! Sequential lost data packages count ' + str(data.delay))
def startGame(self, request): """ Initializes all 9 posible moves using provided game_id """ game_id = request.game_id player1 = request.player1 player2 = request.player2 if request.game_id == None: return StringMessage( message= "Failed, Empty game_id. Please enter a valid unique game_id") if request.player1 == None or request.player2 == None: return StringMessage( message= "Failed, Missing Players. Make sure both player ids are present" ) if request.player1 == request.player2: return StringMessage( message="Failed, Player Ids must be different") game_exists = len(Move.query(Move.game_id == game_id).fetch()) > 0 if game_exists: return StringMessage( message="Game Creation Failed, Game ID already exists: {0}". format(game_id)) # Creating Game game = Game(game_id=game_id, player1=request.player1, player2=request.player2) game.put() print("New Game Created: {0}".format(game)) mv1 = Move(x=0, y=0, game_id=game_id, available=True, description="[0,0]") mv2 = Move(x=0, y=1, game_id=game_id, available=True, description="[0,1]") mv3 = Move(x=0, y=2, game_id=game_id, available=True, description="[0,2]") mv4 = Move(x=1, y=0, game_id=game_id, available=True, description="[1,0]") mv5 = Move(x=1, y=1, game_id=game_id, available=True, description="[1,1]") mv6 = Move(x=1, y=2, game_id=game_id, available=True, description="[1,2]") mv7 = Move(x=2, y=0, game_id=game_id, available=True, description="[2,0]") mv8 = Move(x=2, y=1, game_id=game_id, available=True, description="[2,1]") mv9 = Move(x=2, y=2, game_id=game_id, available=True, description="[2,2]") # ndb.put_multi([ mv1, mv2, mv3, mv4, mv5, mv6, mv7, mv8, mv9]) for m in [mv1, mv2, mv3, mv4, mv5, mv6, mv7, mv8, mv9]: print(" saving: {0}".format(m)) m.put() return StringMessage( message="New Game Created, ID: {0} | Player 1: {1} | Player 2: {2}" .format(game_id, player1, player2))