Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Pygame制作的游戏菜单_Python_User Interface_Menu_Pygame_Livewires - Fatal编程技术网

Python Pygame制作的游戏菜单

Python Pygame制作的游戏菜单,python,user-interface,menu,pygame,livewires,Python,User Interface,Menu,Pygame,Livewires,我不知道我将如何在我制作的游戏中实现游戏菜单,我正在考虑使用指示按钮和“玩游戏”按钮。有人能帮我弄清楚如何用pygame或livewires制作一个简单的菜单吗?提前感谢:) 这是我的游戏的完整代码: # Asteroid Dodger # Player must avoid asteroids # make the score a global variable rather than tied to the asteroid. import pygame from livewires imp

我不知道我将如何在我制作的游戏中实现游戏菜单,我正在考虑使用指示按钮和“玩游戏”按钮。有人能帮我弄清楚如何用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()
小行星道奇 #玩家必须避开小行星 #将分数设置为全局变量,而不是与小行星关联。 导入pygame 从livewires导入游戏、颜色 输入数学,随机 #得分 games.init(屏幕宽度=640,屏幕高度=480,fps=50) 分数=游戏。文本(值=0,大小=25,颜色=color.green, 顶部=5,右侧=games.screen.width-10) 游戏。屏幕。添加(分数) #生活 生活=游戏。文本(值=3,大小=25,颜色=color.green, 顶部=5,左侧=games.screen.width-620) 游戏。屏幕。添加(生活) #存货 存货=[] #小行星图像 images=[games.load_image(“asteroid_small.bmp”), games.load_图像(“asteroid_med.bmp”), games.load_image(“asteroid_big.bmp”)] 等级船(游戏.精灵): """ 玩家控制的飞船,当它被小行星撞击时会爆炸。 """ image=games.load_image(“player.bmp”) 速度_步长=.05 定义初始化(自): “”“初始化装运对象”“” super(Ship,self)。\uuuu init\uuuuu(image=Ship.image, 底部=游戏。屏幕。高度) def更新(自我): 全球库存 “”“使用A和D键移动船舶”“” 如果按下games.keyboard.(游戏键盘): self.dx-=Ship.VELOCITY_步长*2 如果按下games.keyboard.(游戏键盘): self.dx+=Ship.VELOCITY_步长*2 如果self.left<0: self.left=0 如果self.right>games.screen.width: self.right=games.screen.width self.check_collison() def ship_销毁(自我): 自我毁灭 新的_爆炸=爆炸(x=self.x,y=self.y) games.screen.add(新的_爆炸) def检查(自我): “”“检查船上是否有重叠的精灵。”“” 全球生活 对于self.lapping_精灵中的项目: items.handle_catch() 如果是lives.value games.screen.height: 自我毁灭 分数.值+=10 def手柄被卡住(自身): 如果生存。值>0: 生命值-=1 自我毁灭小行星() 如果是lives.value games.screen.width: self.dx=-self.dx elif random.randrange(自身概率变化)==0: self.dx=-self.dx self.check_drop() self.check_for_lifes() def检查下降(自): “”“减少倒计时或丢弃小行星并重置倒计时。”“” 如果self.time\u til\u drop>0: 自下降时间-=0.7 其他: 小行星大小=随机选择(图片) 新小行星=小行星(x=self.x,图像=小行星大小) 游戏。屏幕。添加(新的小行星) #使小行星在产卵器下方稍微产卵 self.time_til_drop=int(新小行星高度*1.3/小行星速度)+1 def检查生命(自我): droplives=random.randrange(04000) 如果droplives==5: lifetoken=Extralifes(x=self.x) g ames.screen.add(lifetoken) 班级额外生活(游戏.精灵): 全球生活 image=games.load_image('addlifes.png')) 速度=2 声音=游戏。加载声音(“CollectLifes.wav”) 定义初始值(self,x,y=10): “”“初始化小行星对象。”“” 超级(Extralifes,self)。\uuuu初始化(image=Extralifes.image, x=x,y=y, dy=超人生命(速度) def更新(自我): “”“检查下边缘是否已到达屏幕底部。”“” 如果self.bottom>games.screen.height: 自我毁灭 def手柄被卡住(自身): 外星生命。声音。播放() 生命。值+=1 自我毁灭 def main(): “玩游戏。” bg=games.load_图像(“space.jpg”,transparent=False) games.screen.background=bg _spawner=spawner() games.screen.add(_产卵器) pygame.mixer.music.load(“Jumpshot.ogg”) pygame.mixer.music.play() 船 游戏。屏幕。添加(船) games.mouse.is_visible=False games.screen.event_grab=True games.screen.mainloop() #开始比赛 main()
Pygbutton模块提供了一种在Pygame程序中创建按钮的方法。您可以通过“pip安装pygbutton”下载它。github上有演示:

请尝试以下代码:

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

按钮功能 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)
以下是
按钮()
中每个参数的含义:

  • x:按钮的x坐标
  • y:按钮的y坐标
  • w:按钮宽度(以像素为单位)
  • h:按钮高度(以像素为单位)
  • 活动:按钮处于活动状态时的图片(例如,当鼠标悬停在按钮上方时)
  • 非活动:按钮空闲时的图片
  • 操作:按下按钮时要执行的功能
注意:制作一个按钮功能更好,因为制作一个按钮更容易,而且可以节省很多时间


希望这有帮助

在我的头顶上,我会使用一个外循环(game_running=True)来显示菜单。如果玩家选择“开始游戏”,则执行mainloop()查看
#Example function call
button(340, 560, 400, 200, randomBtn, randomBtn_hover, random_func)