pygame 菜单栏
时间: 2025-01-22 20:13:01 浏览: 16
如何在 Pygame 中实现菜单栏功能
为了实现在Pygame中的菜单栏功能,通常的做法是手动构建一个简单的状态机来管理不同菜单项之间的切换。由于Pygame本身并不直接支持GUI组件如按钮或下拉菜单,因此需要通过事件循环监听鼠标点击位置并相应地改变游戏的状态。
下面是一个简化版的示例程序,展示了如何创建基本的选择界面[^1]:
import sys
import pygame
def draw_text(surface, text, color, rect, font, aa=False, bkg=None):
"""Utility function to render and blit text onto a surface."""
y = rect.top
line_spacing = -2
# get the height of the font
font_height = font.size("Tg")[1]
while text:
i = 1
# determine if the row will be outside our area
if y + font_height > rect.bottom:
break
# determine maximum width of line
while font.size(text[:i])[0] < rect.width and i < len(text):
i += 1
# if we've wrapped the text, then adjust the wrap to the last word
if i < len(text):
i = text.rfind(" ", 0, i) + 1
# render the line and blit it to the surface
if bkg:
image = font.render(text[:i], True, color, bkg)
image.set_colorkey(bkg)
else:
image = font.render(text[:i], aa, color)
surface.blit(image, (rect.left, y))
y += font_height + line_spacing
# remove the text we just blitted
text = text[i:]
return text
class Menu(object):
def __init__(self, screen, items, bg_color=(0, 0, 0), font_size=70,
font_color=(255, 255, 255)):
self.screen = screen
self.scr_width = self.screen.get_rect().width
self.scr_height = self.screen.get_rect().height
self.bg_color = bg_color
self.clock = pygame.time.Clock()
self.items = items
self.font = pygame.font.SysFont("Courier", font_size)
self.font_color = font_color
self.item = None
def run(self):
mainloop = True
while mainloop:
# Limit frame speed to 50 FPS
self.clock.tick(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainloop = False
elif event.key == pygame.K_UP:
if self.item is None or self.item > 0:
self.item -= 1
elif event.key == pygame.K_DOWN:
if self.item is None or self.item < len(self.items)-1:
self.item += 1
elif event.key == pygame.K_RETURN:
if self.items[self.item][1]:
self.items[self.item][1]()
# Redraw background
self.screen.fill(self.bg_color)
for index, item in enumerate(self.items):
if self.item == index:
label = self.font.render(item[0],
True,
(255, 0, 0)) # Highlight selected option with red color.
else:
label = self.font.render(item[0], True, self.font_color)
width = label.get_rect().width
self.screen.blit(label, ((self.scr_width / 2) - (width / 2),
(index * 60) + 140))
pygame.display.flip()
if __name__ == "__main__":
pygame.init()
screen = pygame.display.set_mode((640, 480))
menu_items = (("Start Game", lambda: print("Starting game...")),
("Options", lambda: print("Opening options...")),
("Quit", sys.exit))
pygame.display.set_caption('Game Menu')
gm = Menu(screen, menu_items)
gm.run()
此代码片段定义了一个Menu
类,用于显示带有几个选项的主菜单。当用户按下回车键时,所选项目对应的回调函数会被调用。这里仅作为演示目的实现了三个命令:“开始游戏”,“设置”以及退出应用的功能。
相关推荐


















