Example #1
0
 def test2(self):
     """ check if moves are possible in non active games"""
     game = Game(cat_user=self.users[0])
     game.save()
     with self.assertRaisesRegex(ValidationError, tests.MSG_ERROR_MOVE):
         Move.objects.create(game=game, player=self.users[0],
                             origin=0, target=9)
Example #2
0
    def test11(self):
        """ Check if __str__ function is available.
            If Game created (but not active) only cat information is printed
            If game is actived then cat and mouse position are given
            [X] vs [ ] report if it is the cat/mouse player turn.
        """
        game = Game(id=0, cat_user=self.users[0])
        self.assertEqual(str(game), "(0, Created)\tCat [X]"
                                    " cat_user_test(0, 2, 4, 6)")

        game.mouse_user = self.users[1]
        game.status = GameStatus.ACTIVE
        game.save()
        self.assertEqual(
            str(game),
            "(0, Active)\tCat [X] cat_user_test(0, 2, 4, 6)"
            " --- Mouse [ ] mouse_user_test(59)")
        game.cat_turn = False
        self.assertEqual(
            str(game),
            "(0, Active)\tCat [ ] "
            "cat_user_test(0, 2, 4, 6) --- Mouse [X] mouse_user_test(59)")

        game.status = GameStatus.FINISHED
        game.save()
        self.assertEqual(
            str(game),
            "(0, Finished)\tCat [ ]"
            " cat_user_test(0, 2, 4, 6) --- Mouse [X] mouse_user_test(59)"
        )
Example #3
0
    def test11(self):
        """ Conversiones a string """
        game = Game(id=0, cat_user=self.users[0])
        self.assertEqual(str(game),
                         "(0, Created)\tCat [X] cat_user_test(0, 2, 4, 6)")

        game.mouse_user = self.users[1]
        game.status = GameStatus.ACTIVE
        game.save()
        self.assertEqual(
            str(game),
            "(0, Active)\tCat [X] cat_user_test(0, 2, 4, 6) --- Mouse [ ] mouse_user_test(59)"
        )

        game.cat_turn = False
        self.assertEqual(
            str(game),
            "(0, Active)\tCat [ ] cat_user_test(0, 2, 4, 6) --- Mouse [X] mouse_user_test(59)"
        )

        game.status = GameStatus.FINISHED
        game.save()
        self.assertEqual(
            str(game),
            "(0, Finished)\tCat [ ] cat_user_test(0, 2, 4, 6) --- Mouse [X] mouse_user_test(59)"
        )
Example #4
0
def populate():
    try:
        user1 = User.objects.get(id=10)
    except User.DoesNotExist:
        user1 = User.objects.create_user(id=10, username="******")

    try:
        user2 = User.objects.get(id=11)
    except User.DoesNotExist:
        user2 = User.objects.create_user(id=11, username="******")

    game = Game(cat_user=user1)
    game.full_clean()
    game.save()

    gamelist = []
    gamelisttemp = Game.objects.all()
    for game in gamelisttemp:
        if (game.mouse_user is None):
            gamelist.append(game)
    print(gamelist)

    playedgame = min(gamelist, key=attrgetter('id'))
    playedgame.mouse_user = user2
    game.full_clean()
    game.save()
    print(playedgame)

    Move.objects.create(game=playedgame, player=user1, origin=2, target=11)
    print(playedgame)

    Move.objects.create(game=playedgame, player=user2, origin=59, target=52)
    print(playedgame)
Example #5
0
def create_game(request):

    user = request.user
    game = Game(cat_user=user)
    game.save()

    return render(request, "mouse_cat/new_game.html", {'game': game})
Example #6
0
def create_game_service(request):
    game = Game()
    game.cat_user = request.user
    game.save()
    context_dict = {}
    context_dict['game'] = game
    return render(request, 'mouse_cat/new_game.html', context_dict)
Example #7
0
 def test6(self):
     """ Juegos sin jugador 1 """
     for status in [
             GameStatus.CREATED, GameStatus.ACTIVE, GameStatus.FINISHED
     ]:
         with self.assertRaises(ValidationError):
             game = Game(mouse_user=self.users[1], status=status)
             game.full_clean()
