Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
49 changes: 49 additions & 0 deletions client/client_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# client 진입점 정의
import network_client
import world_view
import pico2d
import play_view
import time
import sys, os
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common.constants import PORT, WIDTH, HEIGHT
from common import protocol

# 본문은 render 시험은 world_view.py에서 수행한다. (world_view.py는 단독으로 실행 가능)
def main():
client = network_client.NetworkClient()
world = world_view.ClientWorld()
pico2d.open_canvas(WIDTH, HEIGHT)
render = play_view.PlayView()
if client.connect(network_client.title(), PORT) and client.connect_udp(PORT - 1):
'''
# 서버로부터 게임 시작 패킷을 받았다고 가정하고 world를 초기화한다. (실제 게임에서는 서버에서 패킷을 받아서 world를 초기화한다)
'임의의 테스트 값'

name = 'StoC_GAME_START'
time_limit = 180
costs = (10, 14, 24, 40)
players = [(0, 100, 200), (1, 100, 100), (2, 900, 400)]
gold_count = 3
golds = [(7, 1000, 1), (8, 100, 200), (9, 300, 400)]
value = (time_limit, costs, players, gold_count, golds)
msgs = [(name, value)]
'''
while True:
msgs = client.poll()
for name, value in msgs:
world.apply_world_message(name, value)
if world.running:
events = pico2d.get_events()
client.play_state(events)
last_frame_time = time.monotonic()
dt = time.monotonic() - last_frame_time
world.update(dt)
render.update(world)
pico2d.clear_canvas()
render.draw(world)
pico2d.update_canvas()
pico2d.delay(0.01)
#msgs = client.poll() # 테스트시 위의 같은 코드를 주석처리 하고 해당 코드를 활성화
if __name__ == '__main__':
main()
3 changes: 1 addition & 2 deletions client/network_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,7 @@ def send_input(self, key_flags):
# 눌린 키 상태를 서버로 보낸다. key_flags : protocol.KEY_W | KEY_A | KEY_S | KEY_D | KEY_SPACE 를 더한 값.
# (키가 바뀔 때만 / 0.5초마다 호출하는 규칙은 PlayState 에서 정한다)
return self.send(protocol.pack_input(key_flags))
def play_state(self):
events = get_events() # 나중에 client main 에서 분리되면 events 를 매개변수로 받도록 바꾼다. (PlayState 에서 호출)
def play_state(self, events):
for event in events:
if event.type == SDL_KEYDOWN:
if event.key == SDLK_w:
Expand Down
79 changes: 64 additions & 15 deletions client/world_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common import protocol
from common.constants import PLAYER_SPEED
from common import protocol
global running

# TODO client_main을 네트워크 환경에서 테스트 후 지운다. (world_view.py는 단독으로 실행 가능)
import play_view
import pico2d
class ClientWorld:
def __init__(self):
self.time_limit = 0
Expand All @@ -14,7 +19,7 @@ def __init__(self):
self.remain_x10 = 0 # STATE 패킷과 같은 0.1초 단위
self.team_gold = 0
self.item_level = 0

self.running = False
def init_from_start(self, time_limit, costs, players, gold_count, golds):
self.time_limit = time_limit
self.costs = tuple(costs)
Expand All @@ -30,6 +35,7 @@ def init_from_start(self, time_limit, costs, players, gold_count, golds):
self.remain_x10 = time_limit * 10
self.team_gold = 0
self.item_level = 0
self.running = True
def calc_dir(self, player_id, new_x, new_y):
# 서버는 dir를 보내지 않고 클라에서 계산한다. (dir : 0 아래 / 1 왼쪽 / 2 오른쪽 / 3 위)
player = self.players[player_id]
Expand Down Expand Up @@ -74,26 +80,30 @@ def apply_world_message(self, name, payload):
# inbox에는 월드, 로비, 오류 등 여러 종류의 수신 메시지가 도착 순서대로 쌓인다.
# name은 메시지 종류이고, payload는 헤더를 제외한 본문 바이트다.

