首页 > 解决方案 > Pygame中的文本输出?

问题描述

我正在开发一款基于文本的游戏,我遇到了一些困难。

我正在将它从通过打印输出工作的版本移植到在 pygame 窗口中运行的版本。

目前我的输入工作正常,但我的输出仍然打印到控制台。有人告诉我应该将输出放入文本缓冲区,这可以通过将 print() 函数更改为 my_print 来实现。

问题是,我对使用文本缓冲区一无所知。

据我了解,文本缓冲区的目的是将所需的输出存储为变量,然后可以将其显示在我的 pygame 窗口中。我只是不确定该怎么做。

我还希望最近的 5 个输出显示在一种“游戏日志”中。

该视频对弄清楚输入有很大帮助,但输出部分似乎并不是我所需要的。

https://www.youtube.com/watch?v=G933SOLWbbg&t=181s

这是我的代码:

展示:

from pygame_functions import *
import random
screenSize(800, 800)

wordBox = makeTextBox(50, 700, 700, 0, "Enter Command", 0, 24)
showTextBox(wordBox)

gameLog = makeLabel(my_print, 30, 50, 500, "white", "Agency FB", "black" )
showLabel(gameLog)

游戏文件:

from pygame import *
from gameworld import *
from Display import *

def main():

    player = Player("Jeff", 100)
    bag = Bag([])
    location = Location('introd')

    command = '  '
    while True:
        command = textBoxInput(wordBox)
        if command in location.room.exits:
            location.travel(command, bag)
        elif command == 'look':
            location.room_desc()
        elif command == '':
            print('You have to say what it is you want to do!')
            command = '#'
        elif command == 'search':
            location.search_room()
        elif command.split()[0] == 'Take':
            location.check_take(command.split()[1], bag, location)
        elif command == 'Inventory':
            bag.check_inv()
        else:
            print('Invalid command')
        if not command:
            break


if __name__ == '__main__':
    main()

游戏世界:

from gameitems import *


class Room:

    def __init__(self, name, description, exits, actions, roominv, roomkey, lock):
        self.name = name
        self.description = description
        self.exits = exits
        self.actions = actions
        self.roominv = roominv
        self.roomkey = roomkey
        self.lock = lock


class Player:

    def __init__(self, name, health):
        self.name = name
        self.health = health


class Location:

    def __init__(self, room):
        self.room = world[room]

    def travel(self, direction, bag):
        if direction not in self.room.exits:
            self.no_exit()
        else:
            self.set_new_room_name(direction, bag)

    def set_new_room_name(self, direction, bag):
        new_room_name = self.room.exits[direction]
        print("moving to", new_room_name)
        self.key_check(new_room_name, bag)

    def key_check(self, new_room_name, bag):
        if world[new_room_name].lock and world[new_room_name].roomkey not in bag.inventory:
            self.no_key()
        else:
            world[new_room_name].lock = False
            self.set_room(new_room_name)
            self.room_desc()

    def set_room(self, new_room_name):
        self.room = world[new_room_name]

    def no_exit(self):
        print("You can't go that way!")

    def no_key(self):
        print('The door is locked! You need the right key!')

    def room_desc(self):
        print(self.room.description)
        print(self.room.actions)

    def search_room(self):
        if self.room.roominv:
            for item in list(self.room.roominv.keys()):
                print("you find a", item)
        else:
            print("You don't find anything")

    def none_here(self, key):
        print("You can't find a", key)

    def check_take(self, key, bag, location):
        if key in self.room.roominv:
            bag.add_to_inv(key, location)
            print('you take the', key)
        else:
            self.none_here(key)


class Bag():

    def __init__(self, inventory):
        self.inventory = inventory

    def add_to_inv(self, key, location):
        self.inventory.append(location.room.roominv[key])
        del location.room.roominv[key]

    def check_inv(self):
        for item in self.inventory:
            print("Your bag contains:", item.name)


world = {}

world['introd'] = Room('introd', "You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.", {'n': "clearing"}, {"Search the ground", "Go North"}, {'Sword': Sword}, None, False)

