首页 > 解决方案 > 按键后如何重播(返回 TRUE)游戏(在 Pygame 中),一旦 GAME OVER 或您获胜!显示?

问题描述

所以我在 Pygame 中做一个游戏,叫做The Brick-out Game。所以游戏运行得很好,但是一旦我输掉游戏(或者当显示 GAME OVER 时)或者我赢了游戏。屏幕出现了,但如果我想重玩游戏,我需要关闭程序并再次调试我的代码才能玩它。所以我想在我的程序右下角输入一条消息,上面写着“Press a key to play.”,一旦游戏结束或你赢了!显示,但尽管添加了一个函数,用于在按下键后将值返回True ;什么都没发生。这是我添加到检查按键的功能:

def checkForKeyPress():
    if len(pygame.event.get(QUIT))>0:
        terminate()
        
    keyUpEvents = pygame.event.get(KEYUP)
    if len(keyUpEvents) == 0:
        return None
    if keyUpEvents[0].key == K_ESCAPE:
        terminate()
    return keyUpEvents[0].key
    
if checkForKeyPress():
    pygame.event.get()
    True

这是整个源代码:

import pygame, sys
from pygame.locals import *


 
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BRICKRED=(203, 65, 84)
BGBLUE = (96, 160, 226)
DARKGRAY = (40, 40, 40)


pygame.init()

BASICFONT = pygame.font.SysFont('freesansbold.ttf', 18)
# Set the width and height of the screen [width, height]
WINDOWWIDTH = 700
WINDOWHEIGHT = 500
size = ((WINDOWWIDTH, WINDOWHEIGHT))
screen = pygame.display.set_mode(size)

print("Drag the paddle to-and-fro(By your mouse) to support the ball and prevent it from falling down. Thank You! Nishita Thakur.")

"""
    This is a simple Ball class for respresenting a ball 
    in the game. 
"""
class Ball(object):
    def __init__ (self, screen, radius,x,y):
        self.__screen = screen
        self._radius = radius
        self._xLoc = x
        self._yLoc = y
        self.__xVel = 5
        self.__yVel = -3
        w, h = pygame.display.get_surface().get_size()
        self.__width = w
        self.__height = h
    def draw(self):
        """
            draws the ball onto screen.
        """
        pygame.draw.circle(screen,(255, 0, 0) , (self._xLoc,self._yLoc), self._radius)
    def update(self, paddle, brickwall):
        """
            moves the ball at the screen.
            contains some collision detection.
        """
        self._xLoc += self.__xVel
        self._yLoc += self.__yVel
        if self._xLoc == self._radius:
            self.__xVel *= -1
        elif self._xLoc >= self.__width - self._radius:
            self.__xVel *= -1
        if self._yLoc == self._radius:
            self.__yVel *= -1
        elif self._yLoc >= self.__height - self._radius:
            return True

        # for bouncing off the bricks.
        if brickwall.collide(self):
            self.__yVel *= -1

        # collision deection between ball and paddle
        paddleX = paddle._xLoc
        paddleY = paddle._yLoc
        paddleW = paddle._width
        paddleH = paddle._height
        ballX = self._xLoc
        ballY = self._yLoc

        if ((ballX + self._radius) >= paddleX and ballX <= (paddleX + paddleW)) \
        and ((ballY + self._radius) >= paddleY and ballY <= (paddleY + paddleH)):
            self.__yVel *= -1

        return False

        
"""
    Simple class for representing a paddle
"""        
class Paddle (object):
    def __init__ (self, screen, width, height,x,y):
        self.__screen = screen
        self._width = width
        self._height = height
        self._xLoc = x
        self._yLoc = y
        w, h = pygame.display.get_surface().get_size()
        self.__W = w
        self.__H = h
    def draw(self):
        """
            draws the paddle onto screen.
        """
        pygame.draw.rect(screen, (0,0,0), (self._xLoc,self._yLoc,self._width,self._height),0)
    def update(self):
        """
            moves the paddle at the screen via mouse
        """
        x,y = pygame.mouse.get_pos()
        if x >= 0 and x <= (self.__W - self._width):
            self._xLoc = x
 