# 메인 스레드가 poll()로 꺼낸 메시지 중 GAME_START와 STATE만 ClientWorld에 반영한다.
# name은 메시지 종류이고, 이 두 메시지의 payload는 헤더를 제외한 본문 바이트다.
# TODO: network_client에서 unpacking을 해주는게 맞는듯 여기는 클라 데이터만 갱신해야 역할 적으로 맞다.
if name == 'StoC_GAME_START':
# 게임 시작 시 제한 시간, 가격표, 플레이어 시작 위치와 금괴 배치를 설정한다.
self.init_from_start(*protocol.unpack_game_start(payload))
self.init_from_start(*payload) #protocol.unpack_game_start(payload)
#self.init_from_start(*protocol.unpack_game_start(payload))
elif name == 'StoC_GOLD_MINED':
# 채굴이 끝난 금괴를 지우고 팀 금괴를 서버 값으로 맞춘다. (STATE 보다 먼저 도착한다)
self.apply_gold_mined(*protocol.unpack_gold_mined(payload))
elif name == 'StoC_GOLD_RESPAWN':
self.apply_gold_respawn(protocol.unpack_gold_respawn(payload))
self.apply_gold_mined(*payload) #protocol.unpack_gold_mined(payload)
#self.apply_gold_mined(*protocol.unpack_gold_mined(payload))
elif name == 'StoC_STATE':
# 플레이 중에는 서버가 보낸 최신 값으로 플레이어와 HUD에 표시할 데이터를 갱신한다.
remain_x10, team_gold, item_level, players = protocol.unpack_state(payload)
remain_x10, team_gold, item_level, players = (payload) #protocol.unpack_state(payload)
# 서버는 20HZ로 STATE를 보내지만 클라이언트는 60프레임으로 그린다 따라서 서버로 부터 받으면 바로 갱신하지 않고 지난 0.033초 동안의 이동을 계산해서 그린다.
# 또한 서버는 dir를 보내지 않고 클라에서 계산한다
for player_id, x, y, state in players:
player = self.players[player_id]
self.calc_dir(player_id, x, y)
player['dx'] = float(x) - player['x']
player['dy'] = float(y) - player['y']
player['x'] = float(x)
player['y'] = float(y)
player['dx'] = float(x) - float(player['x'])
player['dy'] = float(y) - float(player['y'])
player['state'] = state
self.remain_x10 = remain_x10
self.team_gold = team_gold
Expand All @@ -111,15 +121,54 @@ def apply_gold_respawn(self, golds):
self.golds = {spot_id: {'x': x, 'y': y} for spot_id, x, y in golds}
self.gold_count = len(self.golds)

def print_data(self): # TODO : 디버깅용으로 나중에 지운다
print(f"ClientWorld: time_limit={self.time_limit}, costs={self.costs}, players={self.players}, gold_count={self.gold_count}, golds={self.golds}, remain_x10={self.remain_x10}, team_gold={self.team_gold}, item_level={self.item_level}")
if __name__ == '__main__':
# interpolate()를 테스트한다. 서버에서 임의의 player 데이터를 준다고 가정한다, client main에서 매 프레임 마다 호출하고 받는다 한다
player = {'x': 100.0, 'y': 100.0, 'dir': 0, 'state': 1, 'dx': 3.0, 'dy': -2.0}
world = ClientWorld()
world.players[0] = player
print(f"Before interpolate: {player}")
world.interpolate(0.016) # 16ms = 1/60초
print(f"After interpolate: {player}")
world.interpolate(0.016)
print(f"After interpolate: {player}")
'임의의 테스트 값'

name = 'StoC_GAME_START'
time_limit = 180
costs = (10, 14, 24, 40)
players = [(0, 100, 200), (1, 100, 100), (2, 900, 400)]
gold_count = 3
golds = [(7, 1000, 1), (8, 100, 200), (9, 300, 400)]
value = (time_limit, costs, players, gold_count, golds)
world.apply_world_message(name, value)
world.print_data()
pico2d.open_canvas(1000, 600)
render = play_view.PlayView()
render.update(world)
pico2d.clear_canvas()
render.draw(world)
pico2d.update_canvas()
pico2d.delay(1)

name = 'StoC_STATE'

