【问题标题】:I am new, I have a question about PyGame, OOP and Python in general [duplicate]我是新手,我一般对 PyGame、OOP 和 Python 有疑问 [重复]
【发布时间】:2020-05-01 09:29:12
【问题描述】:

我是编程新手,尤其是 PyGame 和 OOP。我不知道如何让按钮在 PyGame 中执行特定命令。我尝试为按钮创建一个类,如果您查看此代码,我可以执行悬停方法/功能作为示例,但是当我按下退出按钮时,我很难让游戏关闭。我似乎无法理解如何传递一个参数,使 main_menu 在执行 exit 时为 false,而 main_game 在执行 play 时为 true。

from ColorsAndCoordinates import *

pygame.init()

screen = pygame.display.set_mode((1000, 700))
font = pygame.font.Font("freesansbold.ttf", 42)


class Button:
    main_menu = True

    def __init__(self, color, x, y, width, height, text):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def display(self, color):
        self.color = color
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
        text = font.render(self.text, True, red)
        screen.blit(text, (self.x, self.y))

    def hover(self, color):
        mouse = pygame.mouse.get_pos()
        if self.x + self.width > mouse[0] > self.x and self.y + self.height > mouse[1] > self.y:
            Button.display(self, color)

    def clicked(self):
        mouse = pygame.mouse.get_pos()
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if self.x + self.width > mouse[0] > self.x and self.y + self.height > mouse[1] > self.y:
                pass


play_button = Button(blue, 200, 300, 95, 46, "Play")
exit_button = Button(blue, 700, 300, 95, 46, "Exit")
tutorial_button = Button(blue, 410, 550, 165, 46, "Tutorial")

main_menu = True
main_game = False
while main_menu:

    screen.fill(black)
    play_button.display(blue)
    exit_button.display(blue)
    tutorial_button.display(blue)
    play_button.hover(black)
    exit_button.hover(black)
    tutorial_button.hover(black)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            main_menu = False

    exit_button.clicked()

    pygame.display.update()

