a757808c by Barry

Big change to move all the commands to the command handler so it could be

pushed to the flash.
1 parent 59adb22d
def actions(id, players, mud):
mud.send_message(id, '\r\n-Action----------=Actions=-----------Cost-\r\n')
for name, action in players[id]['at'].items():
mud.send_message(id, '{} {}'.format("%-37s" % name, action['cost']))
mud.send_message(id, '\r\n------------------------------------------\r\n')
mud.send_message(id, 'For more detail on a specific action use "help <action>"')
actions(id, players, mud)
del actions
\ No newline at end of file
import utils
# for now spells can only be cast on the thing you are fighting since I don't have a good lexer to pull
# out targets. This also means that spells are offensive only since you cant cast on 'me'
# TODO: Add proper parsing so you can do: cast fireball on turkey or even better, cast fireball on the first turkey
def cast(id, params, players, mud, command):
if params == '':
params = command.strip()
else:
params = params.strip()
if len(params) == 0:
mud.send_message(id, 'What spell do you want to cast?')
return True
spell = players[id]['sp'].get(params)
if not spell:
mud.send_message(id, 'You do not appear to know how to cast %s.' % (params,))
return True
mp = players[id]['mp']
if mp > 0 and mp > spell['cost']:
room_monsters = utils.load_object_from_file('rooms/{}_monsters.json'.format(players[id]['room']))
if not room_monsters:
mud.send_message(id, 'There is nothing here to cast that spell on.')
for mon_name, monster in room_monsters.items():
monster_template = utils.load_object_from_file('mobs/{}.json'.format(mon_name))
if not monster_template:
continue
fighting = False
for active_monster_idx, active_monster in enumerate(monster['active']):
if active_monster['action'] == "attack" and active_monster['target'] == players[id]['name']:
fighting = True
att, mp = utils.calc_att(mud, id, [], mp, spell)
players[id]['mp'] = mp
active_monster['hp'] -= att
# don't let them off without saving cheating sons of bees
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
room_monsters[mon_name]['active'][active_monster_idx] = active_monster
if not fighting:
mud.send_message(id, 'You are not currently in combat')
return True
utils.save_object_to_file(room_monsters, 'rooms/{}_monsters.json'.format(players[id]['room']))
else:
mud.send_message(id, 'You do not have enough mana to cast that spell.')
if command is None and cmd is not None:
command = cmd
cast(id, params.strip(), players, mud, command)
del cast
\ No newline at end of file
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 + '.json')
if tokens[0] in players[id]['inventory']:
if tokens[0] in room_data['inventory']:
room_data['inventory'][tokens[0]].append(players[id]['inventory'][tokens[0]].pop())
else:
room_data['inventory'][tokens[0]] = [players[id]['inventory'][tokens[0]].pop()]
if len(players[id]['inventory'][tokens[0]]) <= 0:
del players[id]['inventory'][tokens[0]]
utils.save_object_to_file(room_data, 'rooms/' + room_name + '.json')
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)
del drop
\ No newline at end of file
def emote(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, "{} {}".format(players[id]["name"], params))
emote(id, params, players, mud)
del emote
\ No newline at end of file
def equip(id, players, tokens, mud):
if len(tokens) == 0:
mud.send_message(id, " %green+-Item---------------------=Equipment=------------------Loc----+", nowrap=True)
if players[id].get('equipment'):
for item, item_list in players[id]['equipment'].items():
if isinstance(item_list, list):
vals = [val for val in item_list if val]
if len(vals) > 0:
mud.send_message(id, ' %green|%reset {} {} %green|'.format("%-51s" % ', '.join(vals), item.rjust(8, ' ')))
else:
mud.send_message(id, ' %green|%reset {} {} %green|'.format("%-51s" % 'None', item.rjust(8, ' ')))
else:
mud.send_message(id, ' %green|%reset {} {} %green|'.format("%-51s" % item_list or "None", item.rjust(8, ' ')))
mud.send_message(id, ' %green|%reset {} {} %green|'.format("%-51s" % players[id]['weapon'] or "None", 'weapon'.rjust(8, ' ')))
mud.send_message(id, " %green+--------------------------------------------------------------+", nowrap=True)
else:
if tokens[0] not in players[id]["inventory"]:
mud.send_message(id, 'You do not have {} in your inventory.'.format(tokens[0]))
else:
gear = utils.load_object_from_file('inventory/' + tokens[0] + '.json')
if gear["type"] == "weapon":
mud.send_message(id, 'That is a weapon and must be "wield".')
elif gear["type"] != "armor":
mud.send_message(id, 'That cannot be worn.')
else:
players[id]["equipment"][gear['loc']] = tokens[0]
mud.send_message(id, 'You wear the {} on your {}.'.format(tokens[0], gear['loc']))
players[id]["inventory"][tokens[0]].pop()
if len(players[id]["inventory"][tokens[0]]) == 0:
del players[id]["inventory"][tokens[0]]
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
equip(id, players, tokens, mud)
del equip
\ No newline at end of file
def get(id, params, 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 + '.json')
container = None
if any(x in params for x in ['from', 'out of']):
if 'out of' in params:
container = params.split('out of')[1].strip()
else:
container = params.split('from')[1].strip()
if room_data["inventory"].get(container) is None and players[id]["inventory"].get(container) is None:
mud.send_message(id, 'You do not see the container {} here.'.format(container))
return True
if container:
found = False
if container in players[id]["inventory"]:
if tokens[0] in players[id]['inventory'][container][0]['inventory']:
found = True
if tokens[0] in players[id]['inventory']:
print(players[id]['inventory'][container][0]['inventory'][tokens[0]])
players[id]['inventory'][tokens[0]].append(players[id]['inventory'][container][0]['inventory'][tokens[0]].pop())
else:
players[id]['inventory'][tokens[0]] = [players[id]['inventory'][container][0]['inventory'][tokens[0]].pop()]
if len(players[id]['inventory'][container][0]['inventory'][tokens[0]]) <= 0:
del players[id]['inventory'][container][0]['inventory'][tokens[0]]
elif container in room_data["inventory"]:
if tokens[0] in room_data['inventory'][container][0]['inventory']:
found = True
if tokens[0] in players[id]['inventory']:
players[id]['inventory'][tokens[0]].append(room_data['inventory'][container][0]['inventory'][tokens[0]].pop())
else:
players[id]['inventory'][tokens[0]] = [room_data['inventory'][container][0]['inventory'][tokens[0]].pop()]
if len(room_data['inventory'][container][0]['inventory'][tokens[0]]) <= 0:
del room_data['inventory'][container][0]['inventory'][tokens[0]]
if not found:
mud.send_message(id, 'You do not see a {} in the {}.'.format(tokens[0], container))
else:
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 {} from a {}.".format(players[id]["name"], tokens[0], container))
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
utils.save_object_to_file(room_data, 'rooms/' + room_name + '.json')
return True
else:
if tokens[0] in room_data.get('inventory'):
if tokens[0] in players[id]['inventory']:
players[id]['inventory'][tokens[0]].append(room_data['inventory'][tokens[0]].pop())
else:
players[id]['inventory'][tokens[0]] = [room_data['inventory'][tokens[0]].pop()]
if len(room_data['inventory'][tokens[0]]) <= 0:
del room_data['inventory'][tokens[0]]
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"]))
utils.save_object_to_file(room_data, 'rooms/' + room_name + '.json')
else:
mud.send_message(id, 'There is no {} here to get.'.format(tokens[0]))
get(id, params.lower().strip(), tokens, players, mud)
\ No newline at end of file
def go(id, params, players, mud, tokens, command):
# store the exit name
if params == '':
params = command.strip().lower()
else:
params = params.strip().lower()
room_data = utils.load_object_from_file('rooms/' + players[id]["room"] + '.json')
# if the specified exit is found in the room's exits list
exits = room_data['exits']
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 exits[params] == None:
mud.send_message(id, "An invisible force prevents you from going in that direction.")
return None
else:
new_room = utils.load_object_from_file('rooms/' + exits[params][0] + '.json')
if not new_room:
mud.send_message(id, "An invisible force prevents you from going in that direction.")
return None
else:
players[id]["room"] = exits[params][0]
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
mud.send_message(id, "You arrive at '{}'".format(new_room['title']))
# 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
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))
if command is None and cmd is not None:
command = cmd
next_command = go(id, params, players, mud, tokens, command)
del go
\ 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)
del help
\ No newline at end of file
def inventory(id, players, mud):
mud.send_message(id, " %green+-Item---------------------=Inventory=--------------------Qty--+", nowrap=True)
for item, item_list in players[id]['inventory'].items():
mud.send_message(id, ' %green|%reset {} {} %green|'.format("%-55s" % item, str(len(item_list)).center(4, ' ')))
mud.send_message(id, " %green+--------------------------------------------------------------+", nowrap=True)
inventory(id, players, mud)
del inventory
\ No newline at end of file
def kill(id, params, players, mud):
if len(params) == 0:
mud.send_message(id, 'What did you want to attack?')
return True
room_monsters = utils.load_object_from_file('rooms/{}_monsters.json'.format(players[id]['room']))
for mon_name, monster in room_monsters.items():
if mon_name in params.lower():
if len(monster['active']) > 0:
if monster['active'][0]['target'] == players[id]['name']:
mud.send_message(id, 'You are already engaged in combat with that target.')
return True
else:
room_monsters[mon_name]['active'][0]['target'] = players[id]['name']
mud.send_message(id, 'You attack the {}.'.format(mon_name), color=['red', 'bold'])
utils.save_object_to_file(room_monsters, 'rooms/{}_monsters.json'.format(players[id]['room']))
return True
if params[0] in 'aeiou':
mud.send_message(id, 'You do not see an {} here.'.format(params))
else:
mud.send_message(id, 'You do not see a {} here.'.format(params))
kill(id, params, players, mud)
del kill
\ 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 + '.json')
room_monsters = utils.load_object_from_file('rooms/' + room_name + '_monsters.json')
mud.send_message(id, "")
if len(tokens) > 0 and tokens[0] == 'at':
del tokens[0]
container = False
if len(tokens) > 0 and tokens[0] == 'in':
del tokens[0]
container = True
if len(tokens) == 0:
exits = {}
for exit_name, exit in room_data.get('exits').items():
exits[exit_name] = exit[1]
print(room_data)
# clid, name, zone, terrain, description, exits, coords
mud.send_room(id, room_data.get('num'), room_data.get('title'), room_data.get('zone'),
'City', '', exits, room_data.get('coords'))
mud.send_message(id, room_data.get('title'), color=['bold', 'green'])
mud.send_message(id, room_data.get('description'), line_ending='\r\n\r\n', color='green')
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 room_data['inventory']:
if container and room_data["inventory"][subject][0].get("inventory") is not None:
items = room_data["inventory"][subject][0]["inventory"]
if len(items) > 0:
mud.send_message(id, 'You look in the {} and see:\r\n'.format(subject))
inv_list = []
for name, i in items.items():
if len(i) > 1:
inv_list.append(str(len(i)) + " " + name + "s")
else:
inv_list.append(name)
mud.send_list(id, inv_list, "look")
else:
mud.send_message(id, 'You look in the {} and see nothing.'.format(subject))
else:
item = utils.load_object_from_file('inventory/' + subject + '.json')
mud.send_message(id, 'You see {}'.format(item.get('description')))
return True
if subject in players[id]['inventory']:
if container and players[id]["inventory"][subject][0].get("inventory") is not None:
items = players[id]["inventory"][subject][0]["inventory"]
if len(items) > 0:
mud.send_message(id, 'You look in your {} and see:\r\n'.format(subject))
inv_list = []
print(items)
for name, i in items.items():
if len(i) > 1:
inv_list.append(str(len(i)) + " " + name + "s")
else:
inv_list.append(name)
mud.send_list(id, inv_list, "look")
else:
mud.send_message(id, 'You look in your {} and see nothing.'.format(subject))
else:
item = utils.load_object_from_file('inventory/' + subject + '.json')
mud.send_message(id, 'You check your inventory and see {}'.format(item.get('description')))
return True
if subject in room_monsters:
if len(room_monsters[subject]['active']) > 0:
monster_template = utils.load_object_from_file('mobs/{}.json'.format(subject))
if monster_template:
mud.send_message(id, 'You see {}'.format(monster_template.get('desc').lower()))
return True
mud.send_message(id, "That doesn't seem to be here.")
return
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 and players[id]["name"] != players[pid]["name"]:
# add their name to the list
playershere.append(players[pid]["name"])
# send player a message containing the list of players in the room
if len(playershere) > 0:
mud.send_message(id, "%boldPlayers here:%reset {}".format(", ".join(playershere)))
mud.send_message(id, "%boldObvious Exits:%reset ", line_ending='')
mud.send_list(id, room_data.get('exits'), "go")
# send player a message containing the list of exits from this room
if len(room_data.get('inventory')) > 0:
mud.send_message(id, "%boldItems here:%reset ", line_ending='')
inv_list = []
for name, i in room_data.get('inventory').items():
if len(i) > 1:
inv_list.append(str(len(i)) + " " + name + "s")
else:
inv_list.append(name)
mud.send_list(id, inv_list, "look")
# send player a message containing the list of players in the room
for mon_name, monster in room_monsters.items():
count = len(monster['active'])
if count > 1:
mud.send_message(id, "{} {} are here.".format(count, mon_name))
elif count > 0:
mud.send_message(id, "a {} is here.".format(mon_name))
look(id, mud, players, tokens)
del look
\ No newline at end of file
import utils
# for now actions can only be cast on the thing you are fighting since I don't have a good lexer to pull
# out targets. This also means that actions are offensive only since you cant cast on 'me'
# TODO: Add proper parsing so you can do: cast fireball on turkey or even better, cast fireball on the first turkey
def perform(id, params, players, mud, command):
if params == '':
params = command.strip()
else:
params = params.strip()
if len(params) == 0:
mud.send_message(id, 'What action do you want to perform?')
return True
action = players[id]['at'].get(params)
if not action:
mud.send_message(id, 'You do not appear to know the action %s.' % (params,))
return True
sta = players[id]['sta']
if sta > 0 and sta > action['cost']:
room_monsters = utils.load_object_from_file('rooms/{}_monsters.json'.format(players[id]['room']))
if not room_monsters:
mud.send_message(id, 'There is nothing here to perform that action on.')
for mon_name, monster in room_monsters.items():
monster_template = utils.load_object_from_file('mobs/{}.json'.format(mon_name))
if not monster_template:
continue
fighting = False
for active_monster_idx, active_monster in enumerate(monster['active']):
if active_monster['action'] == "attack" and active_monster['target'] == players[id]['name']:
fighting = True
att, sta = utils.calc_att(mud, id, [], sta, action)
players[id]['sta'] = sta
active_monster['hp'] -= att
# don't let them off without saving cheating sons of bees
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
room_monsters[mon_name]['active'][active_monster_idx] = active_monster
if not fighting:
mud.send_message(id, 'You are not currently in combat')
return True
utils.save_object_to_file(room_monsters, 'rooms/{}_monsters.json'.format(players[id]['room']))
else:
mud.send_message(id, 'You do not have enough stamina to perform that action.')
if command is None and cmd is not None:
command = cmd
perform(id, params.strip(), players, mud, command)
del perform
\ 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)
del prompt
\ No newline at end of file
def put(id, tokens, players, mud):
if len(tokens) == 0:
mud.send_message(id, 'What do you want to put and where do you want to put it?')
return True
subject = tokens[0]
if 'in' == tokens[1]:
del tokens[1]
dest = tokens[1]
room_name = players[id]["room"]
room_data = utils.load_object_from_file('rooms/' + room_name + '.json')
if subject in players[id]['inventory']:
if dest in players[id]['inventory'] or dest in room_data['inventory']:
if dest in room_data['inventory']:
if len(room_data['inventory'][dest][0]["inventory"]) == 0 and not room_data['inventory'][dest][0]["inventory"].get(subject):
room_data['inventory'][dest][0]["inventory"][subject] = [players[id]['inventory'][subject].pop()]
else:
room_data['inventory'][dest][0]["inventory"][subject].append(players[id]['inventory'][subject].pop())
elif dest in players[id]['inventory']:
#print(players[id]['inventory'][dest][0]["inventory"])
print(players[id]['inventory'][dest][0]["inventory"].get(subject))
if len(players[id]['inventory'][dest][0]["inventory"]) == 0 and not players[id]['inventory'][dest][0]["inventory"].get(subject):
players[id]['inventory'][dest][0]["inventory"][subject] = [players[id]['inventory'][subject].pop()]
else:
players[id]['inventory'][dest][0]["inventory"][subject].append(players[id]['inventory'][subject].pop())
if len(players[id]['inventory'][tokens[0]]) <= 0:
del players[id]['inventory'][tokens[0]]
utils.save_object_to_file(room_data, 'rooms/' + room_name + '.json')
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, "{} put a {} in a {}.".format(players[id]["name"], subject, dest))
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
else:
mud.send_message(id, 'You cannot put {} in {} since it is not here.'.format(subject, dest))
else:
mud.send_message(id, 'You do not have {} in your inventory.'.format(subject))
put(id, tokens, players, mud)
del put
\ 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)
del quit
\ No newline at end of file
def remove(id, players, tokens, mud):
if len(tokens) == 0:
mud.send_message(id, 'What do you want to stop wearing?')
else:
for item, item_list in players[id]['equipment'].items():
if isinstance(item_list, list):
for idx, li in enumerate(item_list):
print(li)
if li == tokens[0]:
item_list[idx] = None
if tokens[0] in players[id]['inventory']:
players[id]['inventory'][tokens[0]].append({"expries": 0})
else:
players[id]['inventory'][tokens[0]] = [{"expries": 0}]
mud.send_message(id, 'You remove the {}.'.format(tokens[0]))
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
return
elif item_list == tokens[0]:
players[id]['equipment'][item] = None
if tokens[0] in players[id]['inventory']:
players[id]['inventory'][tokens[0]].append({"expries": 0})
else:
players[id]['inventory'][tokens[0]] = [{"expries": 0}]
mud.send_message(id, 'You remove the {}.'.format(tokens[0]))
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
return
if tokens[0] == players[id]['weapon']:
if tokens[0] in players[id]['inventory']:
players[id]['inventory'][tokens[0]].append({"expries": 0})
else:
players[id]['inventory'][tokens[0]] = [{"expries": 0}]
mud.send_message(id, 'You unwield the {}.'.format(tokens[0]))
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
return
mud.send_message(id, 'You are not wearing a {}.'.format(tokens[0]))
# else:
# gear = utils.load_object_from_file('inventory/' + tokens[0] + '.json')
# if gear["type"] == "weapon":
# mud.send_message(id, 'That is a weapon and must be "wield".'.format(tokens[0]))
# elif gear["type"] != "armor":
# mud.send_message(id, 'That cannot be worn.'.format(tokens[0]))
# else:
# players[id]["equipment"][gear['loc']] = tokens[0]
# mud.send_message(id, 'You wear the {} on your {}.'.format(tokens[0], gear['loc']))
# if len(players[id]["inventory"][tokens[0]]) == 0:
# del players[id]["inventory"][tokens[0]]
# else:
# players[id]["inventory"][tokens[0]].pop()
# utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
remove(id, players, tokens, mud)
del remove
\ 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")
return True
save(id, players, mud)
del save
\ 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)
del say
\ No newline at end of file
def score(id, players, mud):
from math import floor
mud.send_message(id, " %green+----------------------------=Score=---------------------------+", nowrap=True)
hp = str("%d/%d" % (floor(players[id]['hp']), floor(players[id]['maxhp']))).center(12, ' ')
mp = str("%d/%d" % (floor(players[id]['mp']), floor(players[id]['maxmp']))).center(12, ' ')
sta = str("%d/%d" % (floor(players[id]['sta']), floor(players[id]['maxsta']))).center(12, ' ')
mud.send_message(id, " %%green|%%reset%%bold%%white%s%%reset%%green|" % (players[id]["name"].center(62),), nowrap=True)
mud.send_message(id, " %green+--------------------------------------------------------------+", nowrap=True)
mud.send_message(id, " %%green|%%reset %%cyanHP:%%reset %%white[%s]%%reset %%green|%%reset %%cyanMP:%%reset %%white[%s]%%reset %%green|%%reset %%cyanST:%%reset %%white[%s]%%reset %%green|%%reset" % (hp, mp, sta), nowrap=True)
# output = """
# --------------------------------------------
# HP: {hp} Max HP: {maxhp}
# MP: {mp} Max MP: {maxmp}
# Sta: {sta} Max Sta: {maxsta}
# Experience: {exp}
# Skills:""".format(hp=floor(players[id]['hp']),
# mp=floor(players[id]['mp']),
# maxhp=floor(players[id]['maxhp']),
# maxmp=floor(players[id]['maxmp']),
# sta=floor(players[id]['sta']),
# maxsta=floor(players[id]['maxsta']),
# exp=0)
# mud.send_message(id, output)
mud.send_message(id, " %green+---------------------------=Skills=---------------------------+", nowrap=True)
skills = ["skillasdfasdfasdfasdf", "skill 2 sdfg sdfg", "Skill 3 asdf ewrewwr"]
for skill in skills:
mud.send_message(id, " %%green|%%reset %s%%green|%%reset" % (skill.ljust(61),), nowrap=True)
mud.send_message(id, " %green+--------------------------------------------------------------+", nowrap=True)
score(id, players, mud)
del score
\ No newline at end of file
def spells(id, players, mud):
mud.send_message(id, '\r\n-Spell-----------=Spells=-----------Cost-\r\n')
for name, spell in players[id]['sp'].items():
mud.send_message(id, '{} {}'.format("%-37s" % name, spell['cost']))
mud.send_message(id, '\r\n-----------------------------------------\r\n')
mud.send_message(id, 'For more detail on a specific spell use "help <spell>"')
spells(id, players, mud)
del spells
\ 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)
del whisper
\ No newline at end of file
def who(id, players, mud):
mud.send_message(id, "")
mud.send_message(id, "-------- {} Players Currently Online --------".format(len(players)))
for pid, player in players.items():
if player["name"] is None:
continue
mud.send_message(id, " " + player["name"])
mud.send_message(id, "---------------------------------------------".format(len(players)))
mud.send_message(id, "")
who(id, players, mud)
del who
\ No newline at end of file
def wield(id, players, tokens, mud):
if len(tokens) == 0:
mud.send_message(id, " %greenYou are currently wielding: %reset%bold%white{}".format(players[id]['weapon']))
else:
if tokens[0] not in players[id]["inventory"]:
mud.send_message(id, 'You do not have {} in your inventory.'.format(tokens[0]))
else:
gear = utils.load_object_from_file('inventory/' + tokens[0] + '.json')
if gear["type"] == "armor":
mud.send_message(id, 'That is armor and must be "equip".')
elif gear["type"] != "weapon":
mud.send_message(id, 'That cannot be wielded.')
else:
players[id]["weapon"] = tokens[0]
mud.send_message(id, 'You wield the {}!'.format(tokens[0]))
players[id]["inventory"][tokens[0]].pop()
if len(players[id]["inventory"][tokens[0]]) == 0:
del players[id]["inventory"][tokens[0]]
utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
wield(id, players, tokens, mud)
del wield
\ No newline at end of file
......@@ -299,9 +299,12 @@ class MudServer(object):
self.send_message(clid, ', '.join(list_items))
def gmcp_message(self, clid, message):
byte_data = bytearray([self._TN_IAC, self._TN_SUB_START, self._GMCP])
byte_data.extend(message.encode())
byte_data.extend([self._TN_IAC, self._TN_SUB_END])
array = [self._TN_IAC, self._TN_SUB_START, self._GMCP]
for char in message:
array.append(ord(char))
array.append(self._TN_IAC)
array.append(self._TN_SUB_END)
byte_data = bytearray(array)
print("SENDING GMCP")
print(byte_data)
......@@ -309,7 +312,10 @@ class MudServer(object):
client_socket.sendall(byte_data)
def mxp_secure(self, clid, message, mxp_code="1"):
bytes_to_send = bytearray("\x1b[{}z{}\x1b[3z\r\n".format(mxp_code, message), 'utf-8')
if 'esp' in sys.platform:
bytes_to_send = bytearray("\x1b[{}z{}\x1b[3z\r\n".format(mxp_code, message))
else:
bytes_to_send = bytearray("\x1b[{}z{}\x1b[3z\r\n".format(mxp_code, message), 'utf-8')
client_socket = self._clients[clid].socket
client_socket.sendall(bytes_to_send)
......
{"name": "test", "password": "6c76899eb15393064b4f4db94805e5862232920b", "room": "town/tavern", "equipment": {"finger": [null, null], "hand": [null, null], "arm": [null, null], "leg": [null, null], "foot": [null, null], "head": null, "neck": null, "back": null, "body": null, "waist": null}, "inventory": {"bag": [{"expires": 0, "inventory": {"shirt": [{"expires": 0}]}}]}, "prompt": "hp %hp mp %mp> ", "aliases": {}, "hp": 100, "mp": 10, "maxhp": 100, "maxmp": 10, "maxsta": 10, "sta": 10, "aa": "1d2", "mpr": 0.25, "star": 0.4, "weapon": null, "sp": {}, "at": {"kick": {"cost": 5, "dmg": "2d4", "desc": "You unleash a powerful kick"}}}
\ No newline at end of file
{"name": "test", "password": "6c76899eb15393064b4f4db94805e5862232920b", "room": "town/room001", "equipment": {"finger": [null, null], "hand": [null, null], "arm": [null, null], "leg": [null, null], "foot": [null, null], "head": null, "neck": null, "back": null, "body": null, "waist": null}, "inventory": {"bag": [{"expires": 0, "inventory": {"shirt": [{"expires": 0}]}}]}, "prompt": "hp %hp mp %mp> ", "aliases": {}, "hp": 94, "mp": 10, "maxhp": 100, "maxmp": 10, "maxsta": 10, "sta": 0.8000000000000004, "aa": "1d2", "mpr": 0.25, "star": 0.4, "weapon": null, "sp": {}, "at": {"kick": {"cost": 5, "dmg": "2d4", "desc": "You unleash a powerful kick"}}}
\ No newline at end of file
......
......@@ -11,7 +11,7 @@ IPADDRESS = '192.168.1.189'
BAUDRATE = 115200
folders = ['help', 'rooms', 'rooms/town', 'rooms/wilderness', 'inventory', 'commands', 'mobs']
folders = ['help', 'rooms', 'rooms/town', 'rooms/wilderness', 'inventory', 'mobs']
files = [
"welcome.txt",
......
......@@ -2,6 +2,7 @@ import os
import io
import serial
import time
import sys
######################################
# EDIT THIS TO MATCH YOUR SETTINGS
......@@ -21,6 +22,11 @@ baked_files = [
"utils.py"
]
def countdown(t):
for x in reversed(range(t)):
sys.stdout.write('\r{} '.format(x + 1))
time.sleep(1)
print('\r\n')
def run_command(sio, command, expected='>>>'):
sio.write("{}\n".format(command))
......@@ -47,7 +53,7 @@ os.system('esptool --port {} erase_flash'.format(PORT))
os.system('esptool --port {} --baud 460800 write_flash --flash_size=detect 0 image/firmware-combined.bin'.format(PORT))
print("Sleeping 10 seconds for reboot")
time.sleep(10)
countdown(10)
with open('releasepw.conf', 'r', encoding='utf-8') as f:
WEBREPL_PASS = f.read()
......@@ -70,6 +76,9 @@ with serial.Serial(PORT, BAUDRATE, timeout=1) as ser:
print('Connecting to {}'.format(ESSID))
run_command(sio, "sta_if.connect('{}', '{}')".format(ESSID, WIFI_PASSWORD))
print('Waiting 15 seconds for network to connect.\r\n')
countdown(15)
waiting_for_ip = True
while waiting_for_ip:
try:
......@@ -87,7 +96,8 @@ with serial.Serial(PORT, BAUDRATE, timeout=1) as ser:
run_command(sio, 'import machine;machine.reset()')
print('Starting the squishy mud release')
time.sleep(5)
print('Starting the squishy mud release\r\n')
countdown(5)
# Run the rest of the mud setup
import release
\ No newline at end of file
......
{
"num": 1002,
"coords": { "id": 1000, "x": 1, "y": 0, "z": 0 },
"look_items": {
"wooden,oak,plank": "An old solid oak plank that has a large number of chips and drink marks.",
"barrel,barrels": "The old barrels bands are thick with oxidation and stained with the purple of spilled wine.",
"bar": "The bar is a long wooden plank thrown over roughly hewn barrels."
},
"description": "The back of the bar gives a full view of the tavern. The bar top is a large wooden plank thrown across some barrels.",
"inventory": {
"candle": [{
"age": 0
}]
},
"exits": {
"tavern": ["town/tavern", 1001]
},
"title": "Behind the bar",
"zone": "town"
}
\ No newline at end of file
{"num": 1002, "coords": {"id": 1000, "x": 1, "y": 0, "z": 0}, "look_items": {"wooden,oak,plank": "An old solid oak plank that has a large number of chips and drink marks.", "barrel,barrels": "The old barrels bands are thick with oxidation and stained with the purple of spilled wine.", "bar": "The bar is a long wooden plank thrown over roughly hewn barrels."}, "description": "The back of the bar gives a full view of the tavern. The bar top is a large wooden plank thrown across some barrels.", "inventory": {"candle": [{"age": 0}]}, "exits": {"tavern": ["town/tavern", 1001]}, "title": "Behind the bar", "zone": "town"}
\ No newline at end of file
......
{"cricket": {"max": 1, "active": [{"mp": 10, "maxhp": 14, "hp": 14, "sta": 10, "maxmp": 10, "target": "", "action": "attack", "maxsta": 10}]}}
\ No newline at end of file
{"cricket": {"max": 1, "active": []}}
\ No newline at end of file
......