微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从按钮调用函数时如何让我的游戏循环?

如何解决从按钮调用函数时如何让我的游戏循环?

我正在尝试修复我的游戏。当游戏结束时,它会调用 crash() 函数。它为用户提供了再次播放或退出的选项。在 crash() 函数内的“再次播放”按钮中调用我的 game_loop 函数时,游戏不会重新启动。有什么建议么?提前致谢......................................

import math
import random
import time
import pygame
from pygame import mixer

# Intialize the pygame
pygame.init()

# next setup the display
display_width = 800
display_height = 600
screen = pygame.display.set_mode((800,600))

# Background
background = pygame.image.load('waterbackground.jpg')

# game clock to time frames per second 
clock = pygame.time.Clock()

# Sound
mixer.music.load("ocean.wav")
mixer.music.play(-1)

# setup colors needed in the game
black = (0,0)
white = (255,255,255)
red = (200,0)
bright_red = (255,0)
block_color = (53,115,255)
green = (0,200,0)
bright_green = (0,0)

# Caption and Icon
pygame.display.set_caption("Pirate War")
icon = pygame.image.load('pirateship.png')
pygame.display.set_icon(icon)

# cannon
cannonImg = pygame.image.load('cannonball.png')
cannonX = 0
cannonY = 480
cannonX_change = 0
cannonY_change = 10
cannon_state = "ready"
    

# Player
playerImg = pygame.image.load('cannon.png')
playerX = 370
playerY = 480
playerX_change = 0

# score
score_value = 0

# add explosion sound
crash_sound = pygame.mixer.sound("explosion.wav")

# ship
shipImg = []
shipX = []
shipY = []
shipX_change = []
shipY_change = []
num_of_ships = 6

for i in range(num_of_ships):
    shipImg.append(pygame.image.load('pirateship.png'))
    shipX.append(random.randint(0,736))
    shipY.append(random.randint(50,150))
    shipX_change.append(4)
    shipY_change.append(40)


font = pygame.font.Font('freesansbold.ttf',32)

textx = 10
testY = 10

# Game Over
over_font = pygame.font.Font('freesansbold.ttf',64)
credits_font = pygame.font.Font('freesansbold.ttf',24)

# text object function called by message display function
def text_objects(text,font):
    textSurface = font.render(text,True,white)
    return textSurface,textSurface.get_rect()


def show_score(x,y):
    score = font.render("score : " + str(score_value),(255,255))
    screen.blit(score,(x,y))


def game_over_text():
    over_text = over_font.render("GAME OVER!",255))
    screen.blit(over_text,(200,250))
    screen.fill((0,0))
    # Background Image
    screen.blit(background,(0,0))
    crash()

def game_credits_text(text):
    over_text = over_font.render(text,150))
    
    
def game_credits_text_small(text):
    credits_text = credits_font.render(text,255))
    screen.blit(credits_text,(20,350))   
    
def game_intro_text_small(text):
    credits_text = credits_font.render(text,(125,375))     

def player(x,y):
    screen.blit(playerImg,y))


def ship(x,y,i):
    screen.blit(shipImg[i],y))


def fire_cannon(x,y):
    global cannon_state
    cannon_state = "fire"
    screen.blit(cannonImg,(x + 16,y + 10))


def isCollision(shipX,shipY,cannonX,cannonY):
    distance = math.sqrt(math.pow(shipX - cannonX,2) + (math.pow(shipY - cannonY,2)))
    if distance < 27:
        return True
    else:
        return False

# function to setup message display
def message_display(text):
    largeText = pygame.font.Font('freesansbold.ttf',70)
    TextSurf,TextRect = text_objects(text,largeText)
    TextRect.center = ((display_width/2),(display_height/2))
    screen.blit(TextSurf,TextRect)
    pygame.display.update()
    time.sleep(2)
    
    

def crash():
    #add crash sound
    pygame.mixer.music.stop()
    pygame.mixer.sound.play(crash_sound)
    game_credits_text("Game Over!")
    game_credits_text_small("Created by: Dominique Kellam,Hayley Cull and Dewayne Bowen")
    while True:
        # check for quit
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
                screen.fill((0,0))
        #add buttons to start screen
        button("Play Again",150,450,100,50,green,bright_green,game_loop)
        button("Quit",550,red,bright_red,quitgame)
        
        pygame.display.update()
        clock.tick(15)


