【发布时间】:2019-03-14 17:07:13
【问题描述】:
对于我的 Dofe Gold,我在 pygame 中创建了一个乒乓球游戏,因为这是我第一次使用 pygame,所以我没有使用 sprite,因为我没有想到。我现在想要一个解决方案,它可以让我解决我的问题,而无需用精灵完全重写我的代码。注意:我希望这仍然是我的代码,所以我不会接受其他人重写的解决方案,因为这会带走任何成就感。提前谢谢了。 我的代码:
import pygame
import random
global vel
run = True
def pong():
global run
collision = 0
pygame.init()
screen = (600, 600)
window = pygame.display.set_mode((screen))
pygame.display.set_caption("Pong")
x = 300
y = 590
coords = (300, 150)
width = 175
height = 10
vel = 10 - selection
velx = 10
vely = 10
while run == True:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x>0:
x -= vel
elif keys[pygame.K_RIGHT] and x<600-width:
x += vel
if event.type == pygame.MOUSEBUTTONUP:
pygame.quit()
quit()
paddlecoords = (x, y, width, height)
window.fill((255, 255, 255))
ball = pygame.draw.circle(window, (255,0,255), coords,(35), (0))
paddle = pygame.draw.rect(window, (0, 0, 0), paddlecoords)
pygame.display.update()
coords=((int(coords[0])+velx), (int(coords[1])+vely))
if coords[0]>600-35:
velx = -velx
elif coords[0]<35:
velx = -velx
elif coords[1]<35:
vely = -vely
elif coords[1]>600-35:
vely = -vely
selection =input("Do you want to play\n1)easy\n2)medium\n3)hard\n4)impossible?\n")
if selection.isdigit():
if 0 < int(selection) < 5:
selection = int(selection)
selection = (selection-1)*2
else:
print("must be between 1 and 4")
else:
print("number must be an integer")
quit()
pong()
【问题讨论】:
-
现在我从未与 pygame 合作过,对此我无能为力,但是:我认为 global 并没有像你认为的那样做。我想您想将
vel声明为全局变量?如果是这样:不需要全局,但请考虑将其设为VEL(请参阅此处了解随机实际上做了什么stackoverflow.com/questions/4693120/…)以及为什么您可能想将其命名为VELpython.org/dev/peps/pep-0008/#naming-conventions - 见点“常量” -
如果您搜索“Python 碰撞检测”这个短语,您会发现可以比我们在此处的答案中更好地解释它的资源。另外,请注意您已经实现了球和墙之间的碰撞检测。简单地适应球和桨。
标签: python pygame collision-detection pong