我最近开始使用python和pygame。我的第一个项目是创建一个游戏,你必须点击随机出现在屏幕上的块。经过数小时的研究和解决问题后,我还没有找到解决方案。我想我在定制代码的其他答案时并不擅长。这是代码:
import pygame
import time
import random
pygame.init()
game_width = 800
game_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
gameDisplay = pygame.display.set_mode((game_width, game_height))
pygame.display.set_caption('Click It')
clock = pygame.time.Clock()
def text_objects(text, font):
textSurface = font.render(text, True, red)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def failed():
message_diplay('You Failed')
def game_loop():
thing_height = 100
thing_width = 100
thing_startx = random.randrange(0, game_width-thing_width)
thing_starty = random.randrange(0, game_height-thing_height)
rectangle = (thing_startx, thing_starty, thing_width, thing_height)
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
failed = False
while not failed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
things(thing_startx, thing_starty, thing_width, thing_height, blue )
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
click = rectangle.collidepoint(pygame.mouse.get_pos())
if click == 1:
print ('Clicked!!')
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
答案 0 :(得分:2)
您正在创建元组,并且正在尝试使用方法collidepoint
(元组不具备)。您可能打算使用Rect
对象,因此请更改行
rectangle = (thing_startx, thing_starty, thing_width, thing_height)
到
rectangle = pygame.Rect(thing_startx, thing_starty, thing_width, thing_height)