def button(msg,x,w,h,ic,ac,action=None): 
    mouse = pygame.mouse.get_pos() # returns a list of [x,y]
    click = pygame.mouse.get_pressed()
    
    if x+w > mouse[0] > x and y+h > mouse[1] > y: #check is mouse over button
        # redraw the rectange with active color when mouSEOver
        pygame.draw.rect(screen,h))
        #check for a click
        if click[0] == 1 and action!=None:
            action()
    else:
        pygame.draw.rect(screen,h))
    # Now display text on top of button that was just redrawn
    smallText = pygame.font.Font('freesansbold.ttf',20)
    TextSurf,TextRect = text_objects(msg,smallText)
    TextRect.center = ((x+(w/2)),(y+(h/2)))
    screen.blit(TextSurf,TextRect)
    
    
def quitgame():
    pygame.quit()
    quit() 
    
# start screen code
def game_intro():
    intro = True
    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        screen.fill((0,0))
        # Background Image
        screen.blit(background,0))
        largeText = pygame.font.Font('freesansbold.ttf',115)
        TextSurf,TextRect = text_objects("Pirate War",largeText)
        game_intro_text_small("[space bar] - fire cannon,[<] [>] arrows to move")
        TextRect.center = ((display_width/2),(display_height/2))
        screen.blit(TextSurf,TextRect)
        #add buttons to start screen
        button("Go!",quitgame)
        
        pygame.display.update()
        clock.tick(15)
    
def game_loop():
    global playerX
    global playerX_change
    global cannonX
    global cannonY
    global cannon_state
    global score_value
    # Game Loop
    running = True
    while running:
    
        # RGB = Red,Green,Blue
        screen.fill((0,0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    
            # if keystroke is pressed check whether its right or left
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    playerX_change = -5
                if event.key == pygame.K_RIGHT:
                    playerX_change = 5
                if event.key == pygame.K_SPACE:
                    if cannon_state == "ready":
                        cannonSound = mixer.sound("cannon_x.wav")
                        cannonSound.play()
                        # Get the current x cordinate of the spaceship
                        cannonX = playerX
                        fire_cannon(cannonX,cannonY)
    
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    playerX_change = 0
    
        # 5 = 5 + -0.1 -> 5 = 5 - 0.1
        # 5 = 5 + 0.1
    
        playerX += playerX_change
        if playerX <= 0:
            playerX = 0
        elif playerX >= 736:
            playerX = 736
    
        # ship Movement
        for i in range(num_of_ships):
    
            # Game Over
            if shipY[i] > 440:
                for j in range(num_of_ships):
                    shipY[j] = 2000
                game_over_text()
                break
            
    
            shipX[i] += shipX_change[i]
            if shipX[i] <= 0:
                shipX_change[i] = 1               #######SHIP MOVEMENT
                shipY[i] += shipY_change[i]
            elif shipX[i] >= 736:
                shipX_change[i] = -1              ######SHIP MOVEMENT
                shipY[i] += shipY_change[i]
    
            # Collision
            collision = isCollision(shipX[i],shipY[i],cannonY)
            if collision:
                explosionSound = mixer.sound("explosion.wav")
                explosionSound.play()
                cannonY = 480
                cannon_state = "ready"
                score_value += 1
                shipX[i] = random.randint(0,736)
                shipY[i] = random.randint(50,150)
    
            ship(shipX[i],i)
    
        # cannon Movement
        if cannonY <= 0:
            cannonY = 480
            cannon_state = "ready"
    
        if cannon_state == "fire":
            fire_cannon(cannonX,cannonY)
            cannonY -= cannonY_change
    
        player(playerX,playerY)
        show_score(textx,testY)
        pygame.display.update()

game_intro()

解决方法

您将船舶 y 设置为 2000,即 > 400,因此它会再次崩溃。将此更改为零,它会起作用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。