"""
    This class represents a simple Brick class.
    For representing bricks onto screen.
"""
class Brick (pygame.sprite.Sprite):
    def __init__(self, screen, width, height, x,y):
        self.__screen = screen
        self._width = width
        self._height = height
        self._xLoc = x
        self._yLoc = y
        w, h = pygame.display.get_surface().get_size()
        self.__W = w
        self.__H = h
        self.__isInGroup = False
    def draw(self):
        """
            draws the brick onto screen.
            color: rgb(203, 65, 84)
        """
        pygame.draw.rect(screen, (BRICKRED), (self._xLoc,self._yLoc,self._width,self._height),0)
    def add (self, group):
        """
            adds this brick to a given group.
        """
        group.add(self)
        self.__isInGroup = True
    def remove(self, group):
        """
            removes this brick from the given group.
        """
        group.remove(self)
        self.__isInGroup = False
    def alive(self):
        """
            returns true when this brick is belong to the brick wall.
            otherwise false
        """
        return self.__isInGroup

    def collide(self, ball):
        """
            collision deection between ball and this brick
        """
        brickX = self._xLoc
        brickY = self._yLoc
        brickW = self._width
        brickH = self._height
        ballX = ball._xLoc
        ballY = ball._yLoc
        radius = ball._radius

        if ((ballX + radius) >= brickX and ballX <= (brickX + brickW)) \
        and ((ballY + radius) >= brickY and ballY <= (brickY + brickH)):
            return True

        return False


"""
    This is a simple class for representing a 
    brick wall.
"""
class BrickWall (pygame.sprite.Group):
    def __init__ (self,screen, x, y, width, height):
        self.__screen = screen
        self._x = x
        self._y = y
        self._width = width
        self._height = height
        self._bricks = []

        X = x
        Y = y
        for i in range(3):
            for j in range(4):
                self._bricks.append(Brick(screen,width,height,X,Y))
                X += width + (width/ 7.0)
            Y += height + (height / 7.0)
            X = x
        
    def add(self,brick):
        """
            adds a brick to this BrickWall (group)
        """
        self._bricks.append(brick)
    def remove(self,brick):
        """
            removes a brick from this BrickWall (group)
        """
        self._bricks.remove(brick)
    def draw(self):
        """
            draws all bricks onto screen.
        """
        for brick in self._bricks:
            if brick != None:
                brick.draw()
    def update(self, ball):
        """
            checks collision between ball and bricks.
        """
        for i in range(len(self._bricks)):
            if ((self._bricks[i] != None) and self._bricks[i].collide(ball)):
                self._bricks[i] = None
        
        # removes the None-elements from the brick list.
        for brick in self._bricks:
            if brick == None:
                self._bricks.remove(brick)
    def hasWin(self):
        """
            Has player win the game?
        """
        return len(self._bricks) == 0
    def collide (self, ball):
        """
            check collisions between the ball and 
            any of the bricks.
        """
        for brick in self._bricks:
            if brick.collide(ball):
                return True
        return False
    
def drawPressKeyMsg():
    pressKeySurf = BASICFONT.render('Press a key to play.', True, DARKGRAY)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT - 30)
    screen.blit(pressKeySurf, pressKeyRect)
    checkForKeyPress()
    
def checkForKeyPress():
    if len(pygame.event.get(QUIT))>0:
        terminate()
        
    keyUpEvents = pygame.event.get(KEYUP)
    if len(keyUpEvents) == 0:
        return None
    if keyUpEvents[0].key == K_ESCAPE:
        terminate()
    return keyUpEvents[0].key
    
if checkForKeyPress():
    pygame.event.get()
    True
    


# The game objects ball, paddle and brick wall
ball = Ball(screen,25,350,250)
paddle = Paddle(screen,100,20,250,450)
brickWall = BrickWall(screen,25,25,150,50)

isGameOver = False # determines whether game is lose
gameStatus = True # game is still running

score = 0 # score for the game.
 
