- {% for user in users %}
-
- {{ user.nickname }}
-
-
+{% endblock %}
+{% block body %}
+
+ {% if themes %}
+
+ Играются следующие темы:
+ {% for theme in themes %}
+ {{ theme.0 }}
{% endfor %}
+
+ {% endif %}
+
+
+
+
+
+ {% for user in users %}
+
+ {{ user.nickname }}
+ 0
+
+ {% endfor %}
+
+
+
+
Открыть игровой чат
+
+
+ Игровой чат
+ Х
+
+
+
+
+
-
-
\ No newline at end of file
+{% endblock %}
\ No newline at end of file
diff --git a/dnt/games/templates/games/lobby.html b/dnt/games/templates/games/lobby.html
index cdbfdd8..c094fc3 100644
--- a/dnt/games/templates/games/lobby.html
+++ b/dnt/games/templates/games/lobby.html
@@ -1,11 +1,11 @@
+{% extends "main/base.html" %}
{% load static %}
-
-
-
-
-
Title
-
+{% block title %}Игровое лобби{% endblock %}
+{% block style %}
+
+{% endblock %}
+{% block js_first %}
-
+{% endblock %}
+{% block js_second %}
-
-
-
Ваше приглашение отклонено
-
-
Принять
-
Отклонить
-
Начать игру
-
:
-
-
{{ user.nickname }}
- {% if users %}
- {% for u in users %}
-
{{ u.nickname }}
- {% endfor %}
- {% endif %}
-
-
{{ user.current_lobby.pk }}
-
- {% for mode in modes %}
- {{ mode.1 }}
- {% endfor %}
-
-
Пригласить друга
-
- {% for friend in friends %}
- {{ friend.nickname }}
- {% endfor %}
-
-{% if theme %}
-
- {% for name in themes %}
- {{ name.0 }}
- {% endfor %}
-
-{% endif %}
-
-
\ No newline at end of file
+{% endblock %}
+{% block body %}
+
+
+ Режим игры:
+
+ {% for mode in modes %}
+ {{ mode.1 }}
+ {% endfor %}
+
+ {% if theme %}
+ Выберите тему для игры:
+
+ {% for name in themes %}
+ {{ name.0 }}
+ {% endfor %}
+
+ {% endif %}
+
+
Ваше приглашение отклонено
+
+ {% for b in blanks_left %}
+
+ {% endfor %}
+ {% for u in users_left %}
+
{{ u.nickname }}
+ {% endfor %}
+
+ {{ user.nickname }}
+
+ {% for u in users_right %}
+
{{ u.nickname }}
+ {% endfor %}
+ {% for b in blanks_right %}
+
+ {% endfor %}
+
+
+
+
Открыть чат лобби
+
+
+ Чат лобби
+ Х
+
+
+
+
+
+
+{% endblock %}
\ No newline at end of file
diff --git a/dnt/games/templates/games/results.html b/dnt/games/templates/games/results.html
index 6740f91..fc87f31 100644
--- a/dnt/games/templates/games/results.html
+++ b/dnt/games/templates/games/results.html
@@ -1,16 +1,21 @@
-
-
-
-
-
Title
-
-
-{% for result in results %}
-
- {{ result.1 }}
- {{ result.0.nickname }}
- {{ result.2 }}
-
-{% endfor %}
-
-
\ No newline at end of file
+{% extends "main/base.html" %}
+{% load static %}
+
+{% block title %}Игровое лобби{% endblock %}
+{% block style %}
+
+{% endblock %}
+{% block body %}
+
+
+ {% for result in results %}
+
+ {{ result.1 }}
+ {{ result.0.nickname }}
+ {{ result.2 }}
+
+ {% endfor %}
+
+
+
+{% endblock %}
\ No newline at end of file
diff --git a/dnt/games/urls.py b/dnt/games/urls.py
index 506e578..0ed2b7f 100644
--- a/dnt/games/urls.py
+++ b/dnt/games/urls.py
@@ -6,6 +6,7 @@
urlpatterns = [
path('lobby/', games.create_lobby, name='lobby'),
path('join_lobby/', games.join_lobby, name='join_lobby'),
+ path('join_lobby_ajax/', games.join_lobby_ajax, name='join_lobby_ajax'),
path('change_game_mode/', games.change_game_mode, name='change_game_mode'),
path('queue/', games.queue, name='queue'),
path('quit_lobby/', games.quit_lobby, name='quit_lobby'),
diff --git a/dnt/games/views.py b/dnt/games/views.py
index 16d688f..0e7dffe 100644
--- a/dnt/games/views.py
+++ b/dnt/games/views.py
@@ -16,9 +16,11 @@
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from variables import *
+from django.contrib.auth.decorators import login_required
# view страницы игрового лобби и очереди и создания игрового лобби
+@login_required
def create_lobby(request):
# создание лобби и добавление его в объект пользователя в качестве current_lobby
@@ -33,13 +35,16 @@ def create_lobby(request):
'user': current_user,
'modes': Game.types,
'max_players': GAME_MAX_PLAYERS,
- 'users': '',
- 'friends': AuthUser.objects.filter(pk__in=current_user.friends.values_list('pk'))
+ 'users_left': [],
+ 'users_right': [],
+ 'blanks_left': range(math.floor((GAME_MAX_PLAYERS - 1) / 2)),
+ 'blanks_right': range(math.ceil((GAME_MAX_PLAYERS - 1) / 2)),
}
+
return render(request, 'games/lobby.html', context=context)
-def join_lobby(request):
+def join_lobby_ajax(request):
sender = AuthUser.objects.get(pk=int(request.GET.get('sender_id')))
lobby = Lobby.objects.get(pk=sender.current_lobby.pk)
@@ -49,7 +54,7 @@ def join_lobby(request):
current_user.current_lobby = lobby
current_user.is_lobby_leader = False
current_user.save()
- friends = [x[0] for x in current_user.friends.values_list('pk') if x not in [player.pk for player in lobby.players.all()]]
+ # friends = [x[0] for x in current_user.friends.values_list('pk') if x not in [player.pk for player in lobby.players.all()]]
last_place = True if current_user.current_lobby.players_count == GAME_MAX_PLAYERS else False
data = {'action': 'player_join', 'joiner_pk': current_user.pk, 'joiner_nickname': current_user.nickname,
@@ -58,22 +63,36 @@ def join_lobby(request):
for user in AuthUser.objects.filter(current_lobby=current_user.current_lobby).exclude(pk=current_user.pk):
async_to_sync(layer.group_send)(f'user_{user.pk}', {'type': 'send_message', 'message': data})
- theme = True if eval(lobby.type)[0] == 'theme' else False
+ return JsonResponse({'status': 'ok', 'url': 'http://' + request.META['HTTP_HOST'] + '/games/join_lobby/'})
+ else:
+ return JsonResponse({'status': 'full'})
+
- context = {
- 'title': 'Игровое лобби',
- 'user': current_user,
- 'modes': Game.types,
- 'max_players': GAME_MAX_PLAYERS,
- 'users': AuthUser.objects.filter(current_lobby=lobby).exclude(pk=current_user.pk),
- 'friends': friends,
- 'theme': theme,
- 'themes': Category.objects.all().values_list('name')
- }
+@login_required
+def join_lobby(request):
- return HttpResponse(render_to_string('games/lobby.html', context=context))
- else:
- return HttpResponse('full')
+ current_user = request.user
+ current_lobby = current_user.current_lobby
+
+ theme = True if eval(current_lobby.type)[0] == 'theme' else False
+
+ users_left = [j for i, j in enumerate(AuthUser.objects.filter(current_lobby=current_lobby).exclude(pk=current_user.pk)) if (i + 1) % 2 == 0]
+ users_right = [j for i, j in enumerate(AuthUser.objects.filter(current_lobby=current_lobby).exclude(pk=current_user.pk)) if (i + 1) % 2 == 1]
+
+ context = {
+ 'title': 'Игровое лобби',
+ 'user': current_user,
+ 'modes': Game.types,
+ 'max_players': GAME_MAX_PLAYERS,
+ 'users_left': users_left,
+ 'users_right': users_right,
+ 'blanks_left': range(math.floor((GAME_MAX_PLAYERS - 1) / 2) - len(users_left)),
+ 'blanks_right': range(math.ceil((GAME_MAX_PLAYERS - 1) / 2) - len(users_right)),
+ 'theme': theme,
+ 'themes': Category.objects.all().values_list('name')
+ }
+
+ return render(request, 'games/lobby.html', context=context)
def change_game_mode(request):
@@ -175,7 +194,7 @@ def quit_lobby(request):
current_user = request.user
# если пользователь в лобби один, лобби удаляется, если нет - лобби убирается из current_lobby объекта пользователя
- if current_user.current_lobby and current_user.current_lobby.players_count == 1:
+ if current_user.current_lobby is not None and current_user.current_lobby.players_count == 1:
current_user.current_lobby.delete()
elif current_user.current_lobby is not None:
data = {'action': 'player_quit', 'quitter_pk': current_user.pk, 'quitter_nickname': current_user.nickname,
@@ -219,6 +238,7 @@ def cancel_queue(request):
# view страницы игры
+@login_required
def game(request):
context = {
@@ -247,7 +267,7 @@ def start_game(request):
for _ in range(questions_count):
# получение случайного вопроса, которого не было в игре, и добавление его в объект игры в current_question
- questions = Question.objects.exclude(pk__in=current_game.asked_questions.values_list('pk'))
+ questions = Question.objects.exclude(pk__in=current_game.asked_questions.values_list('pk')).filter(is_validated=True)
current_game = Game.objects.get(pk=request.user.current_game.pk)
if eval(current_game.type)[0] in ['theme', 'friend']:
questions = questions.filter(category__pk__in=current_game.categories.values_list('pk'))
@@ -260,7 +280,7 @@ def start_game(request):
# попытка получить нужное количество неправильных ответов того же подтипа, что и верный
first_answers = Answer.objects.filter(
- Q(subtype=question.answer.subtype) & ~Q(pk=question.answer.pk)
+ Q(subtype=question.answer.subtype) & ~Q(pk=question.answer.pk) & Q(is_validated=True)
).order_by('?')[:GAME_SUBTYPE_ANSWERS_COUNT]
# компенсация возможного недостатка неправильных ответов того же подтипа неправильными ответами того же типа
@@ -268,10 +288,10 @@ def start_game(request):
type_answers_count += GAME_SUBTYPE_ANSWERS_COUNT - len(first_answers)
# получение необходимого количества неправильных ответов того же типа
- type_answers = Answer.objects.exclude(subtype=question.answer.subtype).order_by('?')[:type_answers_count]
+ type_answers = Answer.objects.filter(is_validated=True).exclude(subtype=question.answer.subtype).order_by('?')[:type_answers_count]
# преобразование всех нужных ответов в список словарей и перемешивание их
- answers = first_answers | Answer.objects.filter(pk=question.answer.pk) | type_answers
+ answers = first_answers | Answer.objects.filter(pk=question.answer.pk, is_validated=True) | type_answers
answers = list(answers.values())
random.shuffle(answers)
@@ -399,6 +419,7 @@ def check_answer(request):
# view страницы результатов игры
+@login_required
def results(request, game_id):
# получение объекта нужной игры и всех её игроков
diff --git a/dnt/json/answers.json b/dnt/json/answers.json
index 54ebcfd..fa581ba 100644
--- a/dnt/json/answers.json
+++ b/dnt/json/answers.json
@@ -1,70 +1,87 @@
[
{
"answer": "Губка Боб Квадратные Штаны",
- "subtype": "Персонаж мультфильма"
+ "subtype": "Персонаж мультфильма",
+ "is_validated": true
},
{
"answer": "Анна Франк",
- "subtype": "Историческая личность"
+ "subtype": "Историческая личность",
+ "is_validated": true
},
{
"answer": "Джон Мильтон",
- "subtype": "Поэт"
+ "subtype": "Поэт",
+ "is_validated": true
},
{
"answer": "Император Хирохито",
- "subtype": "Политический деятель"
+ "subtype": "Политический деятель",
+ "is_validated": true
},
{
"answer": "Харрисон Форд",
- "subtype": "Актёр"
+ "subtype": "Актёр",
+ "is_validated": true
},
{
"answer": "Хэлли Берри",
- "subtype": "Актриса"
+ "subtype": "Актриса",
+ "is_validated": true
},
{
"answer": "Мухаммед Али",
- "subtype": "Боксёр"
+ "subtype": "Боксёр",
+ "is_validated": true
},
{
"answer": "Харпер Ли",
- "subtype": "Писательница"
+ "subtype": "Писательница",
+ "is_validated": true
},
{
"answer": "Галилео Галилей",
- "subtype": "Учёный"
+ "subtype": "Учёный",
+ "is_validated": true
},
{
"answer": "Мари Кюри",
- "subtype": "Учёная"
+ "subtype": "Учёная",
+ "is_validated": true
},
{
"answer": "Нил Армстронг",
- "subtype": "Космонавт"
+ "subtype": "Космонавт",
+ "is_validated": true
},
{
"answer": "Рианна",
- "subtype": "Певица"
+ "subtype": "Певица",
+ "is_validated": true
},
{
"answer": "Куинси Джонс",
- "subtype": "Продюсер"
+ "subtype": "Продюсер",
+ "is_validated": true
},
{
"answer": "Джордж Р. Р. Мартин",
- "subtype": "Писатель"
+ "subtype": "Писатель",
+ "is_validated": true
},
{
"answer": "Гена",
- "subtype": "Персонаж мультфильма"
+ "subtype": "Персонаж мультфильма",
+ "is_validated": true
},
{
"answer": "Кот Матроскин",
- "subtype": "Персонаж мультфильма"
+ "subtype": "Персонаж мультфильма",
+ "is_validated": true
},
{
"answer": "Джон Сноу",
- "subtype": "Персонаж телесериала"
+ "subtype": "Персонаж телесериала",
+ "is_validated": true
}
]
\ No newline at end of file
diff --git a/dnt/main/management/commands/fill.py b/dnt/main/management/commands/fill.py
index fa456fd..84941a1 100644
--- a/dnt/main/management/commands/fill.py
+++ b/dnt/main/management/commands/fill.py
@@ -43,18 +43,12 @@ def handle(self, *args, **options):
question['answer'] = Answer.objects.get(answer=question['answer'])
Question.objects.create(**question)
- try:
- AuthUser.objects.get(username='pepper').delete()
- except:
- pass
+ AuthUser.objects.all().delete()
+
AuthUser.objects.create_superuser(username='pepper', password='pepper123', nickname='pepper',
birthdate='2019-01-01', is_moderator=True)
for i in range(2, 10):
- try:
- AuthUser.objects.get(username=f'pepper{i}').delete()
- except:
- pass
AuthUser.objects.create_superuser(username=f'pepper{i}', password='pepper123', nickname=f'pepper{i}',
birthdate='2019-01-01')
diff --git a/dnt/main/templates/main/base.html b/dnt/main/templates/main/base.html
index fb90254..a87ba3c 100644
--- a/dnt/main/templates/main/base.html
+++ b/dnt/main/templates/main/base.html
@@ -7,17 +7,18 @@
{% block title %}{% endblock %}
{% block style %}{% endblock %}
- {% block js %}{% endblock %}
+
+
+ {% block js_first %}{% endblock %}
+
+ {% block js_second %}{% endblock %}
{% block header %}
{% include "main/includes/header.html" %}
{% endblock %}
-
-
- Принять
- Отклонить
-
{% block body %}{% endblock %}
@@ -26,5 +27,15 @@
{% include "main/includes/footer.html" %}
{% endblock %}
+