Skip to content

Commit

Permalink
threading added
Browse files Browse the repository at this point in the history
  • Loading branch information
yusuffugurlu committed Apr 18, 2024
1 parent 3e23ab8 commit 7e239f3
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
11 changes: 7 additions & 4 deletions API/Apps/Game/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def __init__(self, *args, **kwargs):
self.game_id = None
self.game_group_name = None
self.gameState = {}
self.stop_event = threading.Event()

async def connect(self):
await self.accept()
Expand All @@ -91,7 +92,9 @@ async def connect(self):
add_player_in_game(self.game_id)
await self.send_initial_state()
if 'task' not in GameConsumer.game_states[self.game_id] and get_players_in_game(self.game_id) == 2:
asyncio.ensure_future(self.game_loop())
# asyncio.ensure_future(self.game_loop())
self.thread = threading.Thread(target=asyncio.run, args=(self.game_loop(),))
self.thread.start()
GameConsumer.game_states[self.game_id]['task'] = True

async def disconnect(self, close_code):
Expand Down Expand Up @@ -154,7 +157,7 @@ def finish_game(self, winner):
game.save()

async def game_loop(self):
while True:
while not self.stop_event.is_set():
await self.update()
await self.channel_layer.group_send(
self.game_group_name,
Expand All @@ -173,8 +176,6 @@ async def send_state(self, event):

async def update(self):
paddle_height = 200


ball_speed = 1.0001

player1_score = GameConsumer.game_states[self.game_id]['player_one']['score']
Expand Down Expand Up @@ -239,6 +240,7 @@ async def update(self):
'winner': self.player2
}
)
self.stop_event.set()
else:
await self.channel_layer.group_send(
self.game_group_name,
Expand All @@ -265,6 +267,7 @@ async def update(self):
'winner': self.player1
}
)
self.stop_event.set()
else:
await self.channel_layer.group_send(
self.game_group_name,
Expand Down
2 changes: 1 addition & 1 deletion Backend/static/scripts/game.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ async function connectToServer()
{
//"f6c10af0-41b4-480a-909e-8cea089b5218" product
//'77a18eba-6940-4912-a2f8-c34a3cf69e40'
const id = "f6c10af0-41b4-480a-909e-8cea089b5218";
const id = "77a18eba-6940-4912-a2f8-c34a3cf69e40";
let socket = new WebSocket(`ws://localhost:8000/ws/game/${id}`)
var startTime = new Date().getTime();
var count = 0
Expand Down

0 comments on commit 7e239f3

Please sign in to comment.