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)
Esempio n. 2
0
    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)
Esempio n. 3
0
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!")
Esempio n. 4
0
 def pos_post(self, obj):
     move = Move(
         value=obj.total,
         type=1,
         obs=f"GERADO DA COMPRA {obj.id}",
         user=obj.user,
     )
     move.save()
Esempio n. 5
0
 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)
Esempio n. 6
0
    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)
Esempio n. 7
0
    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)
Esempio n. 8
0
 def test_save_move_duplicate_positions(self):
   ''' Tests second move in same x/y position from different player.
       Expected: An exception is raised with message for unique together (game, x, y).
   '''
   game = Game.objects.get(id=1)
   player1 = Player.objects.get(id=1)
   player2 = Player.objects.get(id=2)
   move = Move(game=game, player=player1, position_x=1, position_y=1)
   move2 = Move(game=game, player=player2, position_x=1, position_y=1)
   move.save()
   from_db = Move.objects.get(id=1)
   self.assertEqual(from_db.position_x, 1)
   with self.assertRaises(IntegrityError) as context:
     move2.save()
   self.assertEqual(context.exception.message, 'columns game_id, position_x, position_y are not unique')
Esempio n. 9
0
 def test_save_same_player_immediate_succession(self):
   ''' Tests same player making otherwise valid moves back to back.
       Expected: An exception is raised with message for consecutive moves.
   '''
   game = Game.objects.get(id=1)
   player1 = Player.objects.get(id=1)
   player2 = Player.objects.get(id=2)
   move = Move(game=game, player=player1, position_x=1, position_y=1)
   move2 = Move(game=game, player=player1, position_x=1, position_y=2)
   move.save()
   from_db = Move.objects.get(id=1)
   self.assertEqual(from_db.position_x, 1)
   with self.assertRaises(IntegrityError) as context:
     move2.save()
   self.assertEqual(context.exception.message, 'Same player cannot make consecutive moves in the same game')
Esempio n. 10
0
 def test_invalid_positions(self):
   ''' Tests for positions outside of possible values.
       Expected: Exception raised
   '''
   game = Game.objects.get(id=1)
   player1 = Player.objects.get(id=1)
   invalid_position = 7
   move = Move(game=game, player=player1, position_x=invalid_position, position_y=1)
   with self.assertRaises(IntegrityError) as context:
     move.save()
   self.assertEqual(context.exception.message, 'position_x, %s is outside of valid range,0-2' % invalid_position)
   move.position_x = 0
   move.position_y = invalid_position
   with self.assertRaises(IntegrityError) as context:
     move.save()
   self.assertEqual(context.exception.message, 'position_y, %s is outside of valid range,0-2' % invalid_position)
Esempio n. 11
0
    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)
Esempio n. 12
0
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' )
Esempio n. 13
0
    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 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 newGame(user):
    board = move_logic.create_board(move_logic.size)
    board[1][1] = 1
    move = Move(
            belongs_to = None,
            moveNumber = 1,
            board = move_logic.serialize_board(board),
            serverSecret = "0",
            serverSecretHashed = "0",
            clientSecret = "0",
            clientSecretHashed = "0"
            )
    move.save()
    game = Game(
            gameid = rand256hex(),
            belongs_to = user,
            gameover = False,
            lastMove = move
            )
    game.save()
    move.belongs_to = game
    move.save()
    return game
Esempio n. 16
0
 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)
Esempio n. 17
0
    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)
Esempio n. 18
0
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
Esempio n. 19
0
def send(request):
    '''
    Expects the following POST parameters:
    member_id
    message
    '''
   
    # TODO modify for muti ip. Works from different IP addresses but not from same one
    single_ip_test = True

    if ( single_ip_test == False ):
    	user_id    = request.session['member_id']
    	player_id  = request.session['player_id']
    	game_id    = request.session['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') )

    	if ( single_ip_test == True ):
    	    user_id    = ( request.GET.get('member_id') )
    	    player_id  = int( request.GET.get('player_id') )
    	    game_id    = int( request.GET.get('game_id')   )


        #p = simplejson.loads(request.raw_post_data)
	#print p
    	#moveid = int( p['moveid'] )
    	#cellid = int( p['cellid'] )
    	#tileid = int( p['tileid'] )
    	#rot    = int( p['rot'] )
    	#turnsInHand = int( p['turnsInHand'] )
    	#loops  = int( p['loops'] )

    	#if ( single_ip_test == True ):
    	#    user_id    = int( p['member_id'] )
    	#    player_id  = int( p['player_id'] )
    	#    game_id    = int( p['game_id']   )

    except:
	cellid = EMPTYBOARD

    print "=================="
    print moveid
    print cellid
    print tileid
    print rot
    print turnsInHand
    print loops

    print "Send complete:", user_id, player_id, game_id
    
    g = Game.objects.get(id=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() 
    #r.say(request.user, p['message'])
    #return HttpResponse(p)
    return HttpResponse( simplejson.dumps( { "playerids": player_id } ), mimetype='application/javascript' )
Esempio n. 20
0
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
Esempio n. 21
0
    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)