0

我不知道如何在我制作的游戏中实现游戏菜单,我正在考虑使用用于指示积分的按钮和“玩游戏”按钮。那么有人介意帮助我弄清楚如何在 pygame 或 livewires 中制作一个简单的菜单吗?提前致谢 :)

这是我的游戏的完整代码:

# Asteroid Dodger
# Player must avoid asteroids
# make the score a global variable rather than tied to the asteroid.
import pygame
from livewires import games, color
import math, random

#score
games.init(screen_width = 640, screen_height = 480, fps = 50)

score = games.Text(value = 0, size = 25, color = color.green,
                   top = 5, right = games.screen.width - 10)
games.screen.add(score)

#lives
lives = games.Text(value = 3, size = 25, color = color.green,
                    top  = 5, left = games.screen.width - 620)
games.screen.add(lives)

#inventory
inventory=[]

#Asteroid images
images = [games.load_image("asteroid_small.bmp"),
          games.load_image("asteroid_med.bmp"),
          games.load_image("asteroid_big.bmp")]


class Ship(games.Sprite):
    """
    A Ship controlled by player that explodes when it by Asteroids.
    """
    image = games.load_image("player.bmp")
    VELOCITY_STEP = .05

    def __init__(self):
        """ Initialize Ship object """
        super(Ship, self).__init__(image = Ship.image,
                                  bottom = games.screen.height)




    def update(self):
        global inventory
        """ uses A and D keys to move the ship """

        if games.keyboard.is_pressed(games.K_a):
            self.dx -= Ship.VELOCITY_STEP * 2

        if games.keyboard.is_pressed(games.K_d):
            self.dx += Ship.VELOCITY_STEP * 2

        if self.left < 0:
            self.left = 0

        if self.right > games.screen.width:
            self.right = games.screen.width

        self.check_collison()

    def ship_destroy(self):
        self.destroy()
        new_explosion = Explosion(x = self.x, y = self.y)
        games.screen.add(new_explosion)

    def check_collison(self):
        """ Check for overlapping sprites in the ship. """
        global lives
        for items in self.overlapping_sprites:
            items.handle_caught()
            if lives.value <=0:
                self.ship_destroy()

class Explosion(games.Animation):
    sound = games.load_sound("explosion.wav")
    images = ["explosion1.bmp",
              "explosion2.bmp",
              "explosion3.bmp",
              "explosion4.bmp",
              "explosion5.bmp",
              "explosion6.bmp",
              "explosion7.bmp",
              "explosion8.bmp",
              "explosion9.bmp"]

    def __init__(self, x, y):
        super(Explosion, self).__init__(images = Explosion.images,
                                        x = x, y = y,
                                        repeat_interval = 4, n_repeats = 1,
                                        is_collideable = False)
        Explosion.sound.play()



class Asteroid(games.Sprite):
    global lives
    global score
    global inventory
    """
    A asteroid which falls through space.
    """

    image = games.load_image("asteroid_med.bmp")
    speed = 3

    def __init__(self, x,image, y = 10):
        """ Initialize a asteroid object. """
        super(Asteroid, self).__init__(image = image,
                                    x = x, y = y,
                                    dy = Asteroid.speed)


    def update(self):
        """ Check if bottom edge has reached screen bottom. """
        if self.bottom>games.screen.height:
            self.destroy()
            score.value+=10

    def handle_caught(self):
        if lives.value>0:
            lives.value-=1
            self.destroy_asteroid()

        if lives.value <= 0:
            self.destroy_asteroid()
            self.end_game()


    def destroy_asteroid(self):
        self.destroy()

    def die(self):
        self.destroy()



    def end_game(self):
        """ End the game. """
        end_message = games.Message(value = "Game Over",
                                    size = 90,
                                    color = color.red,
                                    x = games.screen.width/2,
                                    y = games.screen.height/2,
                                    lifetime = 5 * games.screen.fps,
                                    after_death = games.screen.quit)
         games.screen.add(end_message)

