1 回答
TA贡献1825条经验 获得超6个赞
你必须删除错误button()
并且你必须button()
使用game_intro()
要解释的太多了,所以我只展示了最少的工作代码。
按钮可以工作,但仍然不理想。如果新场景在同一个地方有按钮就会有问题——它会自动点击它——但它需要完全不同的代码。更多关于GitHub
import pygame
# --- constants --- (UPPER_CASE_NAMES)
RED = (200, 0, 0)
GREEN = (0, 200, 0)
BRIGHT_RED = (255, 0, 0)
BRIGHT_GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
# --- all classes --- (CamelCaseNames)
class Player:
pass
# ... code ...
class Platform:
pass
# ... code ...
# etc.
# --- all functions --- (lower_case_names)
def text_objects(text, font):
image = font.render(text, True, BLACK)
rect = image.get_rect()
return image, rect
def button(window, msg, x, y, w, h, ic, ac, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(window, ac,(x,y,w,h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(window, ic,(x,y,w,h))
image = small_font.render(msg, True, BLACK)
rect = image.get_rect()
rect.center = (x+(w/2), y+(h/2))
window.blit(image, rect)
def game_intro():
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
window.fill((255,255,255))
image, rect = text_objects("Stolen Hearts!", large_font)
rect.center = (400, 400)
window.blit(image, rect)
button(window, "Start Game", 150, 450, 120, 50, GREEN, BRIGHT_GREEN, main_game)
button(window, "Quit Game", 350, 450, 120, 50, RED, BRIGHT_RED, quit_game)
pygame.display.update()
clock.tick(15)
def main_game():
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
window.fill((255,255,255))
image, rect = text_objects("Main Game", large_font)
rect.center = (400, 400)
window.blit(image, rect)
button(window, "Intro", 550, 450, 120, 50, GREEN, BRIGHT_GREEN, game_intro)
button(window, "Quit Game", 350, 450, 120, 50, RED, BRIGHT_RED, quit_game)
pygame.display.update()
clock.tick(15)
def quit_game():
print("You quit game")
pygame.quit()
quit()
# --- main ---
pygame.init()
window = pygame.display.set_mode((800, 800))
# it has to be after `pygame.init()`
#small_font = pygame.font.Font("freesansbold.ttf", 20)
#large_font = pygame.font.Font('BLOODY.ttf', 115)
small_font = pygame.font.Font(None, 20)
large_font = pygame.font.Font(None, 115)
clock = pygame.time.Clock()
game_intro()
顺便说一句:我也以不同的方式组织代码
所有常量值直接放在一个地方
imports
,它们使用UPPER_CASE_NAMES
(PEP8) 和所有类都在一个地方 - 直接在常量之后和之前
pygame.init()
- 他们使用CamelCaseNames
(PEP8)所有功能都在一个地方 - 课后和课前
pygame.init()
- 他们使用lower_case_names
(PEP8)
添加回答
举报