我正在尝试使用Python的pygame和websockets库为游戏制作客户端。
这是我当前的代码(删除了无关的内容):
import pygame
import websockets, asyncio
from game import *
connection = websockets.connect("wss://example.com/ws")
tanklist = []
pygame.init()
screen = pygame.display.set_mode((1600, 800))
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((50, 50, 50))
screen.blit(background, (0, 0))
pygame.display.flip()
def redraw():
n = len(tanklist)
for i in range(n):
tanklist[i].draw(screen)
m = len(tanklist[i].bullets)
for j in range(m):
tanklist[i].bullets[j].draw(screen)
pygame.display.update()
def consumer(message):
header = message[0]
data = message[1]
screen.blit(background, (0,0))
#Long block of code that decides to shoot, move, rotate, etc.
redraw()
async def tanks():
async with connection as websocket:
while 1:
message = json.loads(await websocket.recv())
print(message)
consumer(message)
asyncio.get_event_loop().run_until_complete(tanks())
此时此刻,我已设法遵循一些文档,以便它可以工作,但似乎我的游戏无法跟上它从websocket收到的消息,并且落后,特别是当几个同时动作是接收。如何更改此代码以便不会发生这种情况?我自己是一个异步的初学者,不太熟悉await / async语法。非常感谢进一步的指导。
编辑:我使用的是Python 3.6