我如何防止球粘在一个不存在的物体上

时间:2015-11-22 05:08:17

标签: python keydown

我在学校学习我的第一个编程课程,Python。我在Windows 7,python 3.4.3上。我的项目是基于Pong的游戏。桨是一个矩形,Ball是一个圆圈。我让球在球拍周围反弹。我的游戏包含在保持空格键时球可以保持球拍的能力,你可以移动球和球。使用向上向下箭头键划桨。这有效!但是,如果我按住空格键并且球不在球拍附近,则球会在球拍的X位置固定到位,就好像它会粘在不在那里的球拍上一样。我试着在代码中添加print语句而没有任何帮助。我在网上搜索,但没有什么能接近我的问题。我的导师很难过,并建议你们快速,优质的服务。希望他是对的!!如果你能指出任何其他错误,那将非常感谢。这是我的代码:

# 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()

0 个答案:

没有答案