You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行FootballSim_server时game模块自动启动的问题求助

问题:运行FootballSim_server的main()时Game模块自动启动的解决方法

运行FootballSim_server模块中的main()函数时,Game模块总是自动启动。已尝试添加if __name__ == '__main__'语句,也将导入方式从from module import class改为直接import module,但均无效果,求解决方法。

涉及模块代码

Football_sim模块

import socket
from _thread import *
import plyer
import json


class GameServer:
    def __init__(self):
        self.Server = '127.0.0.1'
        self.Port = 52674
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.p = []  # Starting positions for player 1 and player 2
        self.PlayerId = 0
        self.Players = [plyer.Player(630, 375, 'R', 'Arsenal', position='ST'),
                    plyer.Player(630, 440, 'B', 'Arsenal', position='ST')]

    def Bind(self):
        # Connects the client to the server
        try:
            self.s.bind((self.Server, self.Port))
        except socket.error:
            print("Error")

        # Listens to maximum 2 players only
        self.s.listen(2)
        print("Waiting for a connection...")

    def ReturnSocket(self):
        return self.s

    def ThreadedClient(self, conn, curr_player):
        conn.send(json.dumps(self.Players[curr_player]))
        reply = ""
        while True:
            # Continuously runs when the client is connected
            try:
                data = json.loads(conn.recv(2048))
                self.Players[curr_player] = data

                if not data:
                    print("Player Left")
                    break
                else:
                    if curr_player == 1:
                        reply = self.Players[0]
                    else:
                        reply = self.Players[1]

                    print("Received: ", data)
                    print("Sending: ", reply)

                conn.sendall(json.dumps(reply))
            except:
                break

        print("Connection Lost")
        conn.close()


def main():
    GS = GameServer()
    GS.Bind()
    while True:
        s = GS.ReturnSocket()
        # Continuously looking for connections
        conn, addr = s.accept()
        print(addr, "has joined the game")

        # Function runs in the background
        start_new_thread(GS.ThreadedClient, (conn, GS.PlayerId))
        GS.PlayerId += 1


if __name__ == '__main__':
    main()

Game模块

import Button_tactics
import pygame
import plyer

class Game:
    def __init__(self):
        self.width = 1280
        self.height = 800
        self.window = pygame.display.set_mode((1280, 800))
        pygame.display.set_caption("Football Simulator")
        self.clock = pygame.time.Clock()

    def RedrawWindow(self, p, p2):
        # Builds the GUI
        self.window.fill((50, 50, 50))
        self.BuildFootballPitch()
        Score.Draw()
        p.DrawPlayerShape()
        p2.DrawPlayerShape()

def main():
    # Team.BuildFormation()
    clock = pygame.time.Clock()
    # Allows the window to stay open
    running = True
    n = Client.Network()
    p = n.ReturnP()
    while running:
        p2 = n.Send(p)

        for events in pygame.event.get():
            if events.type == pygame.QUIT:
                running = False
                pygame.quit()
                pass

        p.Move()
        game.RedrawWindow(p, p2)

game = Game()

if __name__ == '__main__':
    main()
else:
    pass

问题原因及解决方法

核心原因

Game模块中的game = Game()语句位于模块顶级作用域,只要该模块被任何其他代码导入(比如Football_sim模块间接导入了它,或者plyer/Button_tactics模块导入了它),这行代码就会立即执行,导致Game类初始化、pygame窗口创建,表现为Game模块自动启动。

if __name__ == '__main__'只能阻止main()函数在模块被导入时执行,但无法阻止顶级作用域的代码运行。

解决步骤

  1. 移动game = Game()的位置:将这行代码移到Game模块的main()函数内部,或者放到if __name__ == '__main__'代码块中,确保只有直接运行Game模块时才会创建Game实例。

修改后的Game模块示例:

import Button_tactics
import pygame
import plyer

class Game:
    def __init__(self):
        self.width = 1280
        self.height = 800
        self.window = pygame.display.set_mode((1280, 800))
        pygame.display.set_caption("Football Simulator")
        self.clock = pygame.time.Clock()

    def RedrawWindow(self, p, p2):
        # Builds the GUI
        self.window.fill((50, 50, 50))
        self.BuildFootballPitch()
        Score.Draw()
        p.DrawPlayerShape()
        p2.DrawPlayerShape()

def main():
    # Team.BuildFormation()
    clock = pygame.time.Clock()
    # Allows the window to stay open
    running = True
    n = Client.Network()
    p = n.ReturnP()
    # 仅在main函数内创建Game实例
    game = Game()
    while running:
        p2 = n.Send(p)

        for events in pygame.event.get():
            if events.type == pygame.QUIT:
                running = False
                pygame.quit()
                pass

        p.Move()
        game.RedrawWindow(p, p2)

if __name__ == '__main__':
    main()
else:
    pass
  1. 检查间接导入:确认Football_sim模块或其依赖的模块(如plyer)是否导入了Game模块,如果有不必要的导入,删除这些导入语句,避免Game模块被意外加载。

  2. 修正代码缩进问题:原代码中GameServer类的Bind、ReturnSocket等方法,以及Game类的RedrawWindow方法都存在缩进错误,这些语法问题可能导致意外行为,需修正为类方法的正确缩进格式。

内容的提问来源于stack exchange,提问作者Kelan Westwood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 18:54:24