Example #8
0
 def test2(self):
     """ OPTIONAL: If game is created with both cat user and
     mouse user then status=activated game"""
     game = Game(cat_user=self.users[0], mouse_user=self.users[1])
     game.save()
     self.assertEqual(self.get_array_positions(game), [0, 2, 4, 6, 59])
     self.assertTrue(game.cat_turn)
     self.assertEqual(game.status, GameStatus.ACTIVE)
Example #9
0
 def test6(self):
     """ It is not valid to create a game
     without the cat player"""
     for status in [GameStatus.CREATED, GameStatus.ACTIVE,
                    GameStatus.FINISHED]:
         with self.assertRaises(ValidationError):
             game = Game(mouse_user=self.users[1], status=status)
             game.full_clean()
Example #10
0
 def test2(self):
     """ Optional """
     """ Crear juego válido con dos jugadores """
     game = Game(cat_user=self.users[0], mouse_user=self.users[1])
     game.save()
     self.assertEqual(self.get_array_positions(game), [0, 2, 4, 6, 59])
     self.assertTrue(game.cat_turn)
     self.assertEqual(game.status, GameStatus.ACTIVE)
Example #11
0
def create_game(request):
    # Author: Sergio Galán
    # Creamos el juego en cuestión
    game = Game(cat_user=request.user)
    game.save()
    context_dict = {}
    # Pasamos el juego creado a la template
    context_dict['game'] = game
    return render(request, "mouse_cat/new_game.html", context_dict)
Example #12
0
 def test4(self):
     """ Comprobar que el juego se termina correctamente cuando el ratón es encerrado en un lateral"""
     game = Game(cat_user=self.users[0])
     game.full_clean()
     game.mouse_user = self.users[1]
     game.cat1 = 38
     game.cat2 = 54
     game.mouse = 47
     game.save()
     self.assertEqual(game.status, GameStatus.FINISHED)
Example #13
0
    def test9(self):
        """ Relaciones inversas entre User y Game"""
        self.assertEqual(self.users[0].games_as_cat.count(), 0)
        self.assertEqual(self.users[1].games_as_mouse.count(), 0)
        self.assertEqual(
            User.objects.filter(games_as_cat__cat_user__username=self.users[0].
                                username).count(), 0)
        self.assertEqual(
            User.objects.filter(games_as_mouse__mouse_user__username=self.
                                users[1].username).count(), 0)

        game = Game(cat_user=self.users[0], mouse_user=self.users[1])
        game.save()
        self.assertEqual(self.users[0].games_as_cat.count(), 1)
        self.assertEqual(self.users[1].games_as_mouse.count(), 1)
        self.assertEqual(
            User.objects.filter(games_as_cat__cat_user__username=self.users[0].
                                username).count(), 1)
        self.assertEqual(
            User.objects.filter(games_as_mouse__mouse_user__username=self.
                                users[1].username).count(), 1)

        game = Game(cat_user=self.users[0])
        game.save()
        self.assertEqual(self.users[0].games_as_cat.count(), 2)
        self.assertEqual(self.users[1].games_as_mouse.count(), 1)
        self.assertEqual(
            User.objects.filter(games_as_cat__cat_user__username=self.users[0].
                                username).count(), 2)
        self.assertEqual(
            User.objects.filter(games_as_mouse__mouse_user__username=self.
                                users[1].username).count(), 1)
Example #14
0
    def test0(self):
        """ Validación de la actualización del juego al ganar el gato"""
        game = Game(cat_user=self.user1)
        game.save()

        game.cat1 = 41
        game.cat2 = 50
        game.mouse = 48
        game.mouse_user = self.user2
        game.save()

        move = Move(origin=50, target=57, player=self.user1, game=game)
        move.save()

        self.assertEqual(game.status, GameStatus.FINISHED)
