【问题标题】:Pygame start button menuPygame 开始按钮菜单
【发布时间】:2021-09-03 23:54:48
【问题描述】:

几天前我开始制作我的第一个专业pygame(以前没有做过任何pygame),所以我第一次制作了一个主菜单,用于实际游戏,然后是游戏,所以我有2个文件在那个项目中(主菜单和游戏)。 但几秒钟后,我意识到我不知道如何通过单击开始按钮从主菜单开始游戏。所以我需要一些帮助......

我会让你失望我的主菜单代码。

import pygame
import pygame.freetype
from pygame.sprite import Sprite
from pygame.rect import Rect
from enum import Enum
from pygame.sprite import RenderUpdates

BLUE = (106, 159, 181)
WHITE = (255, 255, 255)


def create_surface_with_text(text, font_size, text_rgb, bg_rgb):
   """ Returns surface with text written on """
   font = pygame.freetype.SysFont("Courier", font_size, bold=True)
   surface, _ = font.render(text=text, fgcolor=text_rgb, bgcolor=bg_rgb)
   return surface.convert_alpha()


class UIElement(Sprite):
    """ An user interface element that can be added to a surface """

def __init__(self, center_position, text, font_size, bg_rgb, text_rgb, action=None):
    """
    Args:
        center_position - tuple (x, y)
        text - string of text to write
        font_size - int
        bg_rgb (background colour) - tuple (r, g, b)
        text_rgb (text colour) - tuple (r, g, b)
        action - the gamestate change associated with this button
    """
    self.mouse_over = False

    default_image = create_surface_with_text(
        text=text, font_size=font_size, text_rgb=text_rgb, bg_rgb=bg_rgb
    )

    highlighted_image = create_surface_with_text(
        text=text, font_size=font_size * 1.2, text_rgb=text_rgb, bg_rgb=bg_rgb
    )

    self.images = [default_image, highlighted_image]

    self.rects = [
        default_image.get_rect(center=center_position),
        highlighted_image.get_rect(center=center_position),
    ]

    self.action = action

    super().__init__()

@property
def image(self):
    return self.images[1] if self.mouse_over else self.images[0]

@property
def rect(self):
    return self.rects[1] if self.mouse_over else self.rects[0]

def update(self, mouse_pos, mouse_up):
    """ Updates the mouse_over variable and returns the button's
        action value when clicked.
    """
    if self.rect.collidepoint(mouse_pos):
        self.mouse_over = True
        if mouse_up:
            return self.action
    else:
        self.mouse_over = False

def draw(self, surface):
    """ Draws element onto a surface """
    surface.blit(self.image, self.rect)


class Player:
""" Stores information about a player """

def __init__(self, score=0, lives=3, current_level=1):
    self.score = score
    self.lives = lives
    self.current_level = current_level


def main():
pygame.init()

screen = pygame.display.set_mode((800, 600))
game_state = GameState.TITLE

while True:
    if game_state == GameState.TITLE:
        game_state = title_screen(screen)

    if game_state == GameState.NEWGAME:
        player = Player()
        game_state = play_level(screen, player)

    if game_state == GameState.NEXT_LEVEL:
        player.current_level += 1
        game_state = play_level(screen, player)

    if game_state == GameState.QUIT:
        pygame.quit()
        return


def title_screen(screen):
start_btn = UIElement(
    center_position=(400, 400),
    font_size=30,
    bg_rgb=BLUE,
    text_rgb=WHITE,
    text="Start",
    action=GameState.NEWGAME,
)
quit_btn = UIElement(
    center_position=(400, 500),
    font_size=30,
    bg_rgb=BLUE,
    text_rgb=WHITE,
    text="Quit",
    action=GameState.QUIT,
)

buttons = RenderUpdates(start_btn, quit_btn)

return game_loop(screen, buttons)


def play_level(screen, player):
return_btn = UIElement(
    center_position=(140, 570),
    font_size=20,
    bg_rgb=BLUE,
    text_rgb=WHITE,
    text="Return to main menu",
    action=GameState.TITLE,
)

nextlevel_btn = UIElement(
    center_position=(400, 400),
    font_size=30,
    bg_rgb=BLUE,
    text_rgb=WHITE,
    text=f"Next level ({player.current_level + 1})",
    action=GameState.NEXT_LEVEL,
)

buttons = RenderUpdates(return_btn, nextlevel_btn)

return game_loop(screen, buttons)


def game_loop(screen, buttons):
""" Handles game loop until an action is return by a button in the
    buttons sprite renderer.
"""
while True:
    mouse_up = False
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
            mouse_up = True
    screen.fill(BLUE)

    for button in buttons:
        ui_action = button.update(pygame.mouse.get_pos(), mouse_up)
        if ui_action is not None:
            return ui_action

    buttons.draw(screen)
    pygame.display.flip()


class GameState(Enum):
QUIT = -1
TITLE = 0
NEWGAME = 1
NEXT_LEVEL = 2


if __name__ == "__main__":
main()

谢谢你的建议!!!!

【问题讨论】:

  • 请更正Indentation。你可以在这里找到一些帮助StackOverflow Markdown help
  • 问题是什么?这段代码看起来不错。
  • 当我在菜单中选择开始时,如何打开我的其他 python 文件(游戏)。
  • 你不能“打开”另一个 pygame 文件。如果你想在同一个 pygame 窗口中运行游戏,你已经集成了代码。在第二个文件中创建一些函数(或类和方法)并调用函数(或方法)。

标签: python syntax pygame main


【解决方案1】:

我有两个想法:

第一个: 只需导入它。当你导入它时,它会被执行。

import importlib
importlib.import("name of you file without extension") # i dont know the command

第二: 使用

执行()

exec(open("filename.py").read())

with open("file.py", "r") as f:
    exec(f.read())

ywc

【讨论】:

    猜你喜欢
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    • 2019-01-05
    • 2020-10-20
    • 1970-01-01
    相关资源
    最近更新 更多