将Python Turtle Game进入本地LAN多人游戏

问题描述 投票:0回答:2

I使用Turtle模块制作了一款名为“ Pong”的游戏,我想让它成为本地LAN多人游戏。

有人可以告诉我我该怎么做?

我想让它像当地主机一样,以便我和我的兄弟可以玩。

您将通过使用套接字来实现这一目标。
python network-programming turtle-graphics multiplayer python-turtle
2个回答
0
投票
Server

脚本,将游戏显示给玩家并将用户的输入 +发送到服务器。 服务器将负责两个客户端的游戏同步。 您可以在PC中运行服务器脚本,然后使用来自两台计算机的客户端脚本连接到服务器。 thehere是一个

link

(“每个程序员都需要了解游戏网络”)以获取更多详细信息。

Edit:
我找到了
本教程,可以使用
client

PyGame

创建一个简单的2播放器游戏。 第一部分是创建游戏的客户端。 第二部分是创建服务器端并添加游戏逻辑。 如果您有兴趣,这可能是一个不错的开始。

这不是一个简单的任务,而是可以完成的。 我不会实现乒乓球,因为这涉及大量特定的游戏逻辑,这些逻辑已经妨碍了核心网络代码,这已经涉及。适应此起动器以满足特定用例的习惯是读者的练习。

注意,这不是可扩展的或的设计,只是第一笔努力,对学生项目和作为概念证明很有用。 Server.py:

PodSixNet
您可以免费在Glitch或Pythonanywhere等服务上托管该服务器。在这种情况下,我使用了

glitch

0
投票
fork myproject

,请记住,Glitch的Python 3版本很旧(在编写时),您需要使用wife the Websockets库

import asyncio import json import os import websockets from random import random connected_clients = {} positions = {} async def websocket_handler(websocket, path): client_id = id(websocket) connected_clients[websocket] = client_id positions[client_id] = {"x": 0, "y": 0, "color": [random(), random(), random()]} print(f"Client {client_id} connected") try: async for message in websocket: try: data = json.loads(message) if "x" in data and "y" in data: positions[client_id]["x"] = data["x"] positions[client_id]["y"] = data["y"] except json.JSONDecodeError: pass except websockets.ConnectionClosed: print(f"Client {client_id} disconnected") finally: del connected_clients[websocket] del positions[client_id] async def game_loop(): while True: if connected_clients: message = json.dumps(positions) disconnected_clients = set() for client in connected_clients: try: await client.send(message) except websockets.ConnectionClosed: disconnected_clients.add(client) for client in disconnected_clients: del connected_clients[client] del positions[connected_clients[client]] await asyncio.sleep(1 / 30) # 30 FPS if __name__ == "__main__": port = int(os.environ.get("PORT", 8765)) start_server = websockets.serve(websocket_handler, "0.0.0.0", port) loop = asyncio.get_event_loop() loop.run_until_complete(start_server) loop.create_task(game_loop()) print(f"WebSocket server running on ws://0.0.0.0:{port}") loop.run_forever()

如果不是已经为您安装了。添加一个带有内容

pip install websockets

的文件。 client.py:

start.sh

在设置服务器时,在本地计算机上添加客户端代码,安装
python3 server.py
并按照

import asyncio import json import threading import websockets from turtle import Screen, Turtle async def websocket_client(): global websocket async with websockets.connect(server_uri) as ws: websocket = ws while True: try: message = await websocket.recv() positions = json.loads(message) action_queue.append(positions) except json.JSONDecodeError: pass def start_websocket_client(): asyncio.set_event_loop(loop) loop.run_until_complete(websocket_client()) def redraw(): while action_queue: positions = action_queue.pop() for client_id, pos in positions.items(): t.color(pos["color"]) t.goto(pos["x"], pos["y"]) t.stamp() def send_position(x, y): if websocket and websocket.open: position = json.dumps({"x": x, "y": y}) asyncio.run_coroutine_threadsafe(websocket.send(position), loop) def on_motion(event): x = event.x - screen.window_width() / 2 y = -event.y + screen.window_height() / 2 send_position(x, y) def tick(): redraw() screen.update() screen.ontimer(tick, 1000 // 30) server_uri = "ws://turtle-draw.glitch.me" t = Turtle() t.shape("circle") t.penup() screen = Screen() screen.tracer(0) action_queue = [] websocket = None loop = asyncio.new_event_loop() websocket_thread = threading.Thread(target=start_websocket_client, daemon=True) websocket_thread.start() screen.listen() canvas = screen.getcanvas() canvas.bind("<Motion>", on_motion) tick() screen.exitonclick() 往常运行。它应该连接到小故障服务器并以单人模式工作。 连接更多的客户端,以查看正在绘制不同的颜色斑点。 在这里进行了太多的解释,但是在很高的水平上,客户的基础是turtle -turtle-如何在窗口中获得鼠标光标的位置?

.
构建对此,线程运行一个循环以从服务器接收WebSocket消息,该消息已添加到全局
websockets
中,本地游戏循环从中删除并绘制位置更新。
用户移动鼠标时,将坐标发送到服务器以发送到其他客户端。

服务器以类似的方式工作,以大约30个fps运行一个恒定的游戏循环(这不是一个Great

游戏循环,只是草图),然后将位置更新发送给客户端。

服务器WebSocket接收来自客户端的位置消息,并将其添加到游戏循环读取的位置的全局字典中。
我想强调:不同的应用程序有不同的需求,因此,如果您正在编写聊天服务器或基于转弯的游戏,则无需始终在服务器上运行昂贵的投票循环。您可以使用带有烧瓶和简单HTTP请求的服务器量事件,而不是Websocket。
您可以以与上述不同的方式安排游戏循环。
选择最适合您需求的设计。


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.