Example #15
0
 def test1(self):
     """ Comprobar que el juego se encuentra activo al empezar """
     game = Game(cat_user=self.users[0])
     game.full_clean()
     game.save()
     self.assertIsNone(game.mouse_user)
     self.assertTrue(game.cat_turn)
     self.assertEqual(game.status, GameStatus.CREATED)
     game.mouse_user = self.users[1]
     game.save()
     self.assertEqual(game.status, GameStatus.ACTIVE)
     self.assertEqual(self.get_array_positions(game), [0, 2, 4, 6, 59])
Example #16
0
def move(request):
    # Author: David Cabornero
    if request.method == 'POST':
        form = MoveForm(data=request.POST)
        # Comprobamos si el movimiento es válido en cuanto a rango de valores
        if form.is_valid():
            move = form.save(commit=False)
            move.player = request.user
            # Comprobamos si hay un juego seleccionado
            try:
                pk = request.session[constants.GAME_SELECTED_SESSION_ID]
                game = Game.objects.get(pk=pk)
            except KeyError:
                return JsonResponse({'valid': 0, 'winner': None})
            move.game = game
            # Comprobamos si el movimiento es completamente válido en cuanto
            # a modelo y lógica
            try:
                move.save()
            except ValidationError:
                return JsonResponse({'valid': 0, 'winner': None})
            return JsonResponse({'valid': 1, 'winner': Game.finish(game)})
        else:
            # Imprimimos los errores del formulario
            return JsonResponse({'valid': 0, 'winner': None})
    # No debería ser posible acceder a esta función mediante un método distinto
    # de POST. En caso de que ocurra, hacemos como que no lo hemos visto
    else:
        return JsonResponse({'valid': 0, 'winner': None})
Example #17
0
 def test1(self):
     """ Situaciones en las que gana el ratón por pasar a los 4 gatos """
     games = []
     games.append(Game(cat_user=self.users[0], mouse_user=self.users[1],
                       cat1=25, cat2=43, cat3=29, cat4=47, mouse=9,
                       status=GameStatus.ACTIVE))
     games.append(Game(cat_user=self.users[0], mouse_user=self.users[1],
                       cat1=9, cat2=18, cat3=13, cat4=29, mouse=4,
                       status=GameStatus.ACTIVE))
     games.append(Game(cat_user=self.users[0], mouse_user=self.users[1],
                       cat1=47, cat2=61, cat3=59, cat4=57,
                       mouse=36, status=GameStatus.ACTIVE))
     for game in games:
         game.full_clean()
         game.save()
         self.assertEqual(game.status, GameStatus.FINISHED)
         self.assertEqual(Game.finish(game), "mouse")
Example #18
0
 def test2(self):
     """ Movimientos en un juego no activo """
     game = Game(cat_user=self.users[0])
     with self.assertRaisesRegex(ValidationError, tests.MSG_ERROR_MOVE):
         Move.objects.create(game=game,
                             player=self.users[0],
                             origin=0,
                             target=9)
Example #19
0
 def test2(self):
     """ Situaciones en las que gana el ratón porque\
     los gatos se quedan sin movimientos """
     games = []
     games.append(Game(cat_user=self.users[0], mouse_user=self.users[1],
                       cat1=57, cat2=59, cat3=48, cat4=50, mouse=63,
                       status=GameStatus.ACTIVE))
     games.append(Game(cat_user=self.users[0], mouse_user=self.users[1],
                       cat1=63, cat2=61, cat3=54, cat4=47, mouse=45,
                       status=GameStatus.ACTIVE))
     games.append(Game(cat_user=self.users[0], mouse_user=self.users[1],
                       cat1=57, cat2=59, cat3=61, cat4=50, mouse=52,
                       status=GameStatus.ACTIVE))
     for game in games:
         game.full_clean()
         game.save()
         self.assertEqual(game.status, GameStatus.FINISHED)
         self.assertEqual(Game.finish(game), "mouse")
