我已经制作了这个代码,但是如果我复制它或其他东西我就无法制作更多按钮 所以无论如何我可以获得更多按钮,就像我设置这个代码一样? 是否可以放入def display_button()并在循环中调用它?
def Main():
pygame.font.init()
font = pygame.font.Font(None, 25)
my_font = pygame.font.SysFont("segoe print", 16)
button_surf = pygame.Surface((60, 40))
button_rect = button_surf.get_rect()
button_surf.fill(WHITE)
button_rect.center = (500, 750)
txt_surf = my_font.render("LEFT", 1, BLACK)
txt_rect = txt_surf.get_rect(center=(30,20))
button_surf.blit(txt_surf, txt_rect)
Seconds = 0
Frame=0
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
Screen.fill(BLACK)
Screen.blit(button_surf, button_rect)
这是我的代码
答案 0 :(得分:1)
您应该为按钮创建一个单独的功能:
def button(x, y, w, h, inactive, active, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
gameDisplay.blit(active, (x, y))
if click[0] == 1 and action is not None:
action()
else:
gameDisplay.blit(inactive, (x, y))
完成此操作后,您可以这样称呼它:
#For Example
button(100, 350, 195, 80, startBtn, startBtn_hover, game_loop)
这是每个参数的含义:
答案 1 :(得分:0)
Just repeat the same code with different rect locations, and different variable names.
button_surf2 = pygame.Surface((60, 40))
button_rect2 = button_surf.get_rect()
button_surf2.fill(WHITE)
button_rect2.center = (600, 850)
txt_surf2 = my_font.render("LEFT", 1, BLACK)
txt_rect2 = txt_surf2.get_rect(center=(30,20))
button_surf2.blit(txt_surf2, txt_rect2)
Or, if you want it a bit neater, you could make a button class.
def Button:
def __init__(self, width, height, center, text):
self.surface = pygame.Surface((width, height))
self.rect = self.surface.get_rect()
self.surface.fill(WHITE)
self.rect.center = center
self.textSurf = my_font.render(text, 1, BLACK)
self.textRect = self.textSurf.get_rect(center = (30, 20))
self.surf.blit(self.textSurf, self.textRect)
Then you should make a list of all your buttons, and iterate through them when you want to draw, or check for clicks.
答案 2 :(得分:0)
我认为你应该使用Groups
我使用这些,这是例子:
buttons = pygame.sprite.Group()
picnames = ["Play","Quit"]
place = y/2 - 10 * (len(picnames) - 1) - 8
for picname in picnames:
button = pygame.sprite.Sprite()
button.name = picname
button.image = pygame.image.load("pic/" + picname + ".PNG").convert_alpha()
button.rect = button.image.get_rect()
button.rect.center = (x/2, place)
place += 20
buttons.add(button)
buttons.draw(screen)
Here完全是我的代码。