remain_x10 = 1799
team_gold = 0
item_level = 0
players = [(0, 100, 200, 0), (1, 200, 200, 1), (2, 900, 400, 2)]
value = remain_x10, team_gold, item_level, players
world.apply_world_message(name, value)
world.print_data()
pico2d.clear_canvas()
render.draw(world)
pico2d.delay(1)
for i in range(10):
world.update(0.1)
render.update(world)
pico2d.clear_canvas()
render.draw(world)
pico2d.update_canvas()
pico2d.delay(0.1)
world.print_data()
render.update(world)
render.draw(world)
pico2d.update_canvas()
pico2d.delay(1)
pico2d.close_canvas()



12 changes: 7 additions & 5 deletions common/test_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
# 테스트에 사용할 값
COSTS = (10, 14, 24, 40) # 장갑, 삽, 곡괭이, 드릴 순서
PLAYERS = [(0, 1, 2), (1, -1, 0), (2, 1000, 600)] # (플레이어 번호, x, y)
STATES = [(0, 1, 2, 0, 0), (1, -1, 0, 1, 1), (2, 1000, 600, 3, 2)] # (번호, x, y, 방향, 상태), 진행률 없음
STATES = [(0, 1, 2, 0), (1, -1, 0, 1), (2, 1000, 600, 2)] # (번호, x, y, 상태), 진행률 없음
GOLDS = [(7, 1000, -2)] # (금괴 번호, x, y), 음수 좌표도 복원하는지 확인
GOLD_COUNT = len(GOLDS)
MINED = [(0, 5), (1, 256), (2, 7)] # (플레이어 번호, 채굴 수), 256으로 u16 확인
Expand All @@ -16,10 +16,10 @@
def test_roundtrip_all_values():
# 여러 인자를 받는 패킷 : (입력값, 예상 반환값, 본문 길이)
# 금괴 1개 기준 GAME_START = 26 + 5 = 31B, GOLD_RESPAWN = 1 + 5 = 6B
# STATE = 공통 정보 5B + 플레이어 7B x 3명 = 26B
# STATE = 공통 정보 5B + 플레이어 6B x 3명 = 23B
samples = {
"StoC_GAME_START": ((180, COSTS, PLAYERS, GOLD_COUNT, GOLDS), (180, COSTS, PLAYERS, GOLD_COUNT, GOLDS), 31),
"StoC_STATE": ((1800, 300, 4, STATES), (1800, 300, 4, STATES), 26),
"StoC_STATE": ((1800, 300, 4, STATES), (1800, 300, 4, STATES), 23),
"StoC_GOLD_MINED": ((7, 2, 300), (7, 2, 300), 4),
"StoC_GOLD_RESPAWN": ((GOLDS,), GOLDS, 6),
"StoC_SHOP_RESULT": ((0, 4, 4, 300), (0, 4, 4, 300), 5),
Expand Down Expand Up @@ -63,12 +63,14 @@ def test_exact_bytes():
assert p.KEY_W + p.KEY_A + p.KEY_S + p.KEY_D + p.KEY_SPACE == 31 # 키 비트가 겹치지 않음
# 예상 바이트를 직접 비교해 pack/unpack 양쪽이 같은 실수를 해도 발견한다
# 앞의 3바이트는 종류 1B + 본문 길이 2B이며, 여러 바이트 숫자는 big-endian

assert p.pack_game_start(180, COSTS, PLAYERS, GOLD_COUNT, GOLDS) == bytes.fromhex(
'67 00 1f 00 b4 00 0a 00 0e 00 18 00 28 '
'00 00 01 00 02 01 ff ff 00 00 02 03 e8 02 58 01 07 03 e8 ff fe')
'''
assert p.pack_state(1800, 300, 4, STATES) == bytes.fromhex(
'68 00 1a 07 08 01 2c 04 '
'00 00 01 00 02 00 00 01 ff ff 00 00 01 01 02 03 e8 02 58 03 02')
'68 00 17 07 08 01 2c 00 04 00 00 01 00 02 01 ff ff 00 00 02 03 e8 02 58 02 00')
'''
assert p.pack_gold_mined(7, 2, 300) == bytes([105, 0, 4, 7, 2, 1, 44])
assert p.pack_gold_respawn(GOLDS) == bytes.fromhex('6a 00 06 01 07 03 e8 ff fe')
assert p.pack_shop_result(0, 4, 4, 300) == bytes([107, 0, 5, 0, 4, 4, 1, 44])
Expand Down