【问题讨论】:

  • Button.display(...:应该是self.display(floor)

标签: python oop pygame


【解决方案1】:

对此有不同的解决方案,例如多态性、动作或事件。
一个明显而简单的解决方案是在方法clicked 中添加一个action 参数。参数是一个动作函数,在点击按钮时调用:

class Button:
    # [...]

    def clicked(self, action = None):
        mouse = pygame.mouse.get_pos()
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if self.x + self.width > mouse[0] > self.x and self.y + self.height > mouse[1] > self.y:

                if action:
                    action()

创建一个改变状态的函数。考虑将global statement 用于全局命名空间main_menumain_game 中的变量:

def action_exit():
    global main_menu, main_game 
    main_menu = False
    main_game = True

将操作传递给exit_button.clicked:

while main_menu:
    # [...]

    exit_button.clicked(action_exit)

进一步在方法display()中将Button.display(self, color)更改为self.display(color)

完整示例:

import pygame
from pygame.locals import *

pygame.init()

screen = pygame.display.set_mode((1000, 700))
font = pygame.font.Font("freesansbold.ttf", 42)

red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
black = (0, 0, 0)

class Button:
    main_menu = True

    def __init__(self, color, x, y, width, height, text):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text

    def display(self, color):
        self.color = color
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
        text = font.render(self.text, True, red)
        screen.blit(text, (self.x, self.y))

    def hover(self, color):
        mouse = pygame.mouse.get_pos()
        if self.x + self.width > mouse[0] > self.x and self.y + self.height > mouse[1] > self.y:
            self.display(color)

    def clicked(self, action = None):
        mouse = pygame.mouse.get_pos()
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if self.x + self.width > mouse[0] > self.x and self.y + self.height > mouse[1] > self.y:

                if action:
                    action()

def action_exit():
    global main_menu, main_game 
    main_menu = False
    main_game = True

play_button = Button(blue, 200, 300, 95, 46, "Play")
exit_button = Button(blue, 700, 300, 95, 46, "Exit")
tutorial_button = Button(blue, 410, 550, 165, 46, "Tutorial")

main_menu = True
main_game = False
while main_menu:

    screen.fill(black)
    play_button.display(blue)
    exit_button.display(blue)
    tutorial_button.display(blue)
    play_button.hover(black)
    exit_button.hover(black)
    tutorial_button.hover(black)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            main_menu = False

    exit_button.clicked(action_exit)

    pygame.display.update()

【讨论】:

  • 感谢您的回答!我对这个解决方案有一个问题,当我做所有所说的事情时,游戏在我打开它后就会自行关闭。我想我做错了什么,但我不明白是什么。
  • 是的,我就是这么做的,一打开游戏就关闭了。
  • Nvm 我是个白痴,我有 exit_button.clicked(action_ext()) 而不是 exit_button.clicked(action_exit),对不起,谢谢!
【解决方案2】:

在您点击的函数中使 main_menu 和 main_game 变量成为全局变量

    def clicked(self):
        global main_menu, main_game
        mouse = pygame.mouse.get_pos()
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if self.x + self.width > mouse[0] > self.x and self.y + self.height > mouse[1] > self.y:
                main_menu = False
                main_game = True

【讨论】:

  • Button 用于不同的操作。您将如何处理 tutorial_buttonplay_button 的操作?
  • 当 tutorial_button 和 play_button 被按下时你想采取什么行动
  • 关键是你无法区分exit_button.clicked()tutorial_button.clicked()play_button.clicked()是在click方法内部调用的。
  • 为此我们可以使用 self.text.... 如果 self.text 执行此操作
  • 抱歉,这是一种反模式。对于每个新按钮,您必须在方法clicked 中实现一个额外的案例。请永远不要选择这样的设计。对此有不同的解决方案,例如多态性、动作或事件,...
【解决方案3】:

这是我为另一个question 写的一个例子。我把它改成了一个按钮退出游戏:

import pygame

pygame.init()

display_width = 1200
display_height = 600

# use python style variable names (lowercase)
screen = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Log In')
clock = pygame.time.Clock()

# load the font only once instead of every frame
font = pygame.font.SysFont('comicsans', 20)

# class name should be singular
class Button(pygame.sprite.Sprite):
    # 1) no need to have 4 parameters for position and size, use pygame.Rect instead
    # 2) let the Button itself handle which color it is
    # 3) give a callback function to the button so it can handle the click itself 
    def __init__(self, color, color_hover, rect, callback, text='', outline=None):
        super().__init__()
        self.text = text
        # a temporary Rect to store the size of the button
        tmp_rect = pygame.Rect(0, 0, *rect.size)

        # create two Surfaces here, one the normal state, and one for the hovering state
        # we create the Surfaces here once, so we can simple blit them and dont have
        # to render the text and outline again every frame
        self.org = self._create_image(color, outline, text, tmp_rect)
        self.hov = self._create_image(color_hover, outline, text, tmp_rect)

        # in Sprites, the image attribute holds the Surface to be displayed...
        self.image = self.org
        # ...and the rect holds the Rect that defines it position
        self.rect = rect
        self.callback = callback

    def _create_image(self, color, outline, text, rect):
        # function to create the actual surface
        # see how we can make use of Rect's virtual attributes like 'size'
        img = pygame.Surface(rect.size)
        if outline:
            # here we can make good use of Rect's functions again
            # first, fill the Surface in the outline color
            # then fill a rectangular area in the actual color
            # 'inflate' is used to 'shrink' the rect
            img.fill(outline)
            img.fill(color, rect.inflate(-4, -4))
        else:
            img.fill(color)

        # render the text once here instead of every frame
        if text != '':
            text_surf = font.render(text, 1, pygame.Color('black'))
            # again, see how easy it is to center stuff using Rect's attributes like 'center'
            text_rect = text_surf.get_rect(center=rect.center)
            img.blit(text_surf, text_rect)
        return img

    def update(self, events):
        # here we handle all the logic of the Button
        pos = pygame.mouse.get_pos()
        hit = self.rect.collidepoint(pos)
        # if the mouse in inside the Rect (again, see how the Rect class
        # does all the calculation for use), use the 'hov' image instead of 'org'
        self.image = self.hov if hit else self.org
        for event in events:
            # the Button checks for events itself.
            # if this Button is clicked, it runs the callback function
            if event.type == pygame.MOUSEBUTTONDOWN and hit:
                self.callback(self)

run = True

# we store all Sprites in a Group, so we can easily
# call the 'update' and 'draw' functions of the Buttons
# in the main loop
sprites = pygame.sprite.Group()
sprites.add(Button(pygame.Color('green'), 
                   pygame.Color('red'), 
                   pygame.Rect(150, 200, 90, 100), 
                   lambda b: print(f"Button '{b.text}' was clicked"),
                   'Press',
                   pygame.Color('black')))

def close(*args):
    global run
    run = False

sprites.add(Button(pygame.Color('dodgerblue'), 
                   pygame.Color('lightgreen'), 
                   pygame.Rect(300, 200, 90, 100), 
                   close,
                   'Close'))

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

    # update all sprites
    # it now doesn't matter if we have one or 200 Buttons
    sprites.update(events)
    # clear the screen
    screen.fill(pygame.Color('white'))
    # draw all sprites/Buttons
    sprites.draw(screen)
    pygame.display.update()
    # limit framerate to 60 FPS
    clock.tick(60)

我们只需向Button-class 传递一个回调函数,如果单击该按钮就会调用该函数。为了关闭窗口,我们调用一个小函数来捕获run 变量并将其设置为False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    相关资源
    最近更新 更多