Skip to content

Commit

Permalink
Merge pull request #328 from zstenger93/test
Browse files Browse the repository at this point in the history
Test
  • Loading branch information
zstenger93 authored Apr 28, 2024
2 parents 5247d39 + 72c0d8a commit c7f91a5
Show file tree
Hide file tree
Showing 22 changed files with 314 additions and 455 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ backend/authentication/images/*
media
node_modules

backend/qrcode*

#ssl_keys
*.crt
*.key
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ all:

runb:
daphne -b 0.0.0.0 backend.asgi:application
# http://10.12.2.4:8000/chat/
# http://10.12.2.2:8000/chat/


execbackend:
Expand Down
39 changes: 19 additions & 20 deletions backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,19 @@
# SECURITY WARNING: don't run with debug turned on in production!

ALLOWED_HOSTS = [
'*',
'localhost',
'10.12.2.2',
'172.19.0.4',
'127.0.0.1',
'0.0.0.0',
'10.13.7.5',
'transcendence-backend-znhl.onrender.com',
'https://transcendence-frontend-3otz.onrender.com'
]
"*",
"localhost",
"10.12.2.2",
"172.19.0.4",
"127.0.0.1",
"0.0.0.0",
"10.13.7.5",
"transcendence-backend-znhl.onrender.com",
"https://transcendence-frontend-3otz.onrender.com",
]

# Authentication settings
if DEBUG == 'True':
if DEBUG == "True":
REDIRECT_URI = "https://10.12.2.2"
else:
REDIRECT_URI = "https://transcendence-backend-znhl.onrender.com"
Expand Down Expand Up @@ -76,23 +76,22 @@
"whitenoise.middleware.WhiteNoiseMiddleware",
]
CSRF_ALLOWED_ORIGINS = [

"https://10.12.2.2",
"https://api.intra.42.fr",
"https://api.intra.42.fr",
"http://localhost:3000",
"http://frontend:3000",
"https://transcendence-frontend-3otz.onrender.com",
"https://zstenger93.github.io",
]

CORS_ALLOWED_ORIGINS = [
"http://frontend:3000",
"https://api.intra.42.fr",
"https://10.12.2.2",
"http://localhost:3000",
"https://transcendence-frontend-3otz.onrender.com",
"https://zstenger93.github.io"
]
"http://frontend:3000",
"https://api.intra.42.fr",
"https://10.12.2.2",
"http://localhost:3000",
"https://transcendence-frontend-3otz.onrender.com",
"https://zstenger93.github.io",
]

CORS_ALLOW_CREDENTIALS = True
# CORS_ORIGIN_ALLOW_ALL = True
Expand Down
2 changes: 0 additions & 2 deletions backend/backend/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,5 @@
path('admin/', admin.site.urls),
path('api/', include('user_api.urls')),
path('api/', include('friendship_api.urls')),
# path('api/', include('friendship.urls')),
path('chat/', include('chat.urls')),
path('game/', include('game.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
37 changes: 3 additions & 34 deletions backend/game/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,7 @@
import math

from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
from channels.exceptions import StopConsumer
from rest_framework.request import Request
import secrets
import string


## The consumer will be responsible for handling the game logic and updating the game state(websockets)
def generate_random_string(length):
characters = string.ascii_letters + string.digits + "_"
random_string = "".join(secrets.choice(characters) for _ in range(length))
return random_string


import logging
Expand Down Expand Up @@ -90,7 +79,6 @@ async def receive(self, text_data):
cmd = str(game_event[:2])
userid = int(game_event[2:])
# if connected client < 2, then create a new game instance
logger.info(f"connected clientssssssss: {self.connected_clients}")
if (
self.room_name not in self.connected_clients
and len(self.connected_clients) < 2
Expand All @@ -100,12 +88,9 @@ async def receive(self, text_data):
self.users[self.room_name][1] = self.scope["user"]
self.game_instance = self.connected_clients[self.room_name]

logger.info(f"ccccccconnected clients: {self.connected_clients}")
await self.handleInput(cmd, userid)

async def handleInput(self, cmd, userid):
logger.info(f"users in room: {self.users[self.room_name]}")
logger.info(f"User {userid} sent command: {cmd}")
if cmd == "pw" and userid == self.user_ids[self.room_name][0]:
await self.game_instance.move_p0_up("press")
elif cmd == "ps" and userid == self.user_ids[self.room_name][0]:
Expand All @@ -130,14 +115,13 @@ async def disconnect(self, close_code):
if not self.connected_users:
self.game_state = {}
self.connected_clients = {}
# self.game_instance = None
self.game_instance = None
self.game_tasks = {}
# self.connected_users = set()
self.connected_users = set()

await self.channel_layer.group_discard(self.room_group_name, self.channel_name)

async def startGame(self):
logger.info(f"Game loop started status: {self.game_state[self.room_name]}")
self.game_state[self.room_name] = "starting"
await self.send_game_state_to_clients()
if self.room_name in self.connected_clients:
Expand Down Expand Up @@ -165,7 +149,6 @@ async def gameLoop(self):
await self.send_game_end()

async def send_game_end(self):
game_tag = generate_random_string(20)
await self.channel_layer.group_send(
self.room_group_name,
{
Expand All @@ -176,7 +159,6 @@ async def send_game_end(self):
"room_name": self.room_name,
"game_state": self.game_state.get(self.room_name),
"users": [str(user) for user in self.users.get(self.room_name)],
"game_tag": game_tag,
},
)

Expand All @@ -192,7 +174,6 @@ async def ending_message(self, event):
"game_state": event["game_state"],
"users": event["users"],
"user_ids": self.user_ids.get(self.room_name),
"game_tag": event["game_tag"],
}
)
)
Expand Down Expand Up @@ -244,18 +225,6 @@ async def game_message(self, event):
)
)

@database_sync_to_async
def get_room(self, room_name):
from game.models import GameRoom

return GameRoom.objects.get(name=room_name)

@database_sync_to_async
def get_all_user_channel_names(self):
from .models import UserChannelName

return list(UserChannelName.objects.values("user__username"))


class GameInstance:
def __init__(self):
Expand Down Expand Up @@ -320,7 +289,7 @@ async def update_game(self, game_state, room_name, user0, user1):
0, min(self.canvas_height - self.paddle_height, self.player1)
)
await self.update_ball_position(game_state, room_name, user0, user1)
self.score = f"{self.player0_score} : {self.player1_score}"
self.score = f"{self.player1_score} : {self.player0_score}"
self.ball_speed = math.sqrt(self.ball_speed_x**2 + self.ball_speed_y**2)

async def update_ball_position(self, game_state, room_name, user0, user1):
Expand Down
16 changes: 16 additions & 0 deletions backend/game/migrations/0003_delete_userchannelname.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Generated by Django 5.0 on 2024-04-28 03:33

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
('game', '0002_remove_gamestats_game_history_remove_gamestats_user_and_more'),
]

operations = [
migrations.DeleteModel(
name='UserChannelName',
),
]
38 changes: 13 additions & 25 deletions backend/game/models.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@

from django.db import models
from django.conf import settings
from django.core.serializers import serialize
import json

# Create your models here.

class GameRoom(models.Model):
name = models.CharField(max_length=255)
user1 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="game_user1", null=True)
user2 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="game_user2", null=True)
user1 = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="game_user1",
null=True,
)
user2 = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="game_user2",
null=True,
)
online = models.ManyToManyField(to=settings.AUTH_USER_MODEL, blank=True)

def __str__(self):
Expand All @@ -18,22 +25,3 @@ class Meta:
verbose_name = "Game Room"
verbose_name_plural = "Game Rooms"



class UserChannelName(models.Model):
AppUser = settings.AUTH_USER_MODEL
user = models.OneToOneField(AppUser, on_delete=models.CASCADE, related_name='game_channel_name')
channel_name = models.CharField(max_length=100)

def update_channel_name(self, channel_name):
self.channel_name = channel_name
self.save()

def delete_channel_name(self):
self.delete()

class Meta:
unique_together = ('user', 'channel_name',)

def __str__(self):
return self.user.username + ' ' + self.channel_name
24 changes: 11 additions & 13 deletions backend/game/test.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,29 @@
// const websocketUrl = 'ws://40.13.7.8:8000/game/asdfasdf/';
const websocketUrl = 'wss://10.12.2.4/chat/';

const websocketUrl = "wss://10.12.2.2/chat/";

// Create a new WebSocket instance
const websocket = new WebSocket(websocketUrl);

// Event listener for WebSocket connection open
websocket.onopen = function(event) {
console.log('WebSocket connection opened.');
websocket.onopen = function (event) {
console.log("WebSocket connection opened.");

// Sending a test message to the server
websocket.send(JSON.stringify({ message: 'Hello from the client!' }));
websocket.send(JSON.stringify({ message: "Hello from the client!" }));
};

// Event listener for WebSocket messages received
websocket.onmessage = function(event) {
console.log('Message received from server:', event.data);
websocket.onmessage = function (event) {
console.log("Message received from server:", event.data);
// You can add further processing of the received message here
};

// Event listener for WebSocket errors
websocket.onerror = function(error) {
console.error('WebSocket error:', error);
websocket.onerror = function (error) {
console.error("WebSocket error:", error);
};

// Event listener for WebSocket connection close
websocket.onclose = function(event) {
console.log('WebSocket connection closed.');
websocket.onclose = function (event) {
console.log("WebSocket connection closed.");
};

8 changes: 0 additions & 8 deletions backend/game/urls.py

This file was deleted.

75 changes: 0 additions & 75 deletions backend/game/views.py
Original file line number Diff line number Diff line change
@@ -1,75 +0,0 @@
from .models import *
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .models import *
from user_api.models import AppUser
from django.shortcuts import get_object_or_404
from django.http.response import JsonResponse
from django.views.decorators.http import require_GET, require_POST
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from .consumers import GameConsumer

from django.contrib.sessions.models import Session
from django.contrib.auth.models import User

import string
import random
import json
import logging
from django.http import JsonResponse
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync


def get_user_from_session(session_key):
session = Session.objects.get(session_key=session_key)
user_id = session.get_decoded().get("_auth_user_id")
user = User.objects.get(id=user_id)
return user


logger = logging.getLogger(__name__)

# Then, instead of print, use logger.info (or logger.debug, logger.warning, etc.)


def generate_random_lobby_name(length=10):
# Generate a random string of the given length
lobby_name = "".join(
random.choice(string.ascii_letters + string.digits) for _ in range(length)
)
return lobby_name


def my_handler(message):
user_id = message.get("user_id")
room_name = message.get("room_name")
print(f"User {user_id} joined room {room_name}")


def end_game(request):
lobby_info = request.GET.get("gameinfo", None)
score_board = lobby_info.split(" ")
winner_score = score_board[0]
user1_id = score_board[1]
user2_id = score_board[3]
loser_score = score_board[4]
logger.info(f"Game ended with score: {score_board}")
user1 = get_object_or_404(AppUser, id=user1_id)
user2 = get_object_or_404(AppUser, id=user2_id)

logger.info(f"Game ended with score: {score_board}")

return JsonResponse(
{
"winner": user1,
"score": winner_score,

"loser": user2,
"scoree": loser_score,
}
)


# id1 score1 id2 score2
Binary file added backend/qrcode.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit c7f91a5

Please sign in to comment.