Я бью об стенку с текстовой игрой, над которой я работаю.
Я в процессе переноса из версии, работающей через вывод на печать, в версию, запускаемую в окне Pygame.
В настоящее время мой ввод работает нормально, однако мой вывод все еще работаетвыводит на консоль.Мне сказали, что я должен поместить вывод в текстовый буфер, и этого можно добиться, изменив мои функции print () на my_print.
Дело в том, что я ничего не знаю об использовании текстовых буферов.
Исходя из того, что я понимаю, смысл текстового буфера заключался бы в сохранении желаемого результата в виде переменной, которая затем может отображаться в моем окне Pygame.Я просто не совсем уверен, как сделать это.
Я бы также хотел, чтобы последние 5 выходов отображались в виде "Game Log".
Это видео значительно помогло с выяснением входных данных, но секция вывода, кажется, не совсем то, что мне нужно.
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)
gamefile:
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()
gameworld:
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)
gameitems:
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)