那今天來做開始結束按鈕。
font = pygame.font.SysFont(None, 55)
def display_message(text, color, y_displace=0):
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect(center=(screen_width // 2, screen_height // 2 + y_displace))
screen.blit(text_surface, text_rect)
def draw_button(text, rect, color, hover_color):
mouse_pos = pygame.mouse.get_pos()
if rect.collidepoint(mouse_pos):
pygame.draw.rect(screen, hover_color, rect)
else:
pygame.draw.rect(screen, color, rect)
text_surface = font.render(text, True, black)
text_rect = text_surface.get_rect(center=rect.center)
screen.blit(text_surface, text_rect)
def wait_for_button_click(button_rect):
waiting = True
while waiting:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if button_rect.collidepoint(event.pos):
waiting = False
pygame.display.flip()
start_button_rect = pygame.Rect(screen_width // 2 - 100, screen_height // 2 - 50, 200, 100)
restart_button_rect = pygame.Rect(screen_width // 2 - 150, screen_height // 2, 300, 100)
screen.fill(white)
draw_button("Start", start_button_rect, button_color, button_hover_color)
pygame.display.flip()
wait_for_button_click(start_button_rect)
screen.fill(white)
display_message("Game Over", black, -50)
draw_button("Restart", restart_button_rect, button_color, button_hover_color)
pygame.display.flip()
wait_for_button_click(restart_button_rect)
這邊有參考一些網路上的開始與結束的程式編輯,再加上我自己的需求,做出了目前這個版本的開始與結束,中間出了蠻多差錯,但都有一一修正,最好笑的是在用 VS Code 的時候我按鈕打中文,他跑出幾個方塊,我還一直在想說為什麼無法正常顯示,結果最後用英文就解決了。
那今天就先這樣。