我一直在看一堆教程和新的pygame和一般的编码。我看的教程中没有一个对我有帮助。我的目标是,当用户将鼠标悬停在按钮上时,按钮可以改变为不同的颜色。下面是我目前为止主菜单的全部代码。在
import pygame
import time
import random
pygame.init()
size = (800, 600)
screen = pygame.display.set_mode(size)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
pygame.display.set_caption("Basketball Shootout")
clock = pygame.time.Clock()
#GAME INTRO
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
#Font's and text
font = pygame.font.SysFont ("Times New Norman", 60)
text = font.render ("", True, WHITE)
#Background Image
background_images = pygame.image.load("greybackground.jpg").convert()
screen.blit(background_images, [0,0])
screen.blit(text, (150, 50))
#Background Music
pygame.mixer.music.load('game.ogg')
pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)
pygame.mixer.music.play()
pygame.display.update()
clock.tick(15)
#BUTTONS
screen.blit(text, (150, 50))
pygame.draw.rect(screen,(0,0,0),(300,300,205,80));
pygame.draw.rect(screen,(0,0,0),(300,400,205,80));
pygame.draw.rect(screen,(0,0,0),(300,500,205,80));
font = pygame.font.SysFont ("Times New Norman, Arial", 30)
text = font.render ("START", True, WHITE)
screen.blit(text, (340, 320))
font = pygame.font.SysFont ("Times New Norman, Arial", 30)
text = font.render ("OPTIONS", True, WHITE)
screen.blit(text, (340, 420))
font = pygame.font.SysFont ("Times New Norman, Arial", 30)
text = font.render ("ABOUT", True, WHITE)
screen.blit(text, (340, 520))
pygame.display.flip();
#Quit Pygame
game_intro()
pygame.quit
我建议将按钮数据(文本表面、矩形、颜色)存储在列表列表中。当鼠标移动时,
pygame.MOUSEMOTION
事件被添加到事件队列中。在事件循环中,检查鼠标是否移动,然后在按钮上迭代,并将colliding buttons的颜色设置为悬停颜色,将其他颜色重置为黑色。在for循环中Blit矩形和文本表面。在实际上,我建议定义一个
Button
类,但我不确定您是否已经熟悉类/面向对象编程。在按钮还需要回调函数来实际执行某些操作。看看我的答案:https://stackoverflow.com/a/47664205/6220679
相关问题 更多 >
编程相关推荐