Skip to content

Commit

Permalink
t
Browse files Browse the repository at this point in the history
  • Loading branch information
muratkaanmesum committed May 11, 2024
1 parent 9158e42 commit f27d8ab
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 29 deletions.
13 changes: 9 additions & 4 deletions API/Apps/Game/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from Apps.Profile.models import Profile
from Apps.Game.matchmaking import match


from django.core.serializers.json import DjangoJSONEncoder
class MatchMakingConsumer(WebsocketConsumer):
def connect(self):
self.accept()
Expand Down Expand Up @@ -176,7 +176,7 @@ async def send_initial_state(self):
'state_type': 'initial_state',
'details': data,
'game': GameConsumer.game_states[self.game_id]
}))
}, cls=DjangoJSONEncoder))

async def send_score_state(self, event):
await self.send(text_data=json.dumps({
Expand All @@ -189,6 +189,7 @@ async def send_finish_state(self, event):
'state_type': 'finish_state',
'game': event['game'],
'winner': event['winner'],
'tournament_id': str(event['tournament_id'])
}))
await self.close()

Expand Down Expand Up @@ -296,12 +297,14 @@ async def update(self):
})
if GameConsumer.game_states[self.game_id]['player_two']['score'] >= winner_ball_count:
self.finish_game(self.player2['nickname'])
game = await self.get_game()
await self.channel_layer.group_send(
self.game_group_name,
{
'type': 'send_finish_state',
'game': GameConsumer.game_states[self.game_id],
'winner': self.player2
'winner': self.player2,
'tournament_id': str(game['tournament'])
}
)
self.stop_event.set()
Expand All @@ -325,13 +328,15 @@ async def update(self):
'dy': random.choice([-5, 5])
})
if GameConsumer.game_states[self.game_id]['player_one']['score'] >= winner_ball_count:
game = await self.get_game()
self.finish_game(self.player1['nickname'])
await self.channel_layer.group_send(
self.game_group_name,
{
'type': 'send_finish_state',
'game': GameConsumer.game_states[self.game_id],
'winner': self.player1
'winner': self.player1,
'tournament_id': str(game['tournament'])
}
)
self.stop_event.set()
Expand Down
5 changes: 3 additions & 2 deletions API/Apps/Tournament/admin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from django.contrib import admin

from Apps.Tournament.models import Tournament
from Apps.Tournament.models import Tournament, Round

# Register your models here.

admin.site.register(Tournament)
admin.site.register(Tournament)
admin.site.register(Round)
29 changes: 12 additions & 17 deletions API/Apps/Tournament/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ def check_params(self):
return True

def connect(self):
self.accept()
query_string = self.scope['query_string'].decode()
params = urllib.parse.parse_qs(query_string)

Expand All @@ -53,7 +52,9 @@ def connect(self):
self.channel_name
)
if self.check_params():
self.send_error("invalid_params")
self.close(code=1000)
return
instance = Profile.objects.get(nickname=self.nickname)
serializer = TournamentProfileSerializer(instance)
cache_key = f"user_{self.tournament_id}"
Expand All @@ -72,15 +73,17 @@ def connect(self):
"tournament_name": tournament.name,
"players": data
}
self.accept()
self.send_to_group(tournament_info, "tournament_info")

def receive(self, text_data):
data = json.loads(text_data)
print("data",data)
if data['send_type'] == 'checkMatch':
self.checkMatch(self.nickname, self.tournament_id)
elif data['send_type'] == 'start':
self.check_start_conditions()
# self.StartTournament(data)
self.StartTournament(data)

def check_start_conditions(self):
player = get_player_from_cache(f"user_{self.tournament_id}", self.nickname)
Expand All @@ -91,10 +94,6 @@ def check_start_conditions(self):
if len(players) < 3:
self.send_error("invalid_tournament")
return
for player in players:
if not player['is_ready']:
self.send_error("players_not_ready")
return

def send_error(self, error_type):
if error_type == "invalid_profile":
Expand All @@ -106,6 +105,8 @@ def send_error(self, error_type):
self.send(text_data=json.dumps({"error": "tournament_started", "message": "Tournament Already Started"}))
elif error_type == "players_not_ready":
self.send(text_data=json.dumps({"error": "players_not_ready", "message": "All players must be ready"}))
elif error_type == "invalid_params":
self.send(text_data=json.dumps({"error": "invalid_params", "message": "Something went wrong"}))

