From 71d811100b7cee614a24ab116381fe59070b339b Mon Sep 17 00:00:00 2001 From: Alexander-D-Karpov Date: Wed, 27 Jul 2022 01:24:47 +0300 Subject: [PATCH] added new deck gen --- chess_backend/settings.py | 7 ++++- game/models.py | 12 ++++++-- game/services/deck_handler.py | 32 ++++++++++++--------- room/consumers.py | 33 ++++++++++++++++++++-- room/services/game_logic.py | 53 +++++++++++++++-------------------- 5 files changed, 87 insertions(+), 50 deletions(-) diff --git a/chess_backend/settings.py b/chess_backend/settings.py index f74280c..a426581 100644 --- a/chess_backend/settings.py +++ b/chess_backend/settings.py @@ -6,8 +6,13 @@ BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-%_8sy196w4hzo9^cp9(@r=i+amh47r4mxfhq_(ok&=c(@%bhmk" -TOKEN_EXP = 2678400 # 31 day DEBUG = True +if DEBUG: + TOKEN_EXP = 31536000 # 1 year + AUTH_EXP = 31536000 # 1 year +else: + TOKEN_EXP = 2678400 # 1 month + AUTH_EXP = 3600 # 1 hour ALLOWED_HOSTS = [] diff --git a/game/models.py b/game/models.py index d6bf2e4..bc2add5 100644 --- a/game/models.py +++ b/game/models.py @@ -9,6 +9,7 @@ from django.core.validators import ( ) from django.db import models +from chess_backend import settings from common.generators import generate_charset from game.services.jwt import sign_jwt @@ -39,10 +40,13 @@ class Player(models.Model): return PlayerAuthSession.objects.get(player=self).jit def get_refresh_token(self): - return sign_jwt({"jit": self.get_auth_session(), "type": "refresh"}) + return sign_jwt( + {"jit": self.get_auth_session(), "type": "refresh"}, + t_life=settings.TOKEN_EXP, + ) def get_access_token(self): - return sign_jwt({"id": self.id, "type": "access"}, t_life=3600) + return sign_jwt({"id": self.id, "type": "access"}, t_life=settings.AUTH_EXP) def __str__(self): return self.name @@ -129,7 +133,9 @@ class Deck(models.Model): return self.get_heroes() def score(self): - return sum([x.hero.attack + x.hero.health + x.hero.speed for x in self.get_heroes()]) + return sum( + [x.hero.attack + x.hero.health + x.hero.speed for x in self.get_heroes()] + ) class Meta: db_table = "deck" diff --git a/game/services/deck_handler.py b/game/services/deck_handler.py index 0b89104..82b0ba6 100644 --- a/game/services/deck_handler.py +++ b/game/services/deck_handler.py @@ -5,16 +5,27 @@ from game.models import Deck, Player, HeroTypes, Hero, HeroInDeck def create_first_deck(player: Player): deck = Deck.objects.create(player=player) - positions = [ - [None, None, None, None, None, None, None, None], - [None, None, None, None, None, None, None, None], - ] + positions = [] + + for x in range(8): + for y in range(2): + if (x != 3 and y != 0) or (x != 4 and y != 0): + positions.append((x, y)) + print(positions) + random.shuffle(positions) + types = ( ["KING", "WIZARD"] + ["ARCHER" for _ in range(4)] + ["WARRIOR" for _ in range(6)] - + [random.choice(HeroTypes.choices[:2])[0] for _ in range(3)] ) + for _ in range(4): + t = random.choice(HeroTypes.choices[:3])[0] + if t == "WIZARD" and types.count("WIZARD") > 1: + t = random.choice(HeroTypes.choices[:2])[0] + types.append(t) + + counter = 0 for t in types: hero = Hero() hero.player = player @@ -24,19 +35,14 @@ def create_first_deck(player: Player): if t == "KING": pos_x = 4 pos_y = 0 - positions[0][4] = hero elif t == "WIZARD": pos_x = 3 pos_y = 0 - positions[0][3] = hero else: - pos_x = random.randint(0, 7) - pos_y = random.randint(0, 1) - while positions[pos_y][pos_x] is not None: - pos_x = random.randint(0, 7) - pos_y = random.randint(0, 1) + pos_x = positions[counter][0] + pos_y = positions[counter][1] - positions[pos_y][pos_x] = hero + counter += 1 hero.health = random.randint(0, 10) hero.attack = random.randint(0, 10) diff --git a/room/consumers.py b/room/consumers.py index b20aee4..7728faa 100644 --- a/room/consumers.py +++ b/room/consumers.py @@ -34,6 +34,14 @@ class QueueConsumer(BaseConsumer): await self.accept() await self.check_origin() + if await self.check_user_already_in_room(): + await self.send_message( + "INFO", + message=f"user already in room {self.scope['room_id']}", + room=self.scope["room"], + ) + await self.close() + await self.channel_layer.group_add(self.room_group_name, self.channel_name) async def disconnect(self, close_code): @@ -116,10 +124,22 @@ class QueueConsumer(BaseConsumer): @sync_to_async def delete_user_in_queue(self): try: - PlayerInQueue.objects.get(player_id=self.scope["player"]).delete() + PlayerInQueue.objects.get(player_id=self.scope["player"]) except PlayerInQueue.DoesNotExist: return False + @sync_to_async + def check_user_already_in_room(self): + try: + p = PlayerInRoom.objects.get(player_id=self.scope["player"]) + + self.scope["room"] = p.room.slug + self.scope["room_id"] = p.room.id + + return True + except PlayerInRoom.DoesNotExist: + return False + @sync_to_async def find_user_by_score(self): s_min = self.scope["score"] * 0.95 @@ -312,7 +332,14 @@ class RoomConsumer(BaseConsumer): return False async def perform_move(self, data): - await move_handler(data["px"], data["py"], data["x"], data["y"], self.room_name, self.scope["player_in_room"]) + await move_handler( + data["px"], + data["py"], + data["x"], + data["y"], + self.room_name, + self.scope["player_in_room"], + ) if self.scope["opponent_channel"] and self.scope["opponent_online"]: await self.channel_layer.send( self.scope["opponent_channel"], @@ -378,7 +405,7 @@ class RoomConsumer(BaseConsumer): "x": event["x"], "y": event["y"], "px": event["px"], - "py": event["py"] + "py": event["py"], } ) ) diff --git a/room/services/game_logic.py b/room/services/game_logic.py index f00e02d..7166c25 100644 --- a/room/services/game_logic.py +++ b/room/services/game_logic.py @@ -1,11 +1,17 @@ from asgiref.sync import sync_to_async +from termcolor import colored from room.models import HeroInGame, Room, PlayerInRoom def _check_path(f_x: int, f_y: int, x: int, y: int, room: Room, move_type: str): if move_type == "DIAGONAL": - return HeroInGame.objects.filter(room=room, x__range=(f_x, x), y__range=(f_y, y)).count() == 0 + return ( + HeroInGame.objects.filter( + room=room, x__range=(f_x, x), y__range=(f_y, y) + ).count() + == 0 + ) elif move_type == "HORIZONTAL": return HeroInGame.objects.filter(room=room, x=x, y__range=(f_y, y)).count() == 0 elif move_type == "VERTICAL": @@ -14,13 +20,13 @@ def _check_path(f_x: int, f_y: int, x: int, y: int, room: Room, move_type: str): def _validate_hero_movement( - hero_type: str, - prev_x: int, - prev_y: int, - x: int, - y: int, - room: Room, - first: bool = False, # needed for warrior + hero_type: str, + prev_x: int, + prev_y: int, + x: int, + y: int, + room: Room, + first: bool = False, # needed for warrior ): if hero_type == "KING": if abs(x - prev_x) > 1 or abs(y - prev_y) > 1: @@ -50,42 +56,30 @@ def _validate_hero_movement( def _print_board(room: Room): - class color: - PURPLE = '\033[95m' - CYAN = '\033[96m' - DARKCYAN = '\033[36m' - BLUE = '\033[94m' - GREEN = '\033[92m' - YELLOW = '\033[93m' - RED = '\033[91m' - BOLD = '\033[1m' - UNDERLINE = '\033[4m' - END = '\033[0m' - for y in range(1, 8): for x in range(1, 9): try: hero = HeroInGame.objects.get(x=x, y=y, room=room) if hero.hero.type == "KING": if hero.player.first: - print("♔", end="") + print(colored("♔", 'green', attrs=['bold']), end="") else: - print("♚", end="") + print(colored("♚", 'red', attrs=['bold']), end="") elif hero.hero.type == "WIZARD": if hero.player.first: - print("♕", end="") + print(colored("♕", 'green', attrs=['bold']), end="") else: - print("♛", end="") + print(colored("♛", 'red', attrs=['bold']), end="") elif hero.hero.type == "ARCHER": if hero.player.first: - print("♗", end="") + print(colored("♗", 'green', attrs=['bold']), end="") else: - print("♝", end="") + print(colored("♝", 'red', attrs=['bold']), end="") else: if hero.player.first: - print("♙", end="") + print(colored("♙", 'green', attrs=['bold']), end="") else: - print("♟", end="") + print(colored("♟", 'red', attrs=['bold']), end="") except HeroInGame.DoesNotExist: print("*", end="") print() @@ -93,7 +87,7 @@ def _print_board(room: Room): @sync_to_async def move_handler( - prev_x: int, prev_y: int, x: int, y: int, room_slug: str, player: PlayerInRoom + prev_x: int, prev_y: int, x: int, y: int, room_slug: str, player: PlayerInRoom ): room = Room.objects.get(slug=room_slug) _print_board(room) # TODO: Remove in production @@ -108,4 +102,3 @@ def move_handler( h_t = hero.hero.type _print_board(room) # TODO: Remove in production -