为python游戏添加再次播放选项 [英] Adding a play again option to python game

查看:41
本文介绍了为python游戏添加再次播放选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python 为我的编程课制作游戏.我不知道如何在玩家输球或退出游戏时再次给他们选择权.我正在使用 python 2.7.这是我的游戏代码:

I'm working on making a game for my programming class using python. I don't know how to give the option to the player again when they lose, or quit the game. I am using python 2.7. This is the code for my game:

import pygame, sys, time, random
from pygame.locals import *


# set up pygame
pygame.init()
mainClock = pygame.time.Clock()

# set up the window
WINDOWWIDTH = 1000
WINDOWHEIGHT = 500
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Dankest Memes')

# set up the colors
PINK = (223, 61, 163)
TEXTCOLOR = (223, 61, 163)



def waitForPlayerToPressKey():
 while True:
     for event in pygame.event.get():
         if event.type == QUIT:
             terminate()
         if event.type == KEYDOWN:
             if event.key == K_ESCAPE: # pressing escape quits
                 terminate()
             return

def terminate():
 while True:
    for event in pygame.event.get():
        if event.type == QUIT:
             terminate()
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE: # pressing escape quits
                 terminate()
            return

def drawText(text, font, surface, x, y):
    textobj = font.render(text, 1, TEXTCOLOR)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)
font = pygame.font.SysFont(None, 48)
TEXTCOLOR = (255,250,250)

Score=4

 # set up fonts
font = pygame.font.SysFont(None, 48)
myscore=4

# set up the block data structure
file = 'score.txt'
player = pygame.Rect(300, 100, 40, 40)
playerImage = pygame.image.load('player.png')
playerStretchedImage = pygame.transform.scale(playerImage, (40, 40))
foodImage = pygame.image.load('meme.png')
foods = []
for i in range(20):
    foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))

foodCounter = 0
NEWFOOD = 40

baddie = pygame.Rect(300, 100, 40, 40)
baddieImage = pygame.image.load('baddie.png')
baddieStretchedImage = pygame.transform.scale(baddieImage, (40, 40))
baddies = []
for i in range(20):
    baddies.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))

baddieCounter = 0
NEWBADDIE = 120

# set up keyboard variables
moveLeft = False
moveRight = False
moveUp = False
moveDown = False

MOVESPEED = 6

# set up music
pickUpSound = pygame.mixer.Sound('pickup.wav')
pygame.mixer.music.load('background.mp3')
pygame.mixer.music.play(-1, 0.0)
musicPlaying = True

# show the "Start" screen
drawText('Dankest Memes', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press any key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 50)
drawText('Move with WASD or the arrow keys.', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 100)
drawText('Collect green Pepes to get points.', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 150)
drawText('Avoid the chickens.', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 200)
pygame.display.update()
waitForPlayerToPressKey()


# run the game loop
while True:
    # check for the QUIT event
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            # change the keyboard variables
            if event.key == K_LEFT or event.key == ord('a'):
                moveRight = False
                moveLeft = True
            if event.key == K_RIGHT or event.key == ord('d'):
                moveLeft = False
                moveRight = True
            if event.key == K_UP or event.key == ord('w'):
                moveDown = False
                moveUp = True
            if event.key == K_DOWN or event.key == ord('s'):
                moveUp = False
                moveDown = True
        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            if event.key == K_LEFT or event.key == ord('a'):
                moveLeft = False
            if event.key == K_RIGHT or event.key == ord('d'):
                moveRight = False
            if event.key == K_UP or event.key == ord('w'):
                moveUp = False
            if event.key == K_DOWN or event.key == ord('s'):
                moveDown = False
            if event.key == ord('x'):
                player.top = random.randint(0, WINDOWHEIGHT - player.height)
                player.left = random.randint(0, WINDOWWIDTH - player.width)
            if event.key == ord('m'):
                if musicPlaying:
                    pygame.mixer.music.stop()
                else:
                    pygame.mixer.music.play(-1, 0.0)
                musicPlaying = not musicPlaying

        if event.type == MOUSEBUTTONUP:
            foods.append(pygame.Rect(event.pos[0] - 10, event.pos[1] - 10, 20, 20))

    foodCounter += 1
    if foodCounter >= NEWFOOD:
        # add new food
        foodCounter = 0
        foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))

    baddieCounter += 1
    if baddieCounter >= NEWBADDIE:
        baddieCounter = 0
        baddies.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))

    # draw the pink background onto the surface
    windowSurface.fill(PINK)

    # move the player
    if moveDown and player.bottom < WINDOWHEIGHT:
        player.top += MOVESPEED
    if moveUp and player.top > 0:
        player.top -= MOVESPEED
    if moveLeft and player.left > 0:
        player.left -= MOVESPEED
    if moveRight and player.right < WINDOWWIDTH:
        player.right += MOVESPEED
    drawText('Score: %s' % (Score), font, windowSurface, 10,0)

    # draw the block onto the surface
    windowSurface.blit(playerStretchedImage, player)

    # check if the block has intersected with any food squares.
    for food in foods[:]:
        if player.colliderect(food):
            foods.remove(food)
            Score+=2
            if musicPlaying:
                pickUpSound.play()

    for baddie in baddies[:]:
        if player.colliderect(baddie):
            baddies.remove(baddie)
            Score-=4
            if musicPlaying:
                pickUpSound.play()

    if Score < 0:
        drawText('You have lost', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
        drawText('Press escape to quit the game', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 50)
        drawText('Press any other key to play again', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 100)
        pygame.display.update()
        waitForPlayerToPressKey()




    # draw the food
    for food in foods:
        windowSurface.blit(foodImage, food)

    # draw the baddie
    for baddie in baddies:
        windowSurface.blit(baddieImage, baddie)

    # draw the window onto the screen
    pygame.display.update()
    mainClock.tick(40)



if event.key == pygame.K_ESCAPE:
    pygame.quit()
    sys.exit()

游戏很简单.玩家四处走动,收集食物以获得积分并避免坏人,因此他们不会失去积分.当分数低于 0 时,玩家输了.我设法获得并结束游戏画面,但在此之后我无法再次播放或退出游戏.

The game is simple. The player moves around, collects food to get points and avoids baddies so they don't lose points. When the score drops below 0, the player loses. I managed to get and end game screen, but I can't make it play again or quit the game after this point.

推荐答案

第一个建议.如果您向他们展示您的尝试,人们将更有可能帮助您.

First of, one suggestion. People will be more likely to help you if you show them what you've tried.

无论如何.

我要做的是将整个游戏循环包装在一个函数中.像这样:

What I would do is wrap your entire game loop in a function. Like so:

def game_loop():
    while True:
    # check for the QUIT event
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
            ....

接下来,当你的游戏结束时(我假设它确实有一个条件让它结束),调用一个屏幕上的游戏功能.在您的游戏过屏功能中,您可以先用一种颜色填充窗口,然后将任何文本 blit 到您想要向用户显示的屏幕上,例如按任意键再次播放".然后你会检查是否有任何键被按下,如果是,则调用游戏循环函数.您还需要检查用户是否试图关闭窗口.

next when ever your game ends(I'm assuming it does have a condition that makes it end), call a game over screen function. In your game over screen function, you could first fill the window with a color, then blit any text to the screen you wan to show the user, such as "Press any key to play again". Then you would check if any key was pressed and if so call the game loop function. You also need to check if the user is trying to close the window.

然后像这样调用游戏过屏功能:

Then call the game over screen function like so:

#pseudo code
if game_has_ended == True:
   game_over_screen()

这篇关于为python游戏添加再次播放选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