在游戏 运行 - Python Arcade 2.4.3 时更改文本内容

Change the content of the text while the Game is running - Python Arcade 2.4.3

我正在寻找一种在游戏 运行 时更改渲染文本的方法。

我发现有人说只需更改文本变量即可。

所以我试试这个:

import arcade

WINDOW = {"width":800, "height": 600, "title": ""}

class MyGame(arcade.Window):
    """
    Main application class.
    """

    def __init__(self):

        # Call the parent class and set up the window
        super().__init__(WINDOW['width'], WINDOW['height'], WINDOW['title'])

        arcade.set_background_color(arcade.csscolor.CORNFLOWER_BLUE)

    def setup(self):
        """ Set up the game here. Call this function to restart the game. """
        pass

    def on_draw(self):
        """ Render the screen. """

        arcade.start_render()
        # Code to draw the screen goes here

        self.text = "Hello world!"
        arcade.draw_text(self.text, WINDOW['width'] / 3 + (WINDOW['width'] / 3 / 3) - 20, WINDOW['height'] / 2, arcade.csscolor.WHITE, 18)
    
    def on_mouse_release(self, x, y, button, key_modifiers):
        print("Clicked!")
        self.text = "Clicked!"

def main():
    """ Main method """
    window = MyGame()
    window.setup()
    arcade.run()


if __name__ == "__main__":
    main()

但是,文本没有改变,但它可以检测点击。

arcade.run() 运行循环,在此循环中执行 on_draw()。如果代码以 25 FPS(每秒帧数)的速度运行,那么它每秒执行 on_draw() 25 次。因此,当您单击鼠标时,on_mouse_release() 将文本更改为 "Clicked!",稍后 on_draw() 将其更改回 "Hello world!",最后显示 "Hello world!"

您应该在 __init__() 中使用 self.text = "Hello world!" 或在 setup() 中(更好)只设置一次。

import arcade

WINDOW = {"width":800, "height": 600, "title": ""}

class MyGame(arcade.Window):
    """
    Main application class.
    """

    def __init__(self):

        # Call the parent class and set up the window
        super().__init__(WINDOW['width'], WINDOW['height'], WINDOW['title'])

        arcade.set_background_color(arcade.csscolor.CORNFLOWER_BLUE)

    def setup(self):
        """ Set up the game here. Call this function to restart the game. """
        
        self.text = "Hello world!"

    def on_draw(self):
        """ Render the screen. """

        arcade.start_render()
        # Code to draw the screen goes here

        arcade.draw_text(self.text, WINDOW['width'] / 3 + (WINDOW['width'] / 3 / 3) - 20, WINDOW['height'] / 2, arcade.csscolor.WHITE, 18)
    
    def on_mouse_release(self, x, y, button, key_modifiers):
        print("Clicked!")
        self.text = "Clicked!"

def main():
    """ Main method """
    window = MyGame()
    window.setup()
    arcade.run()


if __name__ == "__main__":
    main()

下面是点击鼠标更改文本的简短示例:

import arcade

class Game(arcade.Window):
    def __init__(self):
        super().__init__(400, 300)
        self.text = 'Waiting for click!'

    def on_draw(self):
        arcade.start_render()
        arcade.draw_text(self.text, 200, 150, arcade.color.RED, 18, anchor_x='center')

    def on_mouse_release(self, x, y, button, key_modifiers):
        self.text = 'Clicked!'

Game()
arcade.run()

输出: