我第一次尝试pygame,现在,我非常熟悉python作为一种语言,并且我一直在尝试重新创建Pong,就像带2个球拍和一个球的老式学校游戏一样。我似乎无法弄清楚如何使球从球拍上反射出来。我还没有寻找角度和东西,因为我无法自行解决。
Buttt我所想到的是获取一个坐标范围,即球拍的X和Y以及x&y +宽度和高度,如果球进入这些坐标,它就像在球上边界。我已经尝试过执行多个if语句,如下面的代码所示,但是我也尝试过将其作为单个语句来执行,但这不起作用。没有将调试打印IVE放入实际打印中,但是当我使用打印测试坐标范围时,它们看起来不错:D
将我的代码粘贴到此处,以便你们可以照常运行我的游戏。
Id非常感谢你们的帮助!
import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("First Game")
x = 50
y = 50
width = 10 #sets variables for the main paddle
height = 60
vel = 5
ballx = 250
bally = 250
radius = 5
direction = True #True is left, False is right
bvel = 4 #sets variables for the ball
angle = 0
coordxGT = 0
coordxLT = 0 #sets variables for the coordinate ranges of the first paddle for collision
coordyGT = 0
coordyLT = 0
def setCoords():
coordxGT = x
coordxLT = x + width
coordyGT = y #This function updates the coords throughout the main loop
coordyLT = y + height
coordxLT += radius
coordyLT += radius
run = True
while run == True:
pygame.time.delay(20)
for event in pygame.event.get(): #on quit, quit the game and dont throw up an error :)
if event.type == pygame.QUIT:
run = False
setCoords()
if direction == True: #Ball movement
ballx -= bvel
else:
ballx += bvel
if ballx<0:
ballx += bvel
direction = False
elif bally<0:
bally += bvel
elif ballx>495: #if the ball hits an edge
ballx -= bvel
direction = True
elif bally>495:
bally -= bvel
if ballx<coordxLT and ballx>coordxGT:
print("S1")
if bally<coordyLT and bally>coordyGT: #THE PART I CANT FIGURE OUT. If the ball lands within these ranges of coordinates, reflect it and change its direction
print("S2")
if direction == True:
print("YES")
ballx += bvel
direction = False
keys = pygame.key.get_pressed() #gets the keys pressed at that current time
if keys[pygame.K_DOWN]:
bally += bvel #Ball control (For debugging)
if keys[pygame.K_UP]:
bally -= bvel
if keys[pygame.K_w]:
y -= vel
if keys[pygame.K_a]:
x -= vel
if keys[pygame.K_s]: #Paddle controls
y += vel
if keys[pygame.K_d]:
x += vel
if x<0:
x += vel
if y<0:
y += vel
if x>80:
x -= vel #Stops the paddle from moving if it hits a boundary
if y>440:
#440 because window height - height of cube
y -= vel
win.fill((0,0,0))
pygame.draw.circle(win, (255, 255, 255), (ballx, bally), radius) #refreshes the screen
pygame.draw.rect(win,(255,255,255),(x, y, width, height))
pygame.display.update()
pygame.quit()
您很接近,但是您没有将变量coordxGT
,coordxLT
,coordxLT
,coordyLT
声明为global
。
def setCoords():
global coordxGT, coordxLT, coordxLT, coordyLT
coordxGT = x
coordxLT = x + width
coordyGT = y
coordyLT = y + height
coordxLT += radius
coordyLT += radius
注意,如果要在函数的全局名称空间中写入变量,则该变量已解释为全局变量。否则,将创建并设置函数范围内的新变量。参见global
statement。
global