Example #20
0
 def test3(self):
     """ Situaciones en las que ganan los gatos\
     (el ratón queda acorralado) """
     games = []
     games.append(Game(cat_user=self.users[0], mouse_user=self.users[1],
                       cat1=48, cat2=50, cat3=20, cat4=36, mouse=57,
                       status=GameStatus.ACTIVE))
     games.append(Game(cat_user=self.users[0], mouse_user=self.users[1],
                       cat1=25, cat2=41, cat3=36, cat4=52, mouse=32,
                       status=GameStatus.ACTIVE))
     games.append(Game(cat_user=self.users[0], mouse_user=self.users[1],
                       cat1=27, cat2=29, cat3=43, cat4=45, mouse=36,
                       status=GameStatus.ACTIVE))
     for game in games:
         game.full_clean()
         game.save()
         self.assertEqual(game.status, GameStatus.FINISHED)
         self.assertEqual(Game.finish(game), "cat")
Example #21
0
def crear_game_vs_ia(request):
    user = request.user

    # get usuario IA o crearlo
    nombre_IA = "IA"
    password = "******"

    try:
        userIA = User.objects.get(username=nombre_IA)
    except User.DoesNotExist:
        userIA = User.objects.create_user(username=nombre_IA, password=password)
        user.save()

    # crear juego
    game = Game(cat_user=user, mouse_user=userIA, es_AI=True)
    game.save()

    return redirect(reverse('vsIA'))
    def test1(self):
        try:
            user1 = User.objects.get(id=10)
        except User.DoesNotExist:
            user1 = User.objects.create_user(id=10, username="******")
        self.assertEqual(user1.id, 10)

        try:
            user2 = User.objects.get(id=11)
        except User.DoesNotExist:
            user2 = User.objects.create_user(id=11, username="******")
        self.assertEqual(user2.id, 11)

        game = Game(cat_user=user1)
        game.full_clean()
        game.save()
        self.assertEqual(game.cat_user.id, 10)

        gamelist = []
        gamelisttemp = Game.objects.all()
        for game in gamelisttemp:
            if (game.mouse_user is None):
                gamelist.append(game)
        print(gamelist)

        playedgame = min(gamelist, key=attrgetter('id'))
        playedgame.mouse_user = user2
        game.full_clean()
        game.save()
        print(playedgame)

        move1 = Move.objects.create(game=playedgame,
                                    player=user1,
                                    origin=2,
                                    target=11)
        print(playedgame)
        self.assertEqual(game.cat2, 11)

        move2 = Move.objects.create(game=playedgame,
                                    player=user2,
                                    origin=59,
                                    target=52)
        print(playedgame)
        self.assertEqual(game.mouse, 52)
Example #23
0
    def test2(self):

        game_t = Game(
            cat_user=self.users[0],
            mouse_user=self.users[1],
            cat1=11,
            mouse=9,
            cat_turn=False)

        game_t.save()

        Move.objects.create(
            game=game_t,
            player=self.users[1],
            origin=9,
            target=0
        )

        self.assertEqual(GameStatus.FINISHED, game_t.status)
Example #24
0
 def test3(self):
     """ OPTIONAL: If mouse_user is added to a CREATED game
     then sttus became ACTIVE"""
     game = Game(cat_user=self.users[0])
     game.save()
     self.assertEqual(game.status, GameStatus.CREATED)
     game.mouse_user = self.users[1]
     game.save()
     self.assertEqual(game.status, GameStatus.ACTIVE)
Example #25
0
 def test3(self):
     """ Optional """
     """ Transición de creado a activo al añadir el segundo jugador """
     game = Game(cat_user=self.users[0])
     game.save()
     self.assertEqual(game.status, GameStatus.CREATED)
     game.mouse_user = self.users[1]
     game.save()
     self.assertEqual(game.status, GameStatus.ACTIVE)
