我做了一个主菜单,但不知道如何开始游戏

因此,我做了一个主菜单。现在,我必须制作“主游戏”。但是我该怎么办呢?我的意思是我必须编写游戏代码,但是当我## m完成后如何通过按“开始”按钮来启动游戏。我必须将什么编码到开始按钮(在我的情况下为“ greenButton”)中,这样才能打开游戏?我是否必须制作一个新文件,如果需要,在按下开始按钮后如何打开新文件。我将代码放在这里,即使它确实是必要的:

import pygame
from pygame.locals import *

pygame.init()

win = pygame.display.set_mode((800, 600))
win.fill((0, 180, 210))

class button():
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def draw(self, win, outline=None):
        # Call this method to draw the button on the screen
        if outline:
            pygame.draw.rect(win, outline, (self.x - 2, self.y - 2, self.width + 4, self.height + 4), 0)

        pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)

        if self.text != '':
            font = pygame.font.SysFont('comicsans', 60)
            text = font.render(self.text, 1, (0, 0, 0))
            win.blit(text, (self.x + (self.width / 2 - text.get_width() / 2), self.y + (self.height / 2 - text.get_height() / 2)))

    def isOver(self, pos):
        # Pos is the mouse position or a tuple of (x,y) coordinates
        if pos[0] > self.x and pos[0] < self.x + self.width:
            if pos[1] > self.y and pos[1] < self.y + self.height:
                return True

        return False

def redrawWindow():
    win.fill((0, 180, 210))
    greenButton.draw(win, (0, 0, 0))
    redButton.draw(win, (0, 0, 0))

run = True
greenButton = button((0, 255, 0), 280, 255, 250, 100, "Start")
redButton = button ((255, 0, 0), 280, 380, 250, 100, "Quit")
while run:
    redrawWindow()

    for event in pygame.event.get():
        pos = pygame.mouse.get_pos()

        if event.type == pygame.QUIT:
            run = False
            pygame.quit()
            quit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            if greenButton.isOver(pos):
                print("clicked the button")
            if redButton.isOver(pos):
                print("clicked the 2button")
                run = False
                pygame.quit()
                quit()

        if event.type == pygame.MOUSEMOTION:
            if greenButton.isOver(pos):
                greenButton.color = (105, 105, 105)
            else:
                greenButton.color = (0, 255, 0)
            if redButton.isOver(pos):
                redButton.color = (105, 105, 105)
            else:
                redButton.color = (255, 0, 0)







    pygame.display.update()
评论