added new deck gen

This commit is contained in:
Alexander Karpov 2022-07-27 01:24:47 +03:00
parent 86c35b3d02
commit 71d811100b
5 changed files with 87 additions and 50 deletions

View File

@ -6,8 +6,13 @@ BASE_DIR = Path(__file__).resolve().parent.parent
# SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-%_8sy196w4hzo9^cp9(@r=i+amh47r4mxfhq_(ok&=c(@%bhmk" SECRET_KEY = "django-insecure-%_8sy196w4hzo9^cp9(@r=i+amh47r4mxfhq_(ok&=c(@%bhmk"
TOKEN_EXP = 2678400 # 31 day
DEBUG = True 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 = [] ALLOWED_HOSTS = []

View File

@ -9,6 +9,7 @@ from django.core.validators import (
) )
from django.db import models from django.db import models
from chess_backend import settings
from common.generators import generate_charset from common.generators import generate_charset
from game.services.jwt import sign_jwt from game.services.jwt import sign_jwt
@ -39,10 +40,13 @@ class Player(models.Model):
return PlayerAuthSession.objects.get(player=self).jit return PlayerAuthSession.objects.get(player=self).jit
def get_refresh_token(self): 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): 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): def __str__(self):
return self.name return self.name
@ -129,7 +133,9 @@ class Deck(models.Model):
return self.get_heroes() return self.get_heroes()
def score(self): 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: class Meta:
db_table = "deck" db_table = "deck"

View File

@ -5,16 +5,27 @@ from game.models import Deck, Player, HeroTypes, Hero, HeroInDeck
def create_first_deck(player: Player): def create_first_deck(player: Player):
deck = Deck.objects.create(player=player) deck = Deck.objects.create(player=player)
positions = [ positions = []
[None, None, None, None, None, None, None, None],
[None, None, None, None, None, None, None, None], 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 = ( types = (
["KING", "WIZARD"] ["KING", "WIZARD"]
+ ["ARCHER" for _ in range(4)] + ["ARCHER" for _ in range(4)]
+ ["WARRIOR" for _ in range(6)] + ["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: for t in types:
hero = Hero() hero = Hero()
hero.player = player hero.player = player
@ -24,19 +35,14 @@ def create_first_deck(player: Player):
if t == "KING": if t == "KING":
pos_x = 4 pos_x = 4
pos_y = 0 pos_y = 0
positions[0][4] = hero
elif t == "WIZARD": elif t == "WIZARD":
pos_x = 3 pos_x = 3
pos_y = 0 pos_y = 0
positions[0][3] = hero
else: else:
pos_x = random.randint(0, 7) pos_x = positions[counter][0]
pos_y = random.randint(0, 1) pos_y = positions[counter][1]
while positions[pos_y][pos_x] is not None:
pos_x = random.randint(0, 7)
pos_y = random.randint(0, 1)
positions[pos_y][pos_x] = hero counter += 1
hero.health = random.randint(0, 10) hero.health = random.randint(0, 10)
hero.attack = random.randint(0, 10) hero.attack = random.randint(0, 10)

View File

@ -34,6 +34,14 @@ class QueueConsumer(BaseConsumer):
await self.accept() await self.accept()
await self.check_origin() 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) await self.channel_layer.group_add(self.room_group_name, self.channel_name)
async def disconnect(self, close_code): async def disconnect(self, close_code):
@ -116,10 +124,22 @@ class QueueConsumer(BaseConsumer):
@sync_to_async @sync_to_async
def delete_user_in_queue(self): def delete_user_in_queue(self):
try: try:
PlayerInQueue.objects.get(player_id=self.scope["player"]).delete() PlayerInQueue.objects.get(player_id=self.scope["player"])
except PlayerInQueue.DoesNotExist: except PlayerInQueue.DoesNotExist:
return False 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 @sync_to_async
def find_user_by_score(self): def find_user_by_score(self):
s_min = self.scope["score"] * 0.95 s_min = self.scope["score"] * 0.95
@ -312,7 +332,14 @@ class RoomConsumer(BaseConsumer):
return False return False
async def perform_move(self, data): 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"]: if self.scope["opponent_channel"] and self.scope["opponent_online"]:
await self.channel_layer.send( await self.channel_layer.send(
self.scope["opponent_channel"], self.scope["opponent_channel"],
@ -378,7 +405,7 @@ class RoomConsumer(BaseConsumer):
"x": event["x"], "x": event["x"],
"y": event["y"], "y": event["y"],
"px": event["px"], "px": event["px"],
"py": event["py"] "py": event["py"],
} }
) )
) )

View File

@ -1,11 +1,17 @@
from asgiref.sync import sync_to_async from asgiref.sync import sync_to_async
from termcolor import colored
from room.models import HeroInGame, Room, PlayerInRoom 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): def _check_path(f_x: int, f_y: int, x: int, y: int, room: Room, move_type: str):
if move_type == "DIAGONAL": 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": elif move_type == "HORIZONTAL":
return HeroInGame.objects.filter(room=room, x=x, y__range=(f_y, y)).count() == 0 return HeroInGame.objects.filter(room=room, x=x, y__range=(f_y, y)).count() == 0
elif move_type == "VERTICAL": elif move_type == "VERTICAL":
@ -50,42 +56,30 @@ def _validate_hero_movement(
def _print_board(room: Room): 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 y in range(1, 8):
for x in range(1, 9): for x in range(1, 9):
try: try:
hero = HeroInGame.objects.get(x=x, y=y, room=room) hero = HeroInGame.objects.get(x=x, y=y, room=room)
if hero.hero.type == "KING": if hero.hero.type == "KING":
if hero.player.first: if hero.player.first:
print("", end="") print(colored("", 'green', attrs=['bold']), end="")
else: else:
print("", end="") print(colored("", 'red', attrs=['bold']), end="")
elif hero.hero.type == "WIZARD": elif hero.hero.type == "WIZARD":
if hero.player.first: if hero.player.first:
print("", end="") print(colored("", 'green', attrs=['bold']), end="")
else: else:
print("", end="") print(colored("", 'red', attrs=['bold']), end="")
elif hero.hero.type == "ARCHER": elif hero.hero.type == "ARCHER":
if hero.player.first: if hero.player.first:
print("", end="") print(colored("", 'green', attrs=['bold']), end="")
else: else:
print("", end="") print(colored("", 'red', attrs=['bold']), end="")
else: else:
if hero.player.first: if hero.player.first:
print("", end="") print(colored("", 'green', attrs=['bold']), end="")
else: else:
print("", end="") print(colored("", 'red', attrs=['bold']), end="")
except HeroInGame.DoesNotExist: except HeroInGame.DoesNotExist:
print("*", end="") print("*", end="")
print() print()
@ -108,4 +102,3 @@ def move_handler(
h_t = hero.hero.type h_t = hero.hero.type
_print_board(room) # TODO: Remove in production _print_board(room) # TODO: Remove in production