Skip to content

Commit

Permalink
Merge pull request #70 from bertt6/front-fix
Browse files Browse the repository at this point in the history
Tournament Finished
  • Loading branch information
muratkaanmesum authored May 12, 2024
2 parents b336948 + d81b6c7 commit 413bcd4
Show file tree
Hide file tree
Showing 10 changed files with 172 additions and 87 deletions.
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 16 additions & 8 deletions API/Apps/Game/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@
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()
self.profile = ProfileGetSerializer(Profile.objects.get(nickname=self.scope['url_route']['kwargs']['nickname'])).data
self.profile = ProfileGetSerializer(
Profile.objects.get(nickname=self.scope['url_route']['kwargs']['nickname'])).data
async_to_sync(self.channel_layer.group_add)(
'player-%s' %self.profile['nickname'],
'player-%s' % self.profile['nickname'],
self.channel_name
)
add_player_in_que(self.profile)
Expand Down Expand Up @@ -176,7 +179,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 +192,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 @@ -240,7 +244,7 @@ async def update(self):
paddle_height = 200
ball_speed = 1.0006

winner_ball_count = 5
winner_ball_count = 1

player1_score = GameConsumer.game_states[self.game_id]['player_one']['score']
player2_score = GameConsumer.game_states[self.game_id]['player_two']['score']
Expand Down Expand Up @@ -295,13 +299,15 @@ async def update(self):
'dy': random.choice([-5, 5])
})
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.finish_game(self.player2['nickname'])
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 +331,15 @@ async def update(self):
'dy': random.choice([-5, 5])
})
if GameConsumer.game_states[self.game_id]['player_one']['score'] >= winner_ball_count:
self.finish_game(self.player1['nickname'])
game = await self.get_game()
await 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)
2 changes: 1 addition & 1 deletion API/Apps/Tournament/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
path('profile/<int:profile_id>', create),
path('<int:profile_id>/<uuid:tournament_id>', get_tournaments),
path('join/<int:tournament_id>', join),
path('delete/<int:tournament_id>', delete),
path('delete/<uuid:tournament_id>', delete),
path('profile/w/<str:nickname>/', websocket_test)

]
Expand Down
56 changes: 31 additions & 25 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,12 +52,19 @@ def connect(self):
self.channel_name
)
if self.check_params():
self.send_error("invalid_params")
self.close(code=1000)
return
self.accept()
instance = Profile.objects.get(nickname=self.nickname)
serializer = TournamentProfileSerializer(instance)
cache_key = f"user_{self.tournament_id}"
created_by = False
tournament = Tournament.objects.get(id=self.tournament_id)
if tournament.is_finished:
self.send_error("tournament_finished")
self.close(code=1000)
return
if tournament.created_by == instance:
created_by = True
data = add_player_to_cache(serializer.data, cache_key, created_by)
Expand All @@ -76,11 +82,12 @@ def connect(self):

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 +98,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,7 +109,10 @@ 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"}))
elif error_type == "tournament_finished":
self.send(text_data=json.dumps({"error": "tournament_finished", "message": "Tournament is finished"}))
def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
Expand All @@ -129,9 +135,6 @@ def disconnect(self, close_code):
def StartTournament(self, data):
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 +156,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 @@ -169,11 +173,7 @@ def StartTournament(self, data):

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,36 +190,42 @@ 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
game.save()
print("Maçı Player 2 kazandı")
return

if last_round.matches.count() == 1 and not last_round.participants.exists() and last_round.matches.first().winner:
game = last_round.matches.first()
tournament.winner = game.winner
tournament.is_finished = True
tournament.save()
self.send_to_group({"winner": game.winner.nickname, "profile_picture": game.winner.profile_picture.url},
"tournament_finished")
if not player_participated:
print("Player Maclarda Yok")
return

winners = [game.winner for game in last_round.matches.all()]
if len(last_round.participants.all()) == 1:
winners.append(last_round.participants.first())
print(winners)
new_round.participants.set(winners)
tournament.rounds.add(new_round)

all_games = []
for i in range(0, len(winners), 2):
if i + 1 < len(winners):
game = Game.objects.create(player1=winners[i], player2=winners[i + 1])
game = Game.objects.create(player1=winners[i], player2=winners[i + 1], tournament=tournament)
game_id = str(game.id)
game.tournament_id = self.tournament_id
player1_nick = str(winners[i].nickname)
player2_nick = str(winners[i + 1].nickname)
game_info = {
"game_id": game_id,
"players": [player1_nick, player2_nick]
}
all_games.append(game_info)
new_round.matches.add(game)
new_round.participants.remove(winners[i])
new_round.participants.remove(winners[i + 1])
new_round.save()
print("Yeni Turnuva Oluşturuldu")
self.send_to_group(all_games, "game_info")
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/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ async function loginForm(event)
const spinner = new Spinner({isVisible:true,className:"login-button-loader"}, loginButton);
spinner.render();
try{
let response = await fetch(endpoint, {
let response = await request(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand Down
22 changes: 10 additions & 12 deletions API/static/scripts/spa.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,21 +53,19 @@ const routes = new Map([
</div>
<div>
<input
type="password"
class="login-input p-2"
id="password"
placeholder="PASSWORD"
type="password"
class="login-input p-2"
id="password"
placeholder="PASSWORD"
/>
</div>
<div class="buttons-wrapper">
<button class="login-button" id="login-button" type="submit">LOGIN</button>
<pong-redirect href="/auth/register/">
<button class="login-button" type="button">REGISTER</button>
</pong-redirect>
<button class="login-button" id="login-button" type="submit">LOGIN</button>
<pong-redirect href="/auth/register/">
<button class="login-button" type="button">REGISTER</button>
</pong-redirect>
</div>
<button class="ecole-login-button">
<button class="ecole-login-button" id="ecole-login-button" type="button">
Login with 42
<div>
<img src="/static/public/42.svg" alt=""/>
Expand Down Expand Up @@ -828,7 +826,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
Loading

0 comments on commit 413bcd4

Please sign in to comment.