2014-10-31 22 views
-1

我對pygame來說是全新的,我正努力在我的遊戲中實現'laserblast'和'tarantula'之間的碰撞檢測。我已經閱讀了pygame.org上的各種表面和sprites以及其他網站(包括堆棧溢出)的文檔,但不幸的是我無法將自己的頭圍繞在他們的概念上。需要幫助實現簡單的碰撞檢測(PYGAME)

另外,我想遠離課堂,因爲我對他們不是很熟悉,我打算在後來的項目中發展我的知識。

我一直遇到的錯誤是

Traceback (most recent call last): 
    File "C:\Python27\jetfighterx.py", line 44, in <module> 
    if pygame.sprite.collide_rect(laserblast.rect, tarantula.rect): 
AttributeError: 'pygame.Surface' object has no attribute 'rect' 

當jetfighter拍攝朝敵人的激光;遊戲也不久之後崩潰。

我真的需要幫助開發一個簡單的解決方案來解決這個問題。

這裏是我的代碼:

import pygame, sys, pygame.mixer 
from pygame.locals import * 
import random 
pygame.init() 

bif="space.jpg" 
jf="spacefightersprite.png" 
enemy="TarantulaSpaceFighter.png" 

laser=pygame.mixer.Sound("LaserBlast.wav") 
screen=pygame.display.set_mode((1000,900),0,32) 
caption=pygame.display.set_caption("Jet Fighter X") 
background=pygame.image.load(bif).convert() 

jetfighterx=pygame.image.load(jf) 
jetfighterx=pygame.transform.scale(jetfighterx, (400,400)) 
tarantula=pygame.image.load(enemy) 
tarantula=pygame.transform.scale(tarantula, (100,100)) 
laserblast=pygame.image.load("C:\Python27\laser.png") 

ex,ey=450,0 
movex,movey=0,0 
clock=pygame.time.Clock() 
speed=300 
shoot_y=0 

while True: 
    mx,my=pygame.mouse.get_pos() 
    for event in pygame.event.get(): 
     if event.type==QUIT: 
      pygame.quit() 
      sys.exit() 
     if event.type==KEYDOWN: 
      if event.key==K_ESCAPE or event.key==K_q: 
        sys.exit() 
     if event.type==MOUSEBUTTONDOWN: 
      laser.play() 
      shoot_y=my-200 
      shoot_x=mx-16 
    if shoot_y>0: 
     screen.blit(laserblast, (shoot_x, shoot_y)) 
     shoot_y-=10 
     pygame.display.update() 
     if pygame.sprite.collide_rect(laserblast.rect, tarantula.rect): 
       print "COLLISION DETECTED!" 

    screen.blit(background, (0,0)) 
    screen.blit(jetfighterx,(mx-200,my-200)) 
    screen.blit(tarantula, (ex, ey)) 

    milli=clock.tick() 
    seconds=milli/1000. 
    dmy=seconds*speed 
    ey+=dmy 

    if ey>900: 
     ey=0 
     ex=random.randint(50,900) 

    update=pygame.display.update() 
+0

你將需要上課。沒有他們的代碼將非常混亂和複雜。除非你想創造大量的變量,否則創造諸如子彈和敵人之類的東西將很難在沒有課堂的情況下實現。 – Thedudxo 2014-10-31 19:32:49

回答

0

你或許應該在pygame的Surface類閱讀起來。你可以使用Surface.get_clip()來返回一個你可以檢查碰撞的矩形。另外,請考慮使用Rect.colliderect()方法而不是Sprite。使用,你的代碼將是

if(laserblast.get_clip().colliderect(tarantula.get_clip())) 

就像Thedudxo說,你應該真的考慮使用類爲您的遊戲元素。

+0

乾杯,你的解決方案正是我所期待的,但現在我有另一個問題,我希望它在激光的尖端與敵人接觸而不是重複印刷它時打印「碰撞檢測」一次,甚至在激光到達敵人之前......你有什麼想法可以解決這個問題嗎?我也意識到類是重要的,所以我會閱讀更多關於他們我一旦我把這個碰撞檢測的東西排序出來,順便說一句,如果它不是我的低代表haha – thebaldhen 2014-10-31 20:57:43

+0

我不知道,我已經想通了。 – thebaldhen 2014-10-31 21:20:33

+0

@thebaldhen優秀!我認爲你應該能夠接受我的答案作爲你的問題的解決方案,tho :) – 2014-11-01 01:24:30