class Spawner(games.Sprite):
    global images
    """
    Spawns the asteroids
    """
    image = games.load_image("spawner.bmp")

    def __init__(self, y = 10, speed = 5, odds_change = 50):

        super(Spawner, self).__init__(image = Spawner.image,
                                   x = games.screen.width / 2,
                                   y = y,
                                   dx = speed)

        self.odds_change = odds_change
        self.time_til_drop = 0

    def update(self):
        """ Determine if direction needs to be reversed. """
        if self.left < 0 or self.right > games.screen.width:
            self.dx = -self.dx
        elif random.randrange(self.odds_change) == 0:
           self.dx = -self.dx

        self.check_drop()
        self.check_for_lives()


    def check_drop(self):
        """ Decrease countdown or drop asteroid and reset countdown. """
        if self.time_til_drop > 0:
            self.time_til_drop -= 0.7
        else:
            asteroid_size = random.choice(images)
            new_asteroid = Asteroid(x = self.x,image = asteroid_size)
            games.screen.add(new_asteroid)

            # makes it so the asteroid spawns slightly below the spawner   
            self.time_til_drop = int(new_asteroid.height * 1.3 / Asteroid.speed) + 1

    def check_for_lives(self):
        droplives = random.randrange(0, 4000)
        if droplives == 5:
            lifetoken = Extralives(x = self.x)
        g    ames.screen.add(lifetoken)




class Extralives(games.Sprite):
    global lives

    image = games.load_image('addlives.png')
    speed = 2
    sound = games.load_sound("collectlives.wav")

    def __init__(self,x,y = 10):
        """ Initialize a asteroid object. """
        super(Extralives, self).__init__(image = Extralives.image,
                                    x = x, y = y,
                                    dy = Extralives.speed)
    def update(self):
        """ Check if bottom edge has reached screen bottom. """
        if self.bottom>games.screen.height:
            self.destroy()

    def handle_caught(self):

        Extralives.sound.play()
        lives.value+=1
        self.destroy()





def main():
    """ Play the game. """
    bg = games.load_image("space.jpg", transparent = False)
    games.screen.background = bg

    the_spawner = Spawner()
    games.screen.add(the_spawner)

    pygame.mixer.music.load("Jumpshot.ogg")
    pygame.mixer.music.play()    



    the_ship = Ship()
    games.screen.add(the_ship)

    games.mouse.is_visible = False

    games.screen.event_grab = True
    games.screen.mainloop()

#starts the game
main()
4

2 回答 2

0

Pygbutton 模块提供了一种在 Pygame 程序中创建按钮的方法。您可以通过“pip install pygbutton”下载它。github上有demo:https ://github.com/asweigart/pygbutton

于 2014-11-01T01:10:48.020 回答
0

试试这个代码:

游戏菜单功能

def game_intro():
    intro = True

    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        gameDisplay.fill(white)

        titleText = gameDisplay.blit(title, (170, 200))    # title is an image
        titleText.center = ((display_width / 2), (display_height / 2))

        # button(x, y, w, h, inactive, active, action=None)
        button(100, 350, 195, 80, startBtn, startBtn_hover, game_loop)
        button(300, 350, 195, 80, creditsBtn, creditsBtn_hover, #Your function)

        pygame.display.update()
        clock.tick(15)

您可以在游戏循环上方调用此菜单。

按钮功能

Pygame 没有按钮,但很容易制作!

def button(x, y, w, h, inactive, active, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        gameDisplay.blit(active, (x, y))
        if click[0] == 1 and action is not None:
            action()
    else:
        gameDisplay.blit(inactive, (x, y))

您可以在游戏菜单中调用此函数,如下所示:

#Example function call
button(340, 560, 400, 200, randomBtn, randomBtn_hover, random_func)

以下是每个参数的含义button()

  • x:按钮的x坐标
  • y:按钮的y坐标
  • w:按钮宽度(以像素为单位)
  • h:按钮高度(以像素为单位)
  • active:按钮处于活动状态时的图片(例如,当鼠标悬停时)
  • inactive:按钮空闲时的图片
  • action:按下按钮时要执行的函数

注意:最好做一个按钮功能,因为它更容易制作,并且可以节省很多时间

希望这有帮助!

于 2020-07-26T14:31:41.243 回答