pygame.display.set_caption("The Brickout Game")


 
# Loop until the user clicks the close button.
done = False
 
# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# for displaying text in the game 
pygame.font.init() # you have to call this at the start, 
                   # if you want to use this module.

# message for game over
mgGameOver = pygame.font.SysFont('Comic Sans MS', 60)

# message for winning the game.
mgWin = pygame.font.SysFont('Comic Sans MS', 60)

# message for score
mgScore = pygame.font.SysFont('Comic Sans MS', 60)

textsurfaceGameOver = mgGameOver.render('   Game Over!  ', False, (255,255,255))
textsurfaceWin = mgWin.render("   You win!",False,(255,255,255))
textsurfaceScore = mgScore.render("Score: "+str(score),False,(255,255,255))
         
 
# -------- Main Program Loop -----------
#showStartScreen()
while not done:
    # --- Main event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
 
    # --- Game logic should go here
 
    # --- Screen-clearing code goes here
 
    # Here, we clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.
 
    # If you want a background image, replace this clear with blit'ing the
    # background image.
    screen.fill(BGBLUE)
 
    # --- Drawing code should go here
    
    """
        Because I use OOP in the game logic and the drawing code,
        are both in the same section.
    """
    if gameStatus:

        # first draws ball for appropriate displaying the score. 
        brickWall.draw()

         # for counting and displaying the score
        if brickWall.collide(ball):
            score += 10
        textsurfaceScore = mgScore.render("Score: "+str(score),False,(255,255,255))
        screen.blit(textsurfaceScore,(300,0))

        # after scoring. because hit bricks are removed in the update-method
        brickWall.update(ball)

        paddle.draw()
        paddle.update()

        if ball.update(paddle, brickWall):
            isGameOver = True
            gameStatus = False
        
        if brickWall.hasWin():
            gameStatus = False

        ball.draw()

    else: # game isn't running.
        if isGameOver: # player lose
            screen.blit(textsurfaceGameOver,(0,180))
            textsurfaceScore = mgScore.render("     Score: "+str(score),False,(255,255,255))
            screen.blit(textsurfaceScore,(300,180))
            drawPressKeyMsg()
            #checkForKeyPress()
            if checkForKeyPress():
                pygame.event.get()
                True
        elif brickWall.hasWin(): # player win
            screen.blit(textsurfaceWin,(0,180))
            textsurfaceScore = mgScore.render("     Score: "+str(score),False,(255,255,255))
            screen.blit(textsurfaceScore,(300,180))
            drawPressKeyMsg()
            #checkForKeyPress()
            if checkForKeyPress():
                pygame.event.get()
                True
                
    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()
 
    # --- Limit to 60 frames per second
    FPS = clock.tick(60)
 
# Close the window and quit.
pygame.quit()

请告诉我如何重新玩游戏一旦我按下一个键一次游戏结束或你赢了!被展示。努力将不胜感激。提前致谢 :)

标签: pythonpygamekey

解决方案


两次更改将获得您想要的结果。

  • 更新checkForKeyPress函数以返回 True 或 False:

    def checkForKeyPress():
        keys = pygame.key.get_pressed()
        if not any(keys): return False
        if keys[pygame.K_ESCAPE]:
            exit()
        return True
    
  • 更新主循环中的密钥检查以重置游戏:

     else: # game isn't running.
         if isGameOver: # player lose
             screen.blit(textsurfaceGameOver,(0,180))
         elif brickWall.hasWin(): # player win
             screen.blit(textsurfaceWin,(0,180))
         textsurfaceScore = mgScore.render("     Score: "+str(score),False,(255,255,255))
         screen.blit(textsurfaceScore,(300,180))
         drawPressKeyMsg()
         #checkForKeyPress()
         if checkForKeyPress():
               # The game objects ball, paddle and brick wall
               ball = Ball(screen,25,350,250)
               paddle = Paddle(screen,100,20,250,450)
               brickWall = BrickWall(screen,25,25,150,50)
    
               isGameOver = False # determines whether game is lose
               gameStatus = True # game is still running
    
               score = 0 # score for the game.
    

推荐阅读