如何从gam返回主菜单

2024-09-27 22:34:11 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好!我从很久以前就被困在一个问题上了,我想在这里你可以帮助我!在

我的问题是:我正在用pygame库在python上制作一个游戏,现在我正在制作菜单,我试着用我自己制作的一个脚本,但是它不起作用,所以我下载了一个预先制作的脚本,但也不起作用,这里的问题是如何从指令屏幕或游戏返回菜单,这是de menu中的代码:

# -*- coding: utf-8 -*-
#
# autor: Hugo Ruscitti
# web: www.losersjuegos.com.ar
# licencia: GPL 2

import random
import pygame
from pygame.locals import *


class Opcion:

    def __init__(self, fuente, titulo, x, y, paridad, funcion_asignada):
        self.imagen_normal = fuente.render(titulo, 1, (0, 0, 0))
        self.imagen_destacada = fuente.render(titulo, 1, (200, 0, 0))
        self.image = self.imagen_normal
        self.rect = self.image.get_rect()
        self.rect.x = 500 * paridad
        self.rect.y = y
        self.funcion_asignada = funcion_asignada
        self.x = float(self.rect.x)

    def actualizar(self):
        destino_x = 780
        self.x += (destino_x - self.x) / 5.0
        self.rect.x = int(self.x)

    def imprimir(self, screen):
        screen.blit(self.image, self.rect)

    def destacar(self, estado):
        if estado:
            self.image = self.imagen_destacada
        else:
            self.image = self.imagen_normal

    def activar(self):
        self.funcion_asignada()


class Cursor:

    def __init__(self, x, y, dy):
        self.image = pygame.image.load('cursor.png').convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.y_inicial = y
        self.dy = dy
        self.y = 0
        self.seleccionar(0)

    def actualizar(self):
        self.y += (self.to_y - self.y) / 10.0
        self.rect.y = int(self.y)

    def seleccionar(self, indice):
        self.to_y = self.y_inicial + indice * self.dy

    def imprimir(self, screen):
        screen.blit(self.image, self.rect)


class Menu:
    "Representa un menú con opciones para un juego"

    def __init__(self, opciones):
        self.opciones = []
        fuente = pygame.font.Font('dejavu.ttf', 40)
        x = 780
        y = 250
        paridad = 1

        self.cursor = Cursor(x - 95, y, 95)

        for titulo, funcion in opciones:
            self.opciones.append(Opcion(fuente, titulo, x, y, paridad, funcion))
            y += 30
            if paridad == 1:
                paridad = -1
            else:
                paridad = 1

        self.seleccionado = 0
        self.total = len(self.opciones)
        self.mantiene_pulsado = False

    def actualizar(self):
        """Altera el valor de 'self.seleccionado' con los direccionales."""

        k = pygame.key.get_pressed()

        if not self.mantiene_pulsado:
            if k[K_UP]:
                self.seleccionado -= 1
            elif k[K_DOWN]:
                self.seleccionado += 1
            elif k[K_RETURN]:
                # Invoca a la función asociada a la opción.
                self.opciones[self.seleccionado].activar()

        # procura que el cursor esté entre las opciones permitidas
        if self.seleccionado < 0:
            self.seleccionado = 0
        elif self.seleccionado > self.total - 1:
            self.seleccionado = self.total - 1

        self.cursor.seleccionar(self.seleccionado)

        # indica si el usuario mantiene pulsada alguna tecla.
        self.mantiene_pulsado = k[K_UP] or k[K_DOWN] or k[K_RETURN]

        self.cursor.actualizar()

        for o in self.opciones:
            o.actualizar()

    def imprimir(self, screen):
        """Imprime sobre 'screen' el texto de cada opción del menú."""

        self.cursor.imprimir(screen)

        for opcion in self.opciones:
            opcion.imprimir(screen)

def comenzar_nuevo_juego():
    print " Función que muestra un nuevo juego."

def mostrar_opciones():
    print " Función que muestra otro menú de opciones."

def creditos():
    print " Función que muestra los creditos del programa."

def salir_del_programa():
    import sys
    print " Gracias por utilizar este programa."
    sys.exit(0)


if __name__ == '__main__':

    salir = False
    opciones = [
        ("", comenzar_nuevo_juego),
        ("", mostrar_opciones),
        ("", creditos),
        ("", salir_del_programa)
        ]

    pygame.font.init()
    screen = pygame.display.set_mode((1200, 900))
    fondo = pygame.image.load("fondo.jpg").convert()
    menu = Menu(opciones)

    while not salir:

        for e in pygame.event.get():
            if e.type == QUIT:
                salir = True

        screen.blit(fondo, (0, 0))
        menu.actualizar()
        menu.imprimir(screen)

        pygame.display.flip()
        pygame.time.delay(10)

我在等你的回答!在

还有一个细节:在我的代码中,我把菜单设置为:def menu():然后你回到我刚才调用的菜单menu(),但在本例中,我不能这样做,因为菜单不是一个函数。在


Tags: rectimageselfifdefscreenpygamecursor
1条回答
网友
1楼 · 发布于 2024-09-27 22:34:11

为了方便地从游戏和菜单中进行更改,您需要制定一种方法来管理这两者。菜单可以有一个类,但是维护菜单的部分应该是一个函数,对于游戏来说也是一样的。这里有一个很好的结构供其使用:

is_menu = False

def menu():
    pass
    #right here you want the necessary code to maintain the main menu. be sure not to put the code that starts up the menu here, only the code required to run over and over again to keep the menu running

def change_to_menu():
    is_menu = True
    #right here you want the things to do to create a menu, as well as the above line of code that will be used to mark the fact that the menu is to be maintained, not gameplay

def gameplay():
    pass
    #here is where you put code to maintain gameplay. remember this will be called over and over again, multiple times a second

def change_to_gameplay():
    is_menu = False
    #insert the code to resume or initialize gameplay here, along with the above line. you may want to make different functions to initialize and resume gameplay, though it is not nescessary

while not salir:          #this is your mainloop
    if is_menu:
        menu()
    else:
        gameplay()

上面的代码有一个主循环,进入主循环的代码保持菜单运行,进入主循环的代码保持游戏的运行,以及从菜单切换到游戏的方法,这些方法可以在任何地方调用。在

如果你想创建一个新的菜单,你只需初始化一个新的菜单对象并去掉旧的。除非它包含重要的游戏属性,否则应该没问题,如果有,你可以将它们存储为全局变量或另一个对象中,例如,如果这个属性包含一个关于游戏设置的属性,你可以改为将该属性设为全局属性,或者设置另一个对象来管理菜单之外的所有设置,这是为了管理这方面的GUI方面。在

相关问题 更多 >

    热门问题