Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
9fe8ffa
feat : 공의 잔상 추가 및 공 물리 값 수정
minseok128 Aug 27, 2024
c6e0589
Merge branch 'main' into feat/multi-game
minseok128 Aug 27, 2024
33d1393
feat : 점수 구현 및 성현이형과 테스트 완료
minseok128 Aug 27, 2024
40c72a5
feat : 공이 언제 태어나는 지 알려쥼
minseok128 Aug 27, 2024
288dacd
feat : 점수가 더 좋게 표시됨
minseok128 Aug 27, 2024
f5f0228
feat : 모든 소켓의 리스트를 관리하도록 구현
minseok128 Aug 27, 2024
5672a90
feat : 게임 승리 패배 이벤트 발생
minseok128 Aug 27, 2024
5a2f539
feat : 로컬 게임 완성
minseok128 Aug 27, 2024
c5c711b
feat : 매치메이킹 엔터 시 서버와 소통 성공
minseok128 Aug 29, 2024
b0de9b0
feat : Game-matching 구현의 첫 발자국이라고 할 수 있는 커밋
minseok128 Sep 1, 2024
df255cf
feat : 매치에 초대는 되는데 loop가 안 돎
minseok128 Sep 1, 2024
a137de1
Merge branch 'main' into feat/multi-game
minseok128 Sep 14, 2024
f7dff2f
feat multi-game invite room : 방에 들어와서 서로 동일한 게임 루프 따르는 것까지 완료
minseok128 Sep 14, 2024
21b5ea6
feat: tournament game 시작 구현
seonjo1 Sep 27, 2024
591d56a
feat: game에 따른 nick1, nick2, game 저장
seonjo1 Sep 27, 2024
de5010a
Merge branch 'main' into dev/tournament-game
seonjo1 Sep 28, 2024
5368e29
Merge remote-tracking branch 'origin/feat/multi-game' into dev/tourna…
seonjo1 Sep 28, 2024
fb5a86c
feat: tournament 게임 실행 구현
seonjo1 Sep 28, 2024
1bc00db
fix: 토너먼트 마지막 라운드 오류 해결
seonjo1 Sep 28, 2024
a6b917b
fix: 뒤로가기 누를시 홈으로 이동
seonjo1 Dec 25, 2024
f86cf3f
fix: fix tournament api
seonjo1 Dec 25, 2024
e080c0d
Update : 모든 것
minseok128 Dec 25, 2024
2f527c1
dev: tournament complete
seonjo1 Dec 26, 2024
a6ff529
Update: 게임 종료시 화면 전환 추가
seonjo1 Dec 26, 2024
7d47650
Update: profile 점수 글자 크기 변경
seonjo1 Dec 26, 2024
b023e70
Update: 완벽한 번역가 조성현 등장
seonjo1 Dec 26, 2024
27c3ffc
friend 추가/삭제 단방향으로 변경 및 친구 삭제 에러 수정
jaehejun Dec 27, 2024
d5fb073
friend 수정 재검증
jaehejun Dec 28, 2024
5704e06
사용자 탈퇴 시 게임 기록도 모두 삭제하도록 변경, 승률로만 남아있음
jaehejun Dec 28, 2024
d886c32
Merge remote-tracking branch 'origin/fix/friends-error' into dev/tour…
minseok128 Dec 28, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 71 additions & 20 deletions backend/game/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,26 @@

SCREEN_HEIGHT = 750
SCREEN_WIDTH = 1250
MAX_SCORE = 150


