所以我在 pygame 上做了一个游戏,可以在局域网上玩。当我运行服务器并在我自己的机器上创建客户端实例时,它工作正常。我什至使用 auto-to-py-exe 使其成为可执行文件,这样我就可以在其他计算机上对其进行测试。该可执行文件在我的机器上也运行良好。但是当我发送它并在另一台机器上测试它时,程序甚至没有尝试连接所以没有发送任何游戏信息,我不知道我是否将exe打包错误或什么,有什么帮助吗?
服务器代码:
import socket
import pickle
from _thread import *
from game import Game
from player import Player
hostname = socket. gethostname()
local_ip = socket. gethostbyname(hostname)
print(local_ip)
#server = local_ip
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(('', port))
except socket.error as e:
print(e)
s.listen()
print("Waiting for connection")
idCount = 0
def threaded_client(conn, p, gameId):
#threaded client stuff
while True:
#accept incoming connections
conn, addr = s.accept()
print("Connected to ", addr)
idCount += 1
p = 0
gameId = (idCount -1)//2
if idCount %2 == 1:
games[gameId] = Game(gameId)
print("making game ", gameId)
else:
p = 1
games[gameId].ready()
start_new_thread(threaded_client, (conn, p, gameId))
客户端代码:
import pygame
from drawingTools import Tools
from game import Game
from player import Player
from player import Bullet
from sound import Sound
from network import Network
#dimensions
WIDTH = 900
HEIGHT = 500
HIT = pygame.USEREVENT + 1
EXPIRE = pygame.USEREVENT + 2
#create object
t = Tools(WIDTH, HEIGHT)
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Game")
def main():
#game loop
run = True
n = Network()
s = Sound()
#this is the method that should be connecting to the server and is where i believe the problem
is
#everything else is game stuff, so i dont think i need to include it
n.connect()
p1:Player = n.send("playerinnit")
try:
game: Game = n.send("get")
except:
print("error")
clock = pygame.time.Clock()
print("player ", p1.p)
ship, r = p1.loadSprite(p1.p)
s.music()
while run:
game stuff logic
网络代码:
import socket
import pickle
class Network:
def __init__(self):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = "ip of the machine where the server is"
self.port = 5555
self.addr = (self.server, self.port)
def getPlayer(self):
return None
#method that should be doing the connecting, works standalone or with a script but not the exe
def connect(self):
try:
self.client.connect(self.addr)
#return pickle.load(self.client.recv(4090))
except:
print("Could not connect")
def send(self, data):
try:
self.client.send(str.encode(data))
return pickle.loads(self.client.recv(4090))
except socket.error as e:
print(e)
def sendObj(self, data):
try:
self.client.send(pickle.dumps(data))
return pickle.loads(self.client.recv(4090))
except socket.error as e:
return []
def disconnect(self):
self.client.close()
现在是exe的主文件:
from client import main, playAgain
if __name__ == "__main__":
main()
playAgain()
我不知道你们是否需要其他任何东西,比如 auto-to-py-exe 打包的所有东西,但任何帮助都将不胜感激!