def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)(
Expand All @@ -127,11 +128,9 @@ def disconnect(self, close_code):
tournament.delete()

def StartTournament(self, data):
print(get_players_from_cache(f"user_{self.tournament_id}"))
tournament = Tournament.objects.get(id=self.tournament_id)
participants = tournament.current_participants.all()
if tournament.rounds.exists():
self.send_error("tournament_started")
return
if tournament.current_participants.count() > 2:
round_number = 1
round_obj = Round.objects.create(round_number=round_number)
Expand All @@ -153,6 +152,7 @@ def StartTournament(self, data):
return
game = Game.objects.create(player1=profile1, player2=profile2, tournament_id=self.tournament_id)
game_id = str(game.id)
game.tournament_id = self.tournament_id
player1_nick = str(profile1.nickname)
player2_nick = str(profile2.nickname)
game_info = {
Expand All @@ -168,12 +168,9 @@ def StartTournament(self, data):
print(e)

def checkMatch(self, profile_id1, tournament_id):

try:
profile_id = int(profile_id1)
except ValueError:
print("Tournament ID metin olarak beklenen türde değil.")
try:
tournament = Tournament.objects.get(pk=tournament_id)
tournament = Tournament.objects.get(pk=self.tournament_id)
last_round = tournament.rounds.order_by('-round_number').first()
except Tournament.DoesNotExist:
print("Turnuva Yok")
Expand All @@ -190,8 +187,7 @@ def checkMatch(self, profile_id1, tournament_id):

player_participated = False
for game in last_round.matches.all():
if game.player1.id == profile_id or game.player2.id == profile_id:
print(game.player1.id, game.player2.id)
if game.player1.nickname == self.nickname or game.player2.nickname == self.nickname:
player_participated = True
if game.winner is None:
game.winner = game.player2
Expand Down Expand Up @@ -221,5 +217,4 @@ def checkMatch(self, profile_id1, tournament_id):
new_round.participants.remove(winners[i])
new_round.participants.remove(winners[i + 1])
new_round.save()
print("Yeni Turnuva Oluşturuldu")
return
22 changes: 18 additions & 4 deletions API/static/scripts/game.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,12 @@ function setPlayerData(state)
}
function handleInitialState(state)
{

setCurrentPoints(state)
setPlayerData(state);
draw(state.game,"red","blue");
}
function printWinner(winner,socket){
function printWinner(data,winner,socket){
let winnerHTML = `
<div class="winner-wrapper">
<div class="winner-image-wrapper">
Expand All @@ -146,8 +147,21 @@ function printWinner(winner,socket){
document.body.appendChild(element);
setTimeout(() => {
element.remove();
loadPage("/home/");
}, 5000);
console.log(data)
if(data.tournament_id)
{
localStorage.setItem("tournament_id",data.tournament_id);
setTimeout(() => {
loadPage(`/tournament/${data.tournament_id}/`);
}, 5000);
}
else
{
setTimeout(() => {
loadPage("/home/");
}, 5000);
}
}
function printCountdown()
{
Expand Down Expand Up @@ -204,6 +218,7 @@ async function connectToServer()

socket.onmessage = async (event) => {
const data = JSON.parse(event.data);
console.log(data)
if(data.state_type === "initial_state")
{
try {
Expand All @@ -225,9 +240,8 @@ async function connectToServer()
printCountdown();
} else if (data.state_type === 'finish_state') {
draw(data.game,"red","blue");

setCurrentPoints(data);
printWinner(data.winner);
printWinner(data,data.winner);
}
else if(data.state_type === "game_state")
{
Expand Down
2 changes: 1 addition & 1 deletion API/static/scripts/spa.js
Original file line number Diff line number Diff line change
Expand Up @@ -779,7 +779,7 @@ async function tryRefreshToken() {
return;
try {

let data = await request(`token/refresh/`, {
let data = await request(`auth/token/refresh/`, {
method: 'POST',
body: JSON.stringify({
refresh: refresh_token
Expand Down
20 changes: 19 additions & 1 deletion API/static/scripts/tournament.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,22 +66,40 @@ function renderTournamentInfo(response,socket)
handleButtons(response.data.players,socket)
document.getElementById("tournament-header").innerText = response.data.tournament_name;
}
function handleGameRedirection(response)
{
for (let game of response.data)
{
if(game.players.includes(getActiveUserNickname()))
{
console.log("redirecting to game")
loadPage(`/game/${game.game_id}`)
}
}
}
function connectToSocket()
{
let errorStates = [
"invalid_profile",
"invalid_tournament",
"tournament_started",
"players_not_ready",
"invalid_params",
]
try
{
const nickname = getActiveUserNickname();
const tournamentId =window.location.pathname.split("/").filter(Boolean)[1];
const url = `${WEBSOCKET_URL}/tournament/?nickname=${nickname}&tournament_id=${tournamentId}`;
const socket = new WebSocket(url);

socket.onopen = () => {
console.log("connected to the server");
if(localStorage.getItem("tournament_id"))
{
localStorage.removeItem("tournament_id");
console.log("sending check_match")
socket.send(JSON.stringify({send_type: "checkMatch"}));
}
}
socket.onmessage = (event) => {
const response = JSON.parse(event.data);
Expand Down

0 comments on commit f27d8ab

Please sign in to comment.