2017-03-05 66 views
0

我正在爲pygame編寫一個paddle pong遊戲的代碼,在這個遊戲中球會從沒有打開槳的三面牆上彈開,當它碰到槳的牆而不是槳時,你失去了生命。我的問題是,我無法弄清楚碰撞檢測。以下是我迄今所做的:Pong Collision Pygame

import pygame, sys 
from pygame.locals import * 

pygame.init() 

screen_width = 640 
screen_height = 480 
Display = pygame.display.set_mode((screen_width, screen_height), 0, 32) 
pygame.display.set_caption('Lonely Pong') 

back = pygame.Surface((screen_width, screen_height)) 
background = back.convert() 
background.fill((255, 255, 255)) 

paddle = pygame.Surface((80, 20)) 
_paddle = paddle.convert() 
_paddle.fill((128, 0, 0)) 

ball = pygame.Surface((15, 15)) 
circle = pygame.draw.circle(ball, (0, 0, 0), (7, 7), 7) 
_ball = ball.convert() 
_ball.set_colorkey((0, 0, 0)) 

_paddle_x = (screen_width/2) - 40 
_paddle_y = screen_height - 20 
_paddlemove = 0 
_ball_x, _ball_y = 8, 8 
speed_x, speed_y, speed_circle = 250, 250, 250 
Lives = 5 

clock = pygame.time.Clock() 
font = pygame.font.SysFont("verdana", 20) 
paddle_spd = 5 

while True: 

    for event in pygame.event.get(): 
     if event.type == QUIT: 
      sys.exit() 
     if event.type == KEYDOWN: 
      if event.key == K_RIGHT: 
       _paddlemove = paddle_spd 
      elif event.key == K_LEFT: 
       _paddlemove = -paddle_spd 
     elif event.type == KEYUP: 
      if event.key == K_RIGHT: 
       _paddlemove = 0 
      elif event.key == K_LEFT: 
       _paddlemove = 0 

    Livespr = font.render(str(Lives), True, (0, 0, 0)) 
    Display.blit(background, (0, 0)) 
    Display.blit(_paddle, (_paddle_x, _paddle_y)) 
    Display.blit(_ball, (_ball_x, _ball_y)) 
    Display.blit(Livespr, ((screen_width/2), 5)) 

    _paddle_x += _paddlemove 

    passed = clock.tick(30) 
    sec = passed/1000 

    _ball_x += speed_x * sec 
    _ball_y += speed_y * sec 

    pygame.display.update() 

我一直有另一個問題是,當我啓動它,球不會出現在所有。請有人指點我正確的方向?第一

+0

我想你的代碼永遠不會越過事件的'在pygame的.event.get()',繪製代碼。繪圖代碼應該在內部循環中;修復縮進並重試。 – 9000

+0

但它像它唯一的跳繩畫球,因爲它吸引了槳和生命 – TheBudderBomb

+0

你檢查過「秒」不是零嗎?也許'秒=通過/ 1000.0'可以解決它。 – 9000

回答

2

第一件事情,球不會出現,因爲你沒有填充表面,您正在設置color_key:

_ball.set_colorkey((0, 0, 0)) 

應該

_ball.fill((0, 0, 0)) 

其次,碰撞檢測, pygame提供了一些功能,如碰撞點和碰撞。

https://www.pygame.org/docs/ref/rect.html#pygame.Rect.collidepoint

這意味着你將需要表面的矩形。通過這樣做:

my_surface.get_rect() 

https://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_rect

爲了與屏幕的邊緣碰撞,你總是可以做

if _ball_x <= 0 or _ball_y <= 0 or _ball_x >= 640 or _ball_y >= 480: 
    # collision detected 
+0

非常感謝你,生病了。 – TheBudderBomb