2
\$\begingroup\$

I'm creating a text-based adventure game using PyGame. I plan on also implementing kind of a Pokemon/Final Fantasy style combat system that works with menus instead of commands, but I haven't started that yet.

The pygame_functions module can be found here; I didn't make it.

Issues I know are present:

  • I'd like to load in my World dict and Item definitions from a JSON file

  • I have a module called "Definitions" that was only created because I needed to move variables out of the main game file. This will be turned into something else, or the variables will be moved somewhere.

  • In myinput.py I'm relying on an elif block. I think I should probably change this to check from a dict of commands?

    • In the Items class, the DoorKeys subclass is currently pointless. I might be doing something cool with this later though.

gamefile.py

import myinput
from definitions import *


def main():

    while True:

        location.bgChange()
        myinput.input_loop()


if __name__ == '__main__':
    main()

myinput.py

from pygame import *
from gameworld import *
from display import *
from myoutput import *
from audio import *
from definitions import *
from nltk import tokenize


def input_loop():
    command = '  '
    while True:
        command = textBoxInput(wordBox)
        if command in location.room.exits:
            location.travel(command, bag)
        elif command == 'look':
            location.room_desc()
        elif command == '':
            log.insert(0, 'You have to say what it is you want to do!')
            logLimit()
            logUpdate()
            command = '#'
        elif command == 'search':
            location.search_room()
        elif command.split()[0] == 'take':
            try:
                location.check_take(command.split()[1], bag, location)
            except IndexError:
                log.insert(0, 'What do you want to take?')
                logLimit()
                logUpdate()
        elif command == 'inventory':
            bag.check_inv()
        elif command == 'checklog':
            print(log)
        else:
            log.insert(0, 'Invalid Command')
            logLimit()
            logUpdate()
        if not command:
            break

display.py

from pygame_functions import *
import random
from myoutput import log
screenSize(1800, 800)

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

gameLog1 = makeLabel(log[0], 20, 50, 600, "white", "Agency FB", "black")
showLabel(gameLog1)

gameLog2 = makeLabel(log[1], 20, 50, 564, "white", "Agency FB", "black")
showLabel(gameLog2)

gameLog3 = makeLabel(log[2], 20, 50, 528, "white", "Agency FB", "black")
showLabel(gameLog3)

gameLog4 = makeLabel(log[3], 20, 50, 492, "white", "Agency FB", "black")
showLabel(gameLog4)

gameLog5 = makeLabel(log[4], 20, 50, 456, "white", "Agency FB", "black")
showLabel(gameLog5)


def logUpdate():
    changeLabel(gameLog1, log[0])
    changeLabel(gameLog2, log[1])
    changeLabel(gameLog3, log[2])
    changeLabel(gameLog4, log[3])
    changeLabel(gameLog5, log[4])

gameitems.py

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)

gameworld.py

from gameitems import *
from display import *
from myoutput import *


class Room:

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


class Player:

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


class Location:

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

    def musChange(self):
        mus = self.room.music
        if self.room.music:
            pygame.mixer.music.load(mus)
            pygame.mixer.music.play(-1)
        else:
            pass

    def bgChange(self):
        bg = self.room.background
        if self.room.background:
            setBackgroundImage(bg)
        else:
            pass

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

    def set_new_room_name(self, direction, bag):
        new_room_name = self.room.exits[direction]
        log.insert(0, "moving to" + ' ' + new_room_name)
        logLimit()
        logUpdate()
        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):
        log.insert(0, "You can't go that way!")
        logLimit()
        logUpdate()

    def no_key(self):
        log.insert(0, 'The door is locked! You need the right key!')
        logLimit()
        logUpdate()

    def room_desc(self):
        log.insert(0, self.room.description + ' You can: ' + ' , '.join(self.room.actions))
        logLimit()
        logUpdate()

    def search_room(self):
        if self.room.roominv:
            for i in self.room.roominv.keys():
                log.insert(0, "you find a" + ' ' + i)
                logLimit()
                logUpdate()
        else:
            log.insert(0, "You don't find anything")
            logLimit()
            logUpdate()

    def none_here(self, key):
        log.insert(0, "You can't find a" + ' ' + key)
        logLimit()
        logUpdate()

    def check_take(self, key, bag, location):
        if key in self.room.roominv:
            bag.add_to_inv(key, location)
            log.insert(0, 'you take the' + ' ' + key)
            logLimit()
            logUpdate()
        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):
        if self.inventory:
            for item in self.inventory:
                log.insert(0, "Your bag contains:" + ' ' + item.name)
                logLimit()
                logUpdate()
        else:
            log.insert(0, "Your bag is empty")
            logLimit()
            logUpdate()


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.", {'north': "clearing"}, {"Search the ground", "Go North"}, {'Sword': Sword}, None, False, 'Background.jpg', 'IntroMus.mp3')

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, 'Background2.jpg', 'IntroMus.mp3')

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", {'south': "cottage", 'east': "stream", 'west': "clearing"}, {"Go South", "Go East", "Go West"}, {'Stick': Stick}, None, False, None, None)

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", {'south': "shack", 'west': "forest path"}, {"Go South", "Go West"}, {'Rusty_Key': Rusty_Key}, None, False, 'bgStream.jpg', 'StreamSong.mp3')

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

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.", {'north': "shack"}, {"Go North", "Take Knife", "Take Key"}, {'Knife': Knife, 'Ornate_Key': Ornate_Key}, Rusty_Key, True, None, None)

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

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

myoutput.py

log = ["Welcome my dear friend, to The Woodsman's Tale", "Listen Well, for in my current state I can only say this once", "Command List: search - searches the current room|||, look - describes the current room|||, take *item name* - picks up the item you specify|||, inventory - check your bags", "north, south, east, and west, will guide you", "all commands are currently case-sensitive. Thank you for playing!"]


def logLimit():
    if len(log) > 5:
        log.pop()

audio.py

import pygame


def bgMusic():
    pygame.mixer.music.load('IntroMus.mp3')
    pygame.mixer.music.play(-1)


bgMusic()
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.