140433fd by Barry

Mmoved all commands to their own files to load dynamically to save memory.

1 parent 664e6bd3
def drop(id, tokens, players, mud):
room_name = players[id]["room"]
if len(tokens) == 0:
mud.send_message(id, 'What do you want to drop?')
return True
room_data = utils.load_object_from_file('rooms/' + room_name + '.txt')
if tokens[0] in players[id]['inventory']:
players[id]['inventory'][tokens[0]] -= 1
if players[id]['inventory'][tokens[0]] <= 0:
del players[id]['inventory'][tokens[0]]
if tokens[0] in room_data['inventory']:
room_data['inventory'][tokens[0]] += 1
else:
room_data['inventory'][tokens[0]] = 1
utils.save_object_to_file(room_data, 'rooms/' + room_name + '.txt')
for pid, pl in players.items():
# if they're in the same room as the player
if players[pid]["room"] == players[id]["room"]:
# send them a message telling them what the player said
mud.send_message(pid, "{} dropped a {}.".format(
players[id]["name"], tokens[0]))
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
else:
mud.send_message(id, 'You do not have {} in your inventory.'.format(tokens[0]))
drop(id, tokens, players, mud)
\ No newline at end of file
def get(id, tokens, players, mud):
room_name = players[id]["room"]
if len(tokens) == 0:
mud.send_message(id, 'What do you want to get?')
return True
room_data = utils.load_object_from_file('rooms/' + room_name + '.txt')
if tokens[0] in room_data.get('inventory'):
if tokens[0] in players[id]['inventory']:
players[id]['inventory'][tokens[0]] += 1
else:
players[id]['inventory'][tokens[0]] = 1
for pid, pl in players.items():
# if they're in the same room as the player
if players[pid]["room"] == players[id]["room"]:
# send them a message telling them what the player said
mud.send_message(pid, "{} picked up a {}.".format(
players[id]["name"], tokens[0]))
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
else:
mud.send_message(id, 'There is no {} here to get.'.format(tokens[0]))
get(id, tokens, players, mud)
\ No newline at end of file
def go(id, params, players, mud, tokens):
# store the exit name
params = params.lower().strip()
room_data = utils.load_object_from_file('rooms/' + players[id]["room"] + '.txt')
exits = room_data['exits']
# if the specified exit is found in the room's exits list
if params in exits:
# go through all the players in the game
for pid, pl in players.items():
# if player is in the same room and isn't the player
# sending the command
if players[pid]["room"] == players[id]["room"] \
and pid != id:
# send them a message telling them that the player
# left the room
mud.send_message(pid, "{} left via exit '{}'".format(
players[id]["name"], params))
# update the player's current room to the one the exit leads to
if room_data['exits'][params] == None:
mud.send_message(id, "An invisible force prevents you from going in that direction.")
return None
else:
players[id]["room"] = exits[params]
room = params
# go through all the players in the game
for pid, pl in players.items():
# if player is in the same (new) room and isn't the player
# sending the command
if players[pid]["room"] == players[id]["room"] \
and pid != id:
# send them a message telling them that the player
# entered the room
mud.send_message(pid,
"{} arrived via exit '{}'".format(
players[id]["name"], params))
# send the player a message telling them where they are now
title = utils.load_object_from_file('rooms/' + players[id]["room"] + '.txt')['title']
mud.send_message(id, "You arrive at '{}'".format(title))
tokens = []
return 'look'
# the specified exit wasn't found in the current room
else:
# send back an 'unknown exit' message
mud.send_message(id, "Unknown exit '{}'".format(params))
next_command = go(id, params, players, mud, tokens)
\ No newline at end of file
def help(id, tokens, mud):
if len(tokens) > 0:
filename = 'help/' + tokens[0] + '.txt'
else:
filename = 'help/help.txt'
try:
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
mud.send_message(id, line, '\r')
mud.send_message(id, '')
except:
mud.send_message(id, 'No help topics available for \"{}\". A list\r\n of all commands is available at: help index'.format(tokens[0]))
help(id, tokens, mud)
\ No newline at end of file
def inventory(id, players, mud):
mud.send_message(id, '\r\n-Item----------=Inventory=-----------Qty-\r\n')
for item, qty in players[id]['inventory'].items():
mud.send_message(id, '{} {}'.format(item.ljust(37), qty))
mud.send_message(id, '\r\n-----------------------------------------')
inventory(id, players, mud)
\ No newline at end of file
def look(id, mud, players, tokens):
room_name = players[id]["room"]
room_data = utils.load_object_from_file('rooms/' + room_name + '.txt')
mud.send_message(id, "")
if len(tokens) > 0 and tokens[0] == 'at':
del tokens[0]
if len(tokens) == 0:
mud.send_message(id, room_data.get('description'))
else:
subject = tokens[0]
items = room_data.get('look_items')
for item in items:
if subject in item:
mud.send_message(id, items[item])
return True
if subject in ['inventory']:
mud.send_message(id, 'You the area see a {}:'.format(subject))
mud.send_message(id, room_data.get('description'))
return True
if subject in players[id]['inventory']:
mud.send_message(id, 'You check your inventory and see a {}:'.format(subject))
mud.send_message(id, room_data.get('description'))
return True
mud.send_message(id, "That doesn't seem to be here.")
playershere = []
# go through every player in the game
for pid, pl in players.items():
# if they're in the same room as the player
if players[pid]["room"] == players[id]["room"]:
# ... and they have a name to be shown
if players[pid]["name"] is not None:
# add their name to the list
playershere.append(players[pid]["name"])
# send player a message containing the list of players in the room
mud.send_message(id, "Players here: {}".format(
", ".join(playershere)))
# send player a message containing the list of exits from this room
mud.send_message(id, "Exits are: {}".format(
", ".join(room_data.get('exits'))))
# send player a message containing the list of exits from this room
mud.send_message(id, "Items here: {}".format(
", ".join(room_data.get('inventory').keys())))
look(id, mud, players, tokens)
\ No newline at end of file
def prompt(id, tokens, params, players, mud):
if len(tokens) == 0:
mud.send_message(id, 'No prompt provided, no changes will be made.\r\nEx: prompt %hp>')
players[id]['prompt'] = params + ' '
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
prompt(id, tokens, params, players, mud)
\ No newline at end of file
def quit(id, players, mud):
# send the player back the list of possible commands
mud.send_message(id, "Saving...")
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
mud.disconnect_player(id)
quit(id, players, mud)
\ No newline at end of file
def save(id, players, mud):
# send the player back the list of possible commands
mud.send_message(id, "Saving...")
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
mud.send_message(id, "Save complete")
save(id, players, mud)
\ No newline at end of file
def say(id, params, players, mud):
# go through every player in the game
for pid, pl in players.items():
# if they're in the same room as the player
if players[pid]["room"] == players[id]["room"]:
# send them a message telling them what the player said
mud.send_message(pid, "{} says: {}".format(
players[id]["name"], params))
say(id, params, players, mud)
\ No newline at end of file
def whisper(id, tokens, players, mud):
# go through every player in the game
for pid, pl in players.items():
# if they're in the same room as the player
if players[pid]["name"] == tokens[0]:
# send them a message telling them what the player said
mud.send_message(pid, "{} whispers: {}".format(
players[id]["name"], ' '.join(tokens[1:])))
whisper(id, tokens, players, mud)
\ No newline at end of file
def who(self):
self.mud.send_message(self.id, "")
self.mud.send_message(self.id, "-------- {} Players Currently Online --------".format(len(self.players)))
for pid, player in self.players.items():
self.mud.send_message(self.id, " " + player["name"])
self.mud.send_message(self.id, "---------------------------------------------".format(len(self.players)))
self.mud.send_message(self.id, "")
who(self)
\ No newline at end of file
......@@ -28,8 +28,7 @@ if 'esp' in sys.platform:
import machine
# import the MUD server class
from mudserver import MudServer
from commandhandler import CommandHandler
from roomloader import RoomLoader
import utils
print('STARTING MUD\r\n\r\n\r\n')
......@@ -41,11 +40,7 @@ if 'esp' in sys.platform:
players = {}
# start the server
mud = MudServer()
cmd_handler = CommandHandler()
roomloader = RoomLoader('rooms')
globals()['mud'] = MudServer()
def prompt(pid):
if "prompt" not in players[pid]:
......@@ -157,9 +152,12 @@ while True:
+ "\r\nType 'help' for a list of commands. Have fun!\r\n\r\n")
# send the new player the description of their current room
mud.send_message(id, roomloader.get_description(players[id]["room"]))
mud.send_message(id, utils.load_object_from_file('rooms/' + players[id]["room"] + '.txt')['description'])
else:
from commandhandler import CommandHandler
cmd_handler = CommandHandler()
handler_results = cmd_handler.parse(id, command, params, mud, players)
......
{"name": "test", "room": "Tavern", "inventory": {"candle": 1}, "prompt": "hp:%hp mp:%mp> ", "aliases": {}, "hp": 100, "mp": 100}
\ No newline at end of file
{"name": "test", "room": "Tavern", "inventory": {"candle": 1}, "prompt": "%hp> ", "aliases": {}, "hp": 100, "mp": 100}
\ No newline at end of file
......
......@@ -21,6 +21,9 @@ for f in os.listdir('rooms'):
for f in os.listdir('inventory'):
files.append('inventory/' + f)
for f in os.listdir('commands'):
files.append('commands/' + f)
with open('releasepw.conf', 'r', encoding='utf-8') as f:
password = f.read()
......
{"title": "Tavern", "description": "You're in a cozy tavern warmed by an open fire.", "exits": {"outside": "Outside", "behind": "Room001", "dark": "Dark"}, "look_items": {"bar": "The bar is a long wooden plank thrown over roughly hewn barrels.", "barrel,barrels": "The old barrels bands are thick with oxidation and stained with the purple of spilled wine.", "wooden,oak,plank": "An old solid oak plank that has a large number of chips and drink marks.", "fire": "The fire crackles quietly in the corner providing a small amount of light and heat."}, "inventory": {"candle": 11}}
\ No newline at end of file
{"title": "Tavern", "description": "You're in a cozy tavern warmed by an open fire.", "exits": {"outside": "Outside", "behind": "Room001", "dark": "Dark"}, "look_items": {"bar": "The bar is a long wooden plank thrown over roughly hewn barrels.", "barrel,barrels": "The old barrels bands are thick with oxidation and stained with the purple of spilled wine.", "wooden,oak,plank": "An old solid oak plank that has a large number of chips and drink marks.", "fire": "The fire crackles quietly in the corner providing a small amount of light and heat."}, "inventory": {"candle": 13}}
\ No newline at end of file
......
......@@ -5,8 +5,10 @@ def save_object_to_file(obj, filename):
f.write(json.dumps(obj))
def load_object_from_file(filename):
#try:
with open(filename, 'r', encoding='utf-8') as f:
return json.loads(f.read())
#except Exception:
# return None
try:
with open(filename, 'r', encoding='utf-8') as f:
return json.loads(f.read())
except Exception as e:
print('Error opening file: ' + filename)
print(e)
return None
......