2013-11-02 183 views
1

我使用Pygame和Python 3.2來製作遊戲。我必須瞭解如何使用碰撞檢測,以便玩家(ballpic)可以拿起物品。Pygame碰撞檢測無法正常工作

這裏是我的代碼:

from pygame import * #import pygame 
bg = image.load('BG.png') 
ballpic = image.load('PlayerForward1.png') #Set the variable "ballpic" to ball.png 
seed = image.load('Sunflowerseed.png') 
ballpic.set_colorkey((0,0,0)) 
from random import randint 
numballs = 10 
delay = 5 
red  = (0, 0, 255) 
done=False 
ballx = 0 #Ball Coordinates 
bally=0 
ballxmove = 0 

ballymove = 0 #Set the direction of the ball 

init() #Start Pygame 

key.set_repeat(10,10) 
screen = display.set_mode((640, 480)) #Set the size of the window 
display.set_caption("RPG game") #Set the window name 
event.set_grab(1) 
if ballx > 600: 
    ballx =ballx-4 
if ballx < 0: 
    ballx =ballx+4 
if bally > 440: 

    bally=bally-4 
if bally < 0: 
    bally=bally+4 
mixer.music.load('bgm.flac') 
#mixer.music.play(-1, 0.0) 
while done == False: 
    screen.fill(0)  #Fill the screen with black 
    screen.blit(bg, (ballx,bally)) 
    screen.blit(ballpic, (320,240))#Draw ball 
    screen.blit(seed, (ballx,240)) 
    display.update() #Update the screen 
    time.delay(9)   #Slow it down 
    ballx=ballx + ballxmove #Update ball position 
    bally=bally + ballymove 
    for e in event.get():  #Check for ESC pressed 
     if e.type == KEYDOWN: 
      if e.key ==K_LEFT: 
       ballpic=image.load('PlayerReversed.png') 
       print(ballx,bally) 
       ballx= (ballx+4) 
      if e.key ==K_RIGHT: 
       ballpic=image.load('PlayerForward1.png') 
       print(ballx,bally) 
       ballx=ballx-4 
      if e.key == K_ESCAPE: 
       quit() 

我的背景(BG)在ballx變量運行,因此屏幕上出現滾動。 我需要檢測ballpicseed是否碰撞。

+0

您需要'pygame.sprite.Sprite',因此您需要關於'class'和'object programing'的知識 – furas

+0

另請參見[pygame.sprite.collide_rect](http://www.pygame.org/docs/ref/ sprite.html#pygame.sprite.collide_rect) – furas

回答