Skip to main content
 首页 » 编程设计

python之Pygame菜单: calling another . py文件

2025年05月04日11Free-Thinker

我正在通过帮助 friend 为他的交互式 TicTacToe 游戏制作菜单来学习 pygame。它很简单,一个标题和 2 个用于开始和退出游戏的按钮。他已经完成了游戏,我只需要将我的菜单链接到他的游戏。

在pygame的摆弄之后,我终于完成了在pygame窗口中显示图像的工作(没想到第一次在空白窗口中看到文字会这么漂亮!T^T)。我相信下一步是让图像像按钮一样调用另一个 python 文件。

这是我的简单菜单代码:

import pygame 
from pygame.locals import * 
from sys import exit 
 
pygame.init() 
 
resX, resY = 640, 480 
 
windowObj = pygame.display.set_mode((resX,resY)) 
 
titleImg = pygame.image.load("title.png") 
startImg = pygame.image.load("start.png") 
exitImg =  pygame.image.load("exit.png") 
 
def width_center(img): 
    """For horizontally setting an image.""" 
    return resX/2 - x(img)/2 
 
def height_center(img): 
    """For vertically setting an image.""" 
    return resY/2 - y(img)/2 
 
def x(img): 
    """Width of object.""" 
    return img.get_width() 
def y(img): 
    """Height of object.""" 
    return img.get_height() 
 
while True: 
    pygame.display.update() 
    windowObj.fill((255,255,255)) 
 
    windowObj.blit(titleImg,(width_center(titleImg), 30)) 
    #This I want to link: 
    windowObj.blit(startImg,(width_center(startImg),height_center(startImg)-10)) 
 
    windowObj.blit(exitImg,(width_center(exitImg),height_center(exitImg)+y(startImg))) 
 
    for i in pygame.event.get(): 
        if i.type == QUIT: 
            exit() 

简单地说,我想知道如何让 startImg 调用 TTTClick.py。他的 TTTClick.py 是否也应该有某种格式?

谢谢:)

请您参考如下方法:

如果是一个项目,您可以有“标题屏幕”状态和“游戏”状态。

伪代码:

class Game(): 
    def __init__(self): 
        self.done = False 
        self.state = "title" 
 
    def game_draw(self): 
        # game draw 
 
    def game_update(self): 
        # game event handling, and physics 
 
    def title_draw(self): 
        # title draw 
 
    def title_update(self): 
        # on event click 
        self.state = "game" 
 
    def loop(self): 
        # main loop 
        while not self.done: 
            if state == 'title': 
                title_update() 
                title_draw() 
            elif state == 'game': 
                game_update() 
                game_draw() 
 
if __name__ == "__main__": 
    game = Game() 
    game.loop() 

注意:x、height_center 等。已经存在于 pygame.Rect

# if Surface 
titleImage.get_rect().width 
 
# if Sprite 
titleImage.rect.width 

还有更多,rect.center,rect.centerx,查看完整列表 http://www.pygame.org/docs/ref/rect.html