Example #26
0
    def test1(self):

        game_t = Game(
            cat_user=self.users[0],
            mouse_user=self.users[1],
            cat1=47,
            mouse=63)

        game_t.save()


        move = Move(
            game=game_t,
            player=self.users[0],
            origin=47,
            target=54
        )

        Move.save(move)
        self.assertEqual(GameStatus.FINISHED, game_t.status)
    def test1(self):
        def get_game_id(game):
            return game.id

        """ Comprobar si existe un usuario con id=10 y si no existe crearlo """
        try:
            user = User.objects.get(id=10)
        except User.DoesNotExist:
            user = User.objects.create_user(username="******",
                                            password="******",
                                            id=10)
            self.users.append(user)
        """ Comprobar si existe un usuario con id=11 y si no existe crearlo """
        try:
            user = User.objects.get(id=11)
        except User.DoesNotExist:
            user = User.objects.create_user(username="******",
                                            password="******",
                                            id=11)
            self.users.append(user)
        """ Crear  un  juego  y  asignarselo  al  usuario  con  id=10 """
        game = Game(cat_user=User.objects.get(id=10))
        #game.full_clean()
        game.save()
        """ Buscar todos los juegos con un solo usuario asignado """
        print(game)
        oneplayergames = []
        for item in Game.objects.all():
            if item.cat_user != None:
                if item.mouse_user == None:
                    oneplayergames.append(item)
            else:
                if item.mouse_user != None:
                    oneplayergames.append(item)
        print(oneplayergames)
        """ Unir al usuario con id=11 al juego con menor id encontrado en el paso anterior y comenzar la partida """
        oneplayergames.sort(key=get_game_id)
        game = oneplayergames[0]
        game.mouse_user = User.objects.get(id=11)
        game.save()
        print(game)
        """ En la partida seleccionada, mover el segundo gato pasandolo de la posicion 2a la 11 """
        Move.objects.create(game=game,
                            player=User.objects.get(id=10),
                            origin=2,
                            target=11)
        print(game)
        """ En la partida seleccionada, mover el raton de la posicion 59 a la 52 """
        Move.objects.create(game=game,
                            player=User.objects.get(id=11),
                            origin=59,
                            target=52)
        print(game)
        """
Example #28
0
def test_query():
    # Check if there is an user with id=10 and if it does not exists, creat it
    u10 = User.objects.get_or_create(id=10, username="******")[0]
    u10.save()
    # Check if there is an user with id=11 and if it does not exists, creat it
    u11 = User.objects.get_or_create(id=11, username="******")[0]
    u11.save()
    # Create a game and assign it to the user with id=10
    game = Game(cat_user=u10)
    game.save()
    # Search for all games with only one user assigned
    # We sort it at the same time by id
    g_1u = Game.objects.filter(mouse_user=None).order_by('id')
    for g in g_1u:
        print(g)
    # Assign a second user to the game and start it
    curr_game = g_1u[0]
    curr_game.mouse_user = u11
    curr_game.save()
    print(curr_game)
    # Add moves to the game
    move1 = Move(game=curr_game,
                 origin=2,
                 target=11,
                 player=curr_game.cat_user)
    move1.save()
    # curr_game.cat2 = 11
    # curr_game.cat_turn = False
    # curr_game.save()
    print(curr_game)
    move2 = Move(game=curr_game,
                 origin=59,
                 target=52,
                 player=curr_game.mouse_user)
    move2.save()
    # curr_game.mouse = 52
    # curr_game.cat_turn = True
    # curr_game.save()
    print(curr_game)
Example #29
0
def create_game_service(request):
    """
        Funcion que crea una partida nueva y muestra una pagina avisando
        de ello.

        Parameters
        ----------
        request : HttpRequest
            Solicitud Http

        Returns
        -------
        Html : archivo html con el resultado de la creación de la partida.

        Author
        -------
            Andrés Mena
    """

    # Creamos una partida asignandosela al usuario que esta dentro del sistema
    new_game = Game(cat_user=request.user)
    new_game.save()
    return render(request, 'mouse_cat/new_game.html', {'game': new_game})
Example #30
0
 def test1(self):
     """ Crear juego válido con un único jugador """
     game = Game(cat_user=self.users[0])
     game.full_clean()
     game.save()
     self.assertIsNone(game.mouse_user)
     self.assertEqual(self.get_array_positions(game), [0, 2, 4, 6, 59])
     self.assertTrue(game.cat_turn)
     self.assertEqual(game.status, GameStatus.CREATED)