我目前正在使用Python和PyGame开发游戏。我已经为主选项按钮制作了图像精灵,但我似乎无法弄清楚如何使图像可以点击,这将把我带到不同的屏幕。源代码:
import os
import sys
import pygame
import time
class Colors:
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
dark_red = (102, 0, 0)
grey = (128, 128, 128)
dark_grey = (51, 51, 51)
class Variables:
screen_w = 1000
screen_h = 600
battleButton = pygame.image.load("Images/battle_button.png")
shopButton = pygame.image.load("Images/shop_button.png")
saveButton = pygame.image.load("Images/save_button.png")
equippedItem = pygame.image.load("Images/equipped.png")
creditsButton = pygame.image.load("Images/credits_button.png")
baseballBat = pygame.image.load("Images/baseball_bat.png")
baseballBat = pygame.transform.scale(baseballBat, (250, 250))
playerHealthMax = 100
playerHealthMin = 0
playerHealth = playerHealthMax
playerCash = 0
pygame.font.init()
gameFont = pygame.font.SysFont("Tweaky", 70)
title = gameFont.render("Causatum", 1, (Colors.black))
mainFont = pygame.font.SysFont("Arial Rounded MT Bold", 50)
equippedWeap = mainFont.render("Equipped", 1, (Colors.black))
cash = mainFont.render("Cash: ${}".format(playerCash), 1,
(Colors.black))
health = mainFont.render("Health: {}".format(playerHealth), 1,
(Colors.black))
gameVersion = mainFont.render("v1.0.0", 1, (Colors.black))
screen = pygame.display.set_mode((Variables.screen_w, Variables.screen_h))
pygame.display.set_caption("Causatum")
screen.fill(Colors.black)
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(Colors.grey)
screen.blit(Variables.battleButton, (0, 170))
screen.blit(Variables.shopButton, (0, 240))
screen.blit(Variables.saveButton, (0, 310))
screen.blit(Variables.title, (330, 0))
screen.blit(Variables.equippedItem, (645, 250))
screen.blit(Variables.baseballBat, (735, 230))
screen.blit(Variables.equippedWeap, (723, 215))
screen.blit(Variables.creditsButton, (0, 380))
screen.blit(Variables.cash, (0, 50))
screen.blit(Variables.health, (0, 0))
screen.blit(Variables.gameVersion, (905, 0))
pygame.display.flip()
感谢任何形式的帮助。感谢。
答案 0 :(得分:1)
尝试这样的事情:
#in 'Variables' add this line
battleButton_rect = battleButton.get_rect(centerx = 0, centery = 170)
#new function, outside any classes
def collide(mouseX, mouseY, rect): #new function for checking the collision of the mouse with a button
return (mouseX >= rect.x-rect.width/2 and mouseX <= rect.x+rect.width/2 and mouseY >= rect.y-rect.height/2 and mouseY <= rect.y+rect.height/2)
# in 'while running'
if pygame.mouse.get_pressed()[0]: #0 for left button, 1 for right, 2 for middle
mouse_pos = pygame.mouse.get_pos()
if collide(mouse_pos[0], mouse_pos[1], Variables.battleButton_rect):
#code for battle button clicked here
#replace
screen.blit(Variables.battleButton, (0, 170))
#with
screen.blit(Variables.battleButton, Variables.battleButton_rect)
当然,这仅适用于战斗按钮。您需要为您使用的每个按钮添加一个Rect。另外,我建议在里面创建一个带有碰撞功能的按钮类,并拥有一组可以迭代的按钮而不会使代码卷曲。但以上是一个快速而肮脏的解决方案。
希望这有帮助!