我怎样才能防止球粘在不存在的物体上
How can i keep a ball from sticking to an object that isn't there
我正在学校学习我的第一门编程课程,Python。我在 Windows 7,python 3.4.3。我的项目是基于 Pong 的游戏。球拍是长方形,球是圆形。我让球在球拍周围弹跳。我的游戏包含在按住 SPACE BAR 时让球粘在球拍上的功能,您可以使用向上向下箭头键移动球和球拍。这行得通!但是,如果我按住 space 条并且球离球拍很远,球就会粘在球拍的 X 位置,就好像它粘在了一个不存在的球拍上一样。我尝试在没有帮助的情况下在代码中添加打印语句。我在网上搜索但没有什么能解决我的问题。我的导师被难住了,并建议你们提供快速、优质的服务。希望他是对的!!如果您能指出任何其他错误,将不胜感激 这是我的代码:
# Pong game
# By Bill B
# Fall 2015
#
# My first post had an issue. This should work
# Sorry this is my first posting... AAAaaa... 2nd now
import pygame, time
pygame.init()
# Define Colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
blue4 = (170, 170, 220)
boardWid = 800 # Game Board width
boardHgt = 600 # Game board height
pHgt = 100 # Paddle height
pWith = 10 # Paddle Width
font = pygame.font.SysFont(None,48)
gameDisplay = pygame.display.set_mode((boardWid,boardHgt))
#print(gameDisplay)
pygame.display.set_caption("Kong Pong")
#====================================================
def msgToScreen( msg, color ):
screen_text = font.render(msg, True, color)
gameDisplay.blit(screen_text, [boardWid/4,boardHgt/2])
pygame.display.update()
#time.sleep(3)
#====================================================
def scoreScreen( score, balls, color ):
# Display the Balls Left and the Score
msg = "Balls Left " + str(balls) + " Score " + str(score)
screen_text = font.render(msg, True, color)
gameDisplay.blit(screen_text, [boardWid/4,10])
#====================================================
def showCongrats():
# Displat the Congratulations/Next Level screen
gameDisplay.fill(blue4)
msgToScreen("Congratulations... ",red)
time.sleep(2)
gameDisplay.fill(blue4)
msgToScreen("You go to the next level",red)
time.sleep(3)
#====================================================
def gameLoop(lev, score): # passing the game level
balls = 3 # number of balls allowed
ball = 0 # the current ball being played
hits = 0 # how many times ball hits paddle
maxHits = 5 # how many times ball hits paddle
for ball in range(1,balls+1):
FPS = 60 # set Frames Per Seconds
gameExit = False # Exit Game flag
spaceKey = False # space bar flag
countSpKy = 0 # Counts the iterations while spaceKey is true
speed = 5 # Speed of Ball and Paddle times the level
padX = boardWid - 20 # Paddle upper lft corner start X position
padY = 300 # Paddle upper lft corner start Y position
padY_new = 0 # New Paddle Y position movement variable
pY = 0 # Where Ball Hits paddle to position ball at that spot
ballX = 400 # Ball upper lft corner start X position
ballY = 300 # Ball upper lft corner start X position
ballX_new = speed # New Ball X position movement variable
ballR = 10 # Ball Radius
ballY_new = 0 # New Ball Y position movement variable
clock = pygame.time.Clock()
gameExit = False
while not gameExit:
print("\tInside the While Ball = ",ball)
for event in pygame.event.get():
print("\t\tInside the For Event Ball = ",ball)
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP: # If up arrow paddle goes up
padY_new = -speed
if event.key == pygame.K_DOWN: # If down arrow paddle goes down
padY_new = speed
if event.key == pygame.K_SPACE:
ballX += ballX_new # repositions Ball X position
ballY += ballY_new # repositions Ball Y position
spaceKey = True
if event.type == pygame.KEYUP: # check up/down arrow keys and space bar
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
padY_new = 0 # if no arrow key, stop paddle
if event.key == pygame.K_SPACE:
spaceKey = False # reset use of space bar flag
# Check ball bounderies
if ballX < 0: # if ball hits left wall
ballX_new = speed
countSpKy = 0 # reinitialize the spaceKey count
pY = 0 # reinitialize the Ball/Paddle spacer
elif ballX >= boardWid:
gameExit = True
elif ballY < 0: # if ball hits floor
ballY_new = speed
elif ballY >= boardHgt: # if ball hits cieling
ballY_new = -speed
# Check for space key down
if not spaceKey: # If NOT down
padY += padY_new # repositions paddle
ballX += ballX_new # repositions Ball X position
ballY += ballY_new # repositions Ball Y position
else: # If space bar down
# while spaceKey is down and ball is on the paddle make
# ball stick to the paddle
if (ballX > padX - 2 and ballX < padX + pWith ) or \
(ballX + ballR > padX -2 and ballX + ballR < padX + pWith):
if (ballY > padY and ballY < padY + pHgt) or \
(ballY + ballR > padY and ballY + ballR < padY + pHgt):
if countSpKy == 0:
pY = ballY - padY # place where the ball hits the paddle
score += 5 # add to score
hits += 1 # add to hits
if hits == maxHits:
showCongrats()
return score
#else:
# pY = 0
countSpKy += 1
print("pY = ", pY)
print("padY =",padY)
print("ballY = ",ballY)
ballX = padX -5 # repositions Ball X position
ballY = padY + pY # repositions Ball Y position to the paddle
else:
ballX += ballX_new # repositions Ball X position
ballY += ballY_new # repositions Ball Y position
padY += padY_new # repositions paddle
# draw object on screen [start, location, ]
gameDisplay.fill(blue4)
pygame.draw.rect(gameDisplay, red, [padX,padY, pWith, pHgt])
pygame.draw.circle(gameDisplay, black, [ballX, ballY], ballR)
scoreScreen( score, balls, blue )
pygame.display.update()
# IF the ball hits the paddle add to score
if (ballX > padX and ballX < padX + pWith) or (ballX + ballR > padX and ballX + ballR < padX + pWith):
if (ballY > padY and ballY < padY + pHgt) or (ballY + ballR > padY and ballY + ballR < padY + pHgt):
if ballY_new == 0:
ballY_new = -speed -2
ballX_new = -speed
if not spaceKey:
score += 5
hits += 1
if hits == maxHits: # When you reach the end of a level
showCongrats()
return score
# check the boundries of the paddle
if padY <= 0: # if top of paddle hits top of screen
padY = 0 # stop the paddle
if padY + pHgt >= boardHgt: # if bottom of paddle hits bottom of screen
padY = boardHgt - pHgt # stop the paddle
clock.tick(FPS+ (25 * lev)) # Set frames per second
msgToScreen("S O R R Y... You Lose a Ball",red)
balls -= 1
pygame.display.update()
time.sleep(3)
return score
# END OF GAMELOOP()
#====================================================
#================ Main Program ====================
score = 0 # keepa the score
for lev in [ 1, 2 ]:
score = gameLoop(lev, score)
gameDisplay.fill(blue4)
msgToScreen("S O R R Y... Game Over",red)
#balls -= 1
time.sleep(3)
pygame.quit()
quit()
我在三个不同的系统上试过你的代码:
- MacosX Python 2.6
- Win32 Python2.7
- Win32 Python3.4
在他们每个人身上,我都无法复制你提到的问题。
如果我在球离桨足够远(100 像素左右)时按下 space 栏,球会保持 运行 并且不会停止。
我想你的系统可能有问题(我不知道是哪一个)。
我建议你在另一台电脑上试试你的代码。
编辑:
问题是你忘了处理一个条件。换句话说,您忘记了 else。
我在下面的代码中进行了更正,但请注意:不要复制和粘贴代码,因为缩进可能会错一个 space。只需要在你的代码中写上带大写注释的三行,就可以了:
else:
if (ballX > padX - 2 and ballX < padX + pWith ) or \
(ballX + ballR > padX -2 and ballX + ballR < padX + pWith):
if (ballY > padY and ballY < padY + pHgt) or \
(ballY + ballR > padY and ballY + ballR < padY + pHgt):
if countSpKy == 0:
pY = ballY - padY
score += 5
hits += 1
if hits == maxHits:
showCongrats()
return score
#else:
# pY = 0
countSpKy += 1
print("pY = ", pY)
print("padY =",padY)
print("ballY = ",ballY)
ballX = padX -5
ballY = padY + pY
else: # THE CONDITION WERE THE Y WERE NOT TEH SAME AS THE PADDLE WAS NOT HANDLED
ballX += ballX_new # THEREFORE IT JUST CHECKED
ballY += ballY_new # THE X COORDINATE
else:
ballX += ballX_new
ballY += ballY_new
padY += padY_new
我正在学校学习我的第一门编程课程,Python。我在 Windows 7,python 3.4.3。我的项目是基于 Pong 的游戏。球拍是长方形,球是圆形。我让球在球拍周围弹跳。我的游戏包含在按住 SPACE BAR 时让球粘在球拍上的功能,您可以使用向上向下箭头键移动球和球拍。这行得通!但是,如果我按住 space 条并且球离球拍很远,球就会粘在球拍的 X 位置,就好像它粘在了一个不存在的球拍上一样。我尝试在没有帮助的情况下在代码中添加打印语句。我在网上搜索但没有什么能解决我的问题。我的导师被难住了,并建议你们提供快速、优质的服务。希望他是对的!!如果您能指出任何其他错误,将不胜感激 这是我的代码:
# Pong game
# By Bill B
# Fall 2015
#
# My first post had an issue. This should work
# Sorry this is my first posting... AAAaaa... 2nd now
import pygame, time
pygame.init()
# Define Colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
blue4 = (170, 170, 220)
boardWid = 800 # Game Board width
boardHgt = 600 # Game board height
pHgt = 100 # Paddle height
pWith = 10 # Paddle Width
font = pygame.font.SysFont(None,48)
gameDisplay = pygame.display.set_mode((boardWid,boardHgt))
#print(gameDisplay)
pygame.display.set_caption("Kong Pong")
#====================================================
def msgToScreen( msg, color ):
screen_text = font.render(msg, True, color)
gameDisplay.blit(screen_text, [boardWid/4,boardHgt/2])
pygame.display.update()
#time.sleep(3)
#====================================================
def scoreScreen( score, balls, color ):
# Display the Balls Left and the Score
msg = "Balls Left " + str(balls) + " Score " + str(score)
screen_text = font.render(msg, True, color)
gameDisplay.blit(screen_text, [boardWid/4,10])
#====================================================
def showCongrats():
# Displat the Congratulations/Next Level screen
gameDisplay.fill(blue4)
msgToScreen("Congratulations... ",red)
time.sleep(2)
gameDisplay.fill(blue4)
msgToScreen("You go to the next level",red)
time.sleep(3)
#====================================================
def gameLoop(lev, score): # passing the game level
balls = 3 # number of balls allowed
ball = 0 # the current ball being played
hits = 0 # how many times ball hits paddle
maxHits = 5 # how many times ball hits paddle
for ball in range(1,balls+1):
FPS = 60 # set Frames Per Seconds
gameExit = False # Exit Game flag
spaceKey = False # space bar flag
countSpKy = 0 # Counts the iterations while spaceKey is true
speed = 5 # Speed of Ball and Paddle times the level
padX = boardWid - 20 # Paddle upper lft corner start X position
padY = 300 # Paddle upper lft corner start Y position
padY_new = 0 # New Paddle Y position movement variable
pY = 0 # Where Ball Hits paddle to position ball at that spot
ballX = 400 # Ball upper lft corner start X position
ballY = 300 # Ball upper lft corner start X position
ballX_new = speed # New Ball X position movement variable
ballR = 10 # Ball Radius
ballY_new = 0 # New Ball Y position movement variable
clock = pygame.time.Clock()
gameExit = False
while not gameExit:
print("\tInside the While Ball = ",ball)
for event in pygame.event.get():
print("\t\tInside the For Event Ball = ",ball)
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP: # If up arrow paddle goes up
padY_new = -speed
if event.key == pygame.K_DOWN: # If down arrow paddle goes down
padY_new = speed
if event.key == pygame.K_SPACE:
ballX += ballX_new # repositions Ball X position
ballY += ballY_new # repositions Ball Y position
spaceKey = True
if event.type == pygame.KEYUP: # check up/down arrow keys and space bar
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
padY_new = 0 # if no arrow key, stop paddle
if event.key == pygame.K_SPACE:
spaceKey = False # reset use of space bar flag
# Check ball bounderies
if ballX < 0: # if ball hits left wall
ballX_new = speed
countSpKy = 0 # reinitialize the spaceKey count
pY = 0 # reinitialize the Ball/Paddle spacer
elif ballX >= boardWid:
gameExit = True
elif ballY < 0: # if ball hits floor
ballY_new = speed
elif ballY >= boardHgt: # if ball hits cieling
ballY_new = -speed
# Check for space key down
if not spaceKey: # If NOT down
padY += padY_new # repositions paddle
ballX += ballX_new # repositions Ball X position
ballY += ballY_new # repositions Ball Y position
else: # If space bar down
# while spaceKey is down and ball is on the paddle make
# ball stick to the paddle
if (ballX > padX - 2 and ballX < padX + pWith ) or \
(ballX + ballR > padX -2 and ballX + ballR < padX + pWith):
if (ballY > padY and ballY < padY + pHgt) or \
(ballY + ballR > padY and ballY + ballR < padY + pHgt):
if countSpKy == 0:
pY = ballY - padY # place where the ball hits the paddle
score += 5 # add to score
hits += 1 # add to hits
if hits == maxHits:
showCongrats()
return score
#else:
# pY = 0
countSpKy += 1
print("pY = ", pY)
print("padY =",padY)
print("ballY = ",ballY)
ballX = padX -5 # repositions Ball X position
ballY = padY + pY # repositions Ball Y position to the paddle
else:
ballX += ballX_new # repositions Ball X position
ballY += ballY_new # repositions Ball Y position
padY += padY_new # repositions paddle
# draw object on screen [start, location, ]
gameDisplay.fill(blue4)
pygame.draw.rect(gameDisplay, red, [padX,padY, pWith, pHgt])
pygame.draw.circle(gameDisplay, black, [ballX, ballY], ballR)
scoreScreen( score, balls, blue )
pygame.display.update()
# IF the ball hits the paddle add to score
if (ballX > padX and ballX < padX + pWith) or (ballX + ballR > padX and ballX + ballR < padX + pWith):
if (ballY > padY and ballY < padY + pHgt) or (ballY + ballR > padY and ballY + ballR < padY + pHgt):
if ballY_new == 0:
ballY_new = -speed -2
ballX_new = -speed
if not spaceKey:
score += 5
hits += 1
if hits == maxHits: # When you reach the end of a level
showCongrats()
return score
# check the boundries of the paddle
if padY <= 0: # if top of paddle hits top of screen
padY = 0 # stop the paddle
if padY + pHgt >= boardHgt: # if bottom of paddle hits bottom of screen
padY = boardHgt - pHgt # stop the paddle
clock.tick(FPS+ (25 * lev)) # Set frames per second
msgToScreen("S O R R Y... You Lose a Ball",red)
balls -= 1
pygame.display.update()
time.sleep(3)
return score
# END OF GAMELOOP()
#====================================================
#================ Main Program ====================
score = 0 # keepa the score
for lev in [ 1, 2 ]:
score = gameLoop(lev, score)
gameDisplay.fill(blue4)
msgToScreen("S O R R Y... Game Over",red)
#balls -= 1
time.sleep(3)
pygame.quit()
quit()
我在三个不同的系统上试过你的代码:
- MacosX Python 2.6
- Win32 Python2.7
- Win32 Python3.4
在他们每个人身上,我都无法复制你提到的问题。 如果我在球离桨足够远(100 像素左右)时按下 space 栏,球会保持 运行 并且不会停止。
我想你的系统可能有问题(我不知道是哪一个)。 我建议你在另一台电脑上试试你的代码。
编辑:
问题是你忘了处理一个条件。换句话说,您忘记了 else。 我在下面的代码中进行了更正,但请注意:不要复制和粘贴代码,因为缩进可能会错一个 space。只需要在你的代码中写上带大写注释的三行,就可以了:
else:
if (ballX > padX - 2 and ballX < padX + pWith ) or \
(ballX + ballR > padX -2 and ballX + ballR < padX + pWith):
if (ballY > padY and ballY < padY + pHgt) or \
(ballY + ballR > padY and ballY + ballR < padY + pHgt):
if countSpKy == 0:
pY = ballY - padY
score += 5
hits += 1
if hits == maxHits:
showCongrats()
return score
#else:
# pY = 0
countSpKy += 1
print("pY = ", pY)
print("padY =",padY)
print("ballY = ",ballY)
ballX = padX -5
ballY = padY + pY
else: # THE CONDITION WERE THE Y WERE NOT TEH SAME AS THE PADDLE WAS NOT HANDLED
ballX += ballX_new # THEREFORE IT JUST CHECKED
ballY += ballY_new # THE X COORDINATE
else:
ballX += ballX_new
ballY += ballY_new
padY += padY_new