Python 撞球游戏
我正在为pygame中的一个单桨乒乓球游戏编写代码,在这个游戏中,球会从没有桨的三面墙上弹起,当它击中桨壁而不是桨时,它会让你失去生命。我的问题是,我无法找出碰撞检测来执行此操作。以下是我迄今为止所做的工作:Python 撞球游戏,python,pygame,collision-detection,pong,Python,Pygame,Collision Detection,Pong,我正在为pygame中的一个单桨乒乓球游戏编写代码,在这个游戏中,球会从没有桨的三面墙上弹起,当它击中桨壁而不是桨时,它会让你失去生命。我的问题是,我无法找出碰撞检测来执行此操作。以下是我迄今为止所做的工作: import pygame, sys from pygame.locals import * pygame.init() screen_width = 640 screen_height = 480 Display = pygame.display.set_mode((screen_w
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()
我遇到的另一个问题是,当我启动它时,球根本不出现。有人能告诉我正确的方向吗?首先,球不会出现,因为你没有填充表面,你正在设置颜色键:
_ball.set_colorkey((0, 0, 0))
应该是
_ball.fill((0, 0, 0))
第二,对于碰撞检测,pygame提供了一些功能,如collidepoint和colliderect
这意味着您需要曲面的矩形。为此,请执行以下操作:
my_surface.get_rect()
为了与屏幕边缘发生碰撞,您始终可以这样做
if _ball_x <= 0 or _ball_y <= 0 or _ball_x >= 640 or _ball_y >= 480:
# collision detected
如果球=480:
#检测到碰撞
首先,球不会出现,因为您没有填充曲面,您正在设置颜色键:
_ball.set_colorkey((0, 0, 0))
应该是
_ball.fill((0, 0, 0))
第二,对于碰撞检测,pygame提供了一些功能,如collidepoint和colliderect
这意味着您需要曲面的矩形。为此,请执行以下操作:
my_surface.get_rect()
为了与屏幕边缘发生碰撞,您始终可以这样做
if _ball_x <= 0 or _ball_y <= 0 or _ball_x >= 640 or _ball_y >= 480:
# collision detected
如果球=480:
#检测到碰撞
我想您的代码永远不会通过pygame.event.get()中事件的到绘图代码。图纸代码应在内部循环中;修正缩进,然后再试一次。但这就像只是跳过了拉球一样,因为它会拉球拍和直播。您是否检查sec
是否为零?也许sec=passed/1000.0
可以修复它。Nah仍然没有修复任何东西。我假设您的代码从未通过pygame.event.get()
中事件的到绘图代码。图纸代码应在内部循环中;修正缩进,然后再试一次。但这就像只是跳过了拉球一样,因为它会拉球拍和直播。您是否检查sec
是否为零?也许sec=passed/1000.0
可以解决它。不,仍然没有解决任何问题