world['clearing'] = Room('clearing', "You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. \
To the South is the way you entered the forest. A well worn path goes to the East. In the distance a harp can be heard.", {'s': "introd", 'e': "forest path"}, {"Take flower", "Go south", "Go East"}, {'Flower': Flower}, None, False)

world['forest path'] = Room('forest path', "You begin walking down a well beaten path. The sounds of the forest surround you. Ahead you can see a fork in the road branching to the South and East.\
You can smell smoke coming from the South, and can hear a stream to the East", {'s': "cottage", 'e': "stream", 'w': "clearing"}, {"Go South", "Go East", "Go West"}, {'Stick': Stick}, None, False)

world['stream'] = Room('stream', "You come upon a relaxing stream at the edge of the woods. It looks like there is something shiny in the water. To your South is a rickety looking shack, \
to your West is the forest path you came down", {'s': "shack", 'w': "forest path"}, {"Go South", "Go West"}, {'Rusty_Key': Rusty_Key}, None, False)

world['shack'] = Room('shack', "In front of you is a shack, possibly used as an outpost for hunting. It looks dilapidated.", {'s': "inside shack", 'n': "stream"}, {"Go South", "Go North"}, None, None, False)

world['inside shack'] = Room('inside shack', "The inside of the shack is dirty. Bits of ragged fur are scattered about the floor and on a table against the back wall.\
A sharp looking knife is on the table. There is an ornate key hanging on the wall by a string.", {'n': "shack"}, {"Go North", "Take Knife", "Take Key"}, {'Knife': Knife, 'Ornate_Key': Ornate_Key}, Rusty_Key, True)

world['cottage'] = Room('cottage', "A quaint cottage sits in the middle of a small clearing, smoke drifting lazily from the chimney.", {'n': "forest path"}, {"Go north"}, None, None, False)

world['inside cottage'] = Room('inside cottage', "The inside of the cottage is warm and cozy. It reeks like death.", {'n': 'outside cottage'}, None, {'Moonstone': Moonstone}, Ornate_Key, True)

游戏物品:

class Items:
    def __init__(self, name, info, weight):
        self.name = name
        self.info = info
        self.weight = weight


class DoorKeys(Items):
    def __init__(self, name, info, weight):
        super().__init__(name, info, weight)


class Weapon(Items):
    def __init__(self, name, info, damage, speed, weight):
        super().__init__(name, info, weight)
        self.damage = damage
        self.speed = speed


Sword = Weapon("Sword", "A sharp looking sword. Good for fighting goblins!", 7, 5, 5)
Knife = Weapon("Knife", "A wicked looking knife, seems sharp!", 5, 7, 3)
Stick = Weapon("Stick", "You could probably hit someone with this stick if you needed to", 2, 3, 3)
Rusty_Key = DoorKeys("Rusty_Key", "A key! I wonder what it opens.", .01)
Ornate_Key = DoorKeys("Ornate_Key", "An ornate key with an engraving of a small cottage on one side", .01)
Moonstone = Items("Moonstone", "A smooth white stone that seems to radiate soft white light", .05)
Flower = Items("Flower", "A beautiful wildflower", .001)

标签: pythontextpygameoutput

解决方案


他们所说的Text Buffer只是创建Font Object的一个花哨的术语。

首先,您将使用生成一个字体对象pygame.font.Font

myFont = pygame.font.Font('MyFontFile.ttf', MySize)

然后你会使用Font.render

myText = myFont.render('myText', True, MyColor)

Finnaly,你会把它放到屏幕上。

myScreen.blit(myText, (0, 0))

对于像您这样复杂的项目和您想要的东西,您可能想要创建一个继承字体对象的全文对象

class AdvancedFont(pygame.font.Font):
    def __init__(self):
        super().__init__()

它可以有滚动功能,颜色,任何你想要的!

另外,在你的下一个问题上,尝试减少一些示例代码,直到我们可以得到一些更可测试的东西。


推荐阅读