这是我到目前为止的代码,我可以移动它并放置一个可以拾取的 blip,我只需要知道如何注册它并将 blip 移动到新的随机位置! 我对 pygame 很陌生,对 python 也不是 100% 流利,但我还不错。如果有适合中级编码员使用 Python 的 pdf:那就太好了!
import sys, pygame, os, math
from random import randint
pygame.init()
size = width, height = 800, 600
speed = [2, 2]
black = 1, 1, 1
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Pick up the squares!')
UP='up'
DOWN='down'
LEFT='left'
RIGHT='right'
ball = pygame.image.load("ball.png")
ballrect = ball.get_rect()
ballx = 400
bally = 300
blip = pygame.image.load("blip.png")
bliprect = blip.get_rect()
blipx = randint(1,800)
blipy = randint(1,600)
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))
clock = pygame.time.Clock()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
ballx -= 5
if keys[pygame.K_RIGHT]:
ballx += 5
if keys[pygame.K_UP]:
bally -= 5
if keys[pygame.K_DOWN]:
bally +=5
screen.fill(black)
screen.blit(ball, (ballx,bally))
screen.blit(blip, (blipx, blipy))
pygame.display.update()
clock.tick(40)
最佳答案
使用矩形的colliderect
方法:
if ballrect.colliderect(bliprect):
print 'Do something here'
关于python - 如何使用 pygame 检测两个 Sprite 的碰撞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28488088/