1

大家好!我从很多天前就陷入了一个问题,我想你可以在这里帮助我!

我的问题:我正在使用 pygame 库在 python 上制作游戏,现在我正在处理菜单,我尝试使用我制作的脚本,但它不起作用,所以你下载了一个预制脚本,但不是两者都不起作用,这里的问题是如何从说明屏幕或游戏返回菜单,这是菜单中的代码:

# -*- 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(),但在这种情况下,我不能,因为菜单不是函数。

4

1 回答 1

1

要从游戏玩法和菜单中轻松更改,您需要找到一种方法来干净地管理它们。菜单可以有一个类,但维护菜单的部分应该是一个函数,游戏玩法也是如此。这是一个很好的结构供它使用:

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 方面。

于 2013-11-22T23:47:04.887 回答