class GameState:
def __init__(self):
print("initializing game state!")
self.map = GameMap()
self.left_bar = Bar(
0,
Bar.X_GAP,
SCREEN_HEIGHT // 2 - Bar.HEIGHT // 2,
0
)
self.left_bar = Bar(0, Bar.X_GAP, SCREEN_HEIGHT // 2 - Bar.HEIGHT // 2, 0)
self.right_bar = Bar(
1,
SCREEN_WIDTH - Bar.WIDTH - Bar.X_GAP,
SCREEN_HEIGHT // 2 - Bar.HEIGHT // 2,
SCREEN_WIDTH - Bar.WIDTH
SCREEN_WIDTH - Bar.WIDTH,
)
self.left_ball = Ball(0, SCREEN_HEIGHT, SCREEN_WIDTH, self.left_bar)
self.right_ball = Ball(1, SCREEN_HEIGHT, SCREEN_WIDTH, self.right_bar)
self.score = [0, 0]
self.player = ["player1", "player2"]
self.penalty_time = [0, 0]


class GameConsumer(AsyncWebsocketConsumer):
game_tasks = {}
Expand All @@ -50,7 +50,7 @@ async def receive(self, text_data):
text_data_json = json.loads(text_data)
action = text_data_json["action"]

print("text_data", text_data_json)
# print("text_data", text_data_json)
if action == "authenticate":
token = text_data_json.get("token")
if not token or not self.authenticate(token):
Expand All @@ -75,7 +75,6 @@ async def receive(self, text_data):

# Start ball movement if not already running
if self.room_group_name not in GameConsumer.game_tasks:
print("starting game loop!")
GameConsumer.game_tasks[self.room_group_name] = asyncio.create_task(
self.game_loop()
)
Expand Down Expand Up @@ -113,9 +112,13 @@ def authenticate(self, token):
# Decode JWT token
decoded = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
uid = decoded.get("id")
print(f"uid: {uid}", f"room_name: {self.room_name}", str(uid) == str(self.room_name))
print(
f"uid: {uid}",
f"room_name: {self.room_name}",
str(uid) == str(self.room_name),
)
# Check if uid matches the room_name
if str(uid) == str(self.room_name):
if str(uid) == str(self.room_name):
return True
else:
return False
Expand All @@ -129,7 +132,9 @@ def authenticate(self, token):
async def disconnect(self, close_code):
# Leave room group
if self.authenticated:
await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
await self.channel_layer.group_discard(
self.room_group_name, self.channel_name
)
# Decrease the client count for this room
if self.room_group_name in GameConsumer.client_counts:
GameConsumer.client_counts[self.room_group_name] -= 1
Expand All @@ -141,7 +146,6 @@ async def disconnect(self, close_code):
else:
GameConsumer.client_counts[self.room_group_name] = 0


async def send_initialize_game(self):
state = GameConsumer.game_states[self.room_group_name]
await self.send(
Expand All @@ -163,6 +167,8 @@ async def send_initialize_game(self):
"right_ball_y": state.right_ball.y,
"ball_radius": Ball.RADIUS,
"map": state.map.map,
"player": state.player,
"max_score": MAX_SCORE,
}
)
)
Expand All @@ -175,26 +181,65 @@ async def game_loop(self):
state.left_bar.update()
state.right_bar.update()

state.left_ball.move(state.left_bar)
state.penalty_time[0] = state.left_ball.move(state.left_bar)
state.left_ball.check_bar_collision(state.left_bar)
state.left_ball.check_bar_collision(state.right_bar)
state.left_ball.check_collision(state.map)
state.left_ball.check_collision(state.map, state.score)

state.right_ball.move(state.right_bar)
state.penalty_time[1] = state.right_ball.move(state.right_bar)
state.right_ball.check_bar_collision(state.left_bar)
state.right_ball.check_bar_collision(state.right_bar)
state.right_ball.check_collision(state.map)
state.right_ball.check_collision(state.map, state.score)

if count % 3 == 0:
if count % 5 == 0:
await self.send_game_state()
await asyncio.sleep(0.005)
await asyncio.sleep(0.00390625)
await state.map.init()
if state.score[0] >= MAX_SCORE:
await asyncio.sleep(0.1)
await self.send_game_result(0)
await asyncio.sleep(0.1)
await self.close()
break
elif state.score[1] >= MAX_SCORE:
await asyncio.sleep(0.1)
await self.send_game_result(1)
await asyncio.sleep(0.1)
await self.close()
break
else:
await asyncio.sleep(0.005)
await asyncio.sleep(0.00390625)
count += 1
except asyncio.CancelledError:
# Handle the game loop cancellation
print("Game loop cancelled for", self.room_group_name)
await self.close()

async def send_game_result(self, winner):
state = GameConsumer.game_states[self.room_group_name]
await self.channel_layer.group_send(
self.room_group_name,
{
"type": "game_result_message",
"score": state.score,
"winner": winner,
},
)

async def game_result_message(self, event):
score = event["score"]
winner = event["winner"]

# Send the game result to the WebSocket
await self.send(
text_data=json.dumps(
{
"type": "game_result",
"score": score,
"winner": winner,
}
)
)

async def send_game_state(self):
state = GameConsumer.game_states[self.room_group_name]
Expand All @@ -211,6 +256,8 @@ async def send_game_state(self):
"right_ball_x": state.right_ball.x,
"right_ball_y": state.right_ball.y,
"map_diff": state.map.diff,
"score": state.score,
"penalty_time": state.penalty_time,
},
)

Expand All @@ -223,6 +270,8 @@ async def update_game_state_message(self, event):
left_ball_y = event["left_ball_y"]
right_ball_x = event["right_ball_x"]
right_ball_y = event["right_ball_y"]
score = event["score"]
penalty_time = event["penalty_time"]

# Send the updated game state to the WebSocket
await self.send(
Expand All @@ -238,6 +287,8 @@ async def update_game_state_message(self, event):
"right_ball_x": int(right_ball_x),
"right_ball_y": int(right_ball_y),
"map_diff": GameConsumer.game_states[self.room_group_name].map.diff,
"score": score,
"penalty_time": penalty_time,
}
)
)
Loading
Loading