1

I'm hitting a bit of a wall with a text-based game that I'm working on.

I'm in the process of porting it from a version that works through print-output to a version that runs in a pygame window.

Currently my input works fine, however my output still prints to the console. I was told I should be putting the output into a text buffer, and this could be achieved by changing my print() functions to my_print.

The thing is, I know nothing about using text-buffers.

From what I understand, the point of a text-buffer would be to store the desired output as a variable, which can then be displayed in my pygame window. I'm just not really sure how to do this.

I would also preferably like the most recent 5 outputs to display in a sort of "Game Log".

This video helped significantly with figuring out the input, but the output section doesn't seem to be quite what I need.

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

Here's my code:

display:

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)

1 Answer 1

2

What they mean by a Text Buffer is just a fancy term of creating a Font Object.

First you would generate a font object using pygame.font.Font

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

And then you would render it using Font.render

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

Finnaly, you would blit it onto the screen.

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

With a project as complex as yours and the stuff you want though, you might want to create a full text object that inherits the font object

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

It could have scrolling capabilities, colors, whatever you would like!

Also, on youre next question, try cutting down the example code some until we can get something slightly more testable.

Sign up to request clarification or add additional context in comments.

3 Comments

So, I understand that I can use this to render a specific message onto the screen, but it's unclear to me how I can adapt this to replace my print functions. Can you elaborate at all?
Sure! What you can do is change the print statements and instead just add text objects into a list. Afterwards, loop through the list and then draw the text, when the list exceeds a length of 5, knock off the first text object in the list. this would allow the log you wanted.
but, want to print something in console while developing and not in pygame window; How to do this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.