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
1 def actions(id, players, mud):
2 mud.send_message(id, '\r\n-Action----------=Actions=-----------Cost-\r\n')
3 for name, action in players[id]['at'].items():
4 mud.send_message(id, '{} {}'.format("%-37s" % name, action['cost']))
5 mud.send_message(id, '\r\n------------------------------------------\r\n')
6 mud.send_message(id, 'For more detail on a specific action use "help <action>"')
7
8
9 actions(id, players, mud)
10 del actions
...\ No newline at end of file ...\ No newline at end of file
1 import utils
2
3 # for now spells can only be cast on the thing you are fighting since I don't have a good lexer to pull
4 # out targets. This also means that spells are offensive only since you cant cast on 'me'
5 # TODO: Add proper parsing so you can do: cast fireball on turkey or even better, cast fireball on the first turkey
6 def cast(id, params, players, mud, command):
7 if params == '':
8 params = command.strip()
9 else:
10 params = params.strip()
11 if len(params) == 0:
12 mud.send_message(id, 'What spell do you want to cast?')
13 return True
14 spell = players[id]['sp'].get(params)
15 if not spell:
16 mud.send_message(id, 'You do not appear to know how to cast %s.' % (params,))
17 return True
18 mp = players[id]['mp']
19 if mp > 0 and mp > spell['cost']:
20 room_monsters = utils.load_object_from_file('rooms/{}_monsters.json'.format(players[id]['room']))
21 if not room_monsters:
22 mud.send_message(id, 'There is nothing here to cast that spell on.')
23 for mon_name, monster in room_monsters.items():
24 monster_template = utils.load_object_from_file('mobs/{}.json'.format(mon_name))
25 if not monster_template:
26 continue
27 fighting = False
28 for active_monster_idx, active_monster in enumerate(monster['active']):
29 if active_monster['action'] == "attack" and active_monster['target'] == players[id]['name']:
30 fighting = True
31 att, mp = utils.calc_att(mud, id, [], mp, spell)
32
33 players[id]['mp'] = mp
34 active_monster['hp'] -= att
35 # don't let them off without saving cheating sons of bees
36 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
37 room_monsters[mon_name]['active'][active_monster_idx] = active_monster
38 if not fighting:
39 mud.send_message(id, 'You are not currently in combat')
40 return True
41
42 utils.save_object_to_file(room_monsters, 'rooms/{}_monsters.json'.format(players[id]['room']))
43 else:
44 mud.send_message(id, 'You do not have enough mana to cast that spell.')
45
46 if command is None and cmd is not None:
47 command = cmd
48 cast(id, params.strip(), players, mud, command)
49 del cast
...\ No newline at end of file ...\ No newline at end of file
1 def drop(id, tokens, players, mud):
2 room_name = players[id]["room"]
3 if len(tokens) == 0:
4 mud.send_message(id, 'What do you want to drop?')
5 return True
6 room_data = utils.load_object_from_file('rooms/' + room_name + '.json')
7 if tokens[0] in players[id]['inventory']:
8 if tokens[0] in room_data['inventory']:
9 room_data['inventory'][tokens[0]].append(players[id]['inventory'][tokens[0]].pop())
10 else:
11 room_data['inventory'][tokens[0]] = [players[id]['inventory'][tokens[0]].pop()]
12 if len(players[id]['inventory'][tokens[0]]) <= 0:
13 del players[id]['inventory'][tokens[0]]
14
15 utils.save_object_to_file(room_data, 'rooms/' + room_name + '.json')
16 for pid, pl in players.items():
17 # if they're in the same room as the player
18 if players[pid]["room"] == players[id]["room"]:
19 # send them a message telling them what the player said
20 mud.send_message(pid, "{} dropped a {}.".format(
21 players[id]["name"], tokens[0]))
22 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
23 else:
24 mud.send_message(id, 'You do not have {} in your inventory.'.format(tokens[0]))
25
26 drop(id, tokens, players, mud)
27 del drop
...\ No newline at end of file ...\ No newline at end of file
1 def emote(id, params, players, mud):
2 # go through every player in the game
3 for pid, pl in players.items():
4 # if they're in the same room as the player
5 if players[pid]["room"] == players[id]["room"]:
6 # send them a message telling them what the player said
7 mud.send_message(pid, "{} {}".format(players[id]["name"], params))
8
9 emote(id, params, players, mud)
10 del emote
...\ No newline at end of file ...\ No newline at end of file
1 def equip(id, players, tokens, mud):
2 if len(tokens) == 0:
3 mud.send_message(id, " %green+-Item---------------------=Equipment=------------------Loc----+", nowrap=True)
4 if players[id].get('equipment'):
5 for item, item_list in players[id]['equipment'].items():
6 if isinstance(item_list, list):
7 vals = [val for val in item_list if val]
8 if len(vals) > 0:
9 mud.send_message(id, ' %green|%reset {} {} %green|'.format("%-51s" % ', '.join(vals), item.rjust(8, ' ')))
10 else:
11 mud.send_message(id, ' %green|%reset {} {} %green|'.format("%-51s" % 'None', item.rjust(8, ' ')))
12 else:
13 mud.send_message(id, ' %green|%reset {} {} %green|'.format("%-51s" % item_list or "None", item.rjust(8, ' ')))
14 mud.send_message(id, ' %green|%reset {} {} %green|'.format("%-51s" % players[id]['weapon'] or "None", 'weapon'.rjust(8, ' ')))
15 mud.send_message(id, " %green+--------------------------------------------------------------+", nowrap=True)
16 else:
17 if tokens[0] not in players[id]["inventory"]:
18 mud.send_message(id, 'You do not have {} in your inventory.'.format(tokens[0]))
19 else:
20 gear = utils.load_object_from_file('inventory/' + tokens[0] + '.json')
21 if gear["type"] == "weapon":
22 mud.send_message(id, 'That is a weapon and must be "wield".')
23 elif gear["type"] != "armor":
24 mud.send_message(id, 'That cannot be worn.')
25 else:
26 players[id]["equipment"][gear['loc']] = tokens[0]
27 mud.send_message(id, 'You wear the {} on your {}.'.format(tokens[0], gear['loc']))
28 players[id]["inventory"][tokens[0]].pop()
29 if len(players[id]["inventory"][tokens[0]]) == 0:
30 del players[id]["inventory"][tokens[0]]
31
32 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
33
34
35 equip(id, players, tokens, mud)
36 del equip
...\ No newline at end of file ...\ No newline at end of file
1 def get(id, params, tokens, players, mud):
2 room_name = players[id]["room"]
3 if len(tokens) == 0:
4 mud.send_message(id, 'What do you want to get?')
5 return True
6
7 room_data = utils.load_object_from_file('rooms/' + room_name + '.json')
8
9 container = None
10 if any(x in params for x in ['from', 'out of']):
11 if 'out of' in params:
12 container = params.split('out of')[1].strip()
13 else:
14 container = params.split('from')[1].strip()
15 if room_data["inventory"].get(container) is None and players[id]["inventory"].get(container) is None:
16 mud.send_message(id, 'You do not see the container {} here.'.format(container))
17 return True
18
19 if container:
20 found = False
21 if container in players[id]["inventory"]:
22 if tokens[0] in players[id]['inventory'][container][0]['inventory']:
23 found = True
24 if tokens[0] in players[id]['inventory']:
25 print(players[id]['inventory'][container][0]['inventory'][tokens[0]])
26 players[id]['inventory'][tokens[0]].append(players[id]['inventory'][container][0]['inventory'][tokens[0]].pop())
27 else:
28 players[id]['inventory'][tokens[0]] = [players[id]['inventory'][container][0]['inventory'][tokens[0]].pop()]
29 if len(players[id]['inventory'][container][0]['inventory'][tokens[0]]) <= 0:
30 del players[id]['inventory'][container][0]['inventory'][tokens[0]]
31 elif container in room_data["inventory"]:
32 if tokens[0] in room_data['inventory'][container][0]['inventory']:
33 found = True
34 if tokens[0] in players[id]['inventory']:
35 players[id]['inventory'][tokens[0]].append(room_data['inventory'][container][0]['inventory'][tokens[0]].pop())
36 else:
37 players[id]['inventory'][tokens[0]] = [room_data['inventory'][container][0]['inventory'][tokens[0]].pop()]
38 if len(room_data['inventory'][container][0]['inventory'][tokens[0]]) <= 0:
39 del room_data['inventory'][container][0]['inventory'][tokens[0]]
40 if not found:
41 mud.send_message(id, 'You do not see a {} in the {}.'.format(tokens[0], container))
42 else:
43 for pid, pl in players.items():
44 # if they're in the same room as the player
45 if players[pid]["room"] == players[id]["room"]:
46 # send them a message telling them what the player said
47 mud.send_message(pid, "{} picked up a {} from a {}.".format(players[id]["name"], tokens[0], container))
48 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
49 utils.save_object_to_file(room_data, 'rooms/' + room_name + '.json')
50 return True
51 else:
52 if tokens[0] in room_data.get('inventory'):
53 if tokens[0] in players[id]['inventory']:
54 players[id]['inventory'][tokens[0]].append(room_data['inventory'][tokens[0]].pop())
55 else:
56 players[id]['inventory'][tokens[0]] = [room_data['inventory'][tokens[0]].pop()]
57
58 if len(room_data['inventory'][tokens[0]]) <= 0:
59 del room_data['inventory'][tokens[0]]
60 for pid, pl in players.items():
61 # if they're in the same room as the player
62 if players[pid]["room"] == players[id]["room"]:
63 # send them a message telling them what the player said
64 mud.send_message(pid, "{} picked up a {}.".format(
65 players[id]["name"], tokens[0]))
66 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
67 utils.save_object_to_file(room_data, 'rooms/' + room_name + '.json')
68 else:
69 mud.send_message(id, 'There is no {} here to get.'.format(tokens[0]))
70
71 get(id, params.lower().strip(), tokens, players, mud)
...\ No newline at end of file ...\ No newline at end of file
1 def go(id, params, players, mud, tokens, command):
2 # store the exit name
3 if params == '':
4 params = command.strip().lower()
5 else:
6 params = params.strip().lower()
7
8 room_data = utils.load_object_from_file('rooms/' + players[id]["room"] + '.json')
9
10 # if the specified exit is found in the room's exits list
11 exits = room_data['exits']
12
13 if params in exits:
14 # go through all the players in the game
15 for pid, pl in players.items():
16 # if player is in the same room and isn't the player
17 # sending the command
18 if players[pid]["room"] == players[id]["room"] \
19 and pid != id:
20 # send them a message telling them that the player
21 # left the room
22 mud.send_message(pid, "{} left via exit '{}'".format(
23 players[id]["name"], params))
24
25 # update the player's current room to the one the exit leads to
26
27 if exits[params] == None:
28 mud.send_message(id, "An invisible force prevents you from going in that direction.")
29 return None
30 else:
31 new_room = utils.load_object_from_file('rooms/' + exits[params][0] + '.json')
32 if not new_room:
33 mud.send_message(id, "An invisible force prevents you from going in that direction.")
34 return None
35 else:
36 players[id]["room"] = exits[params][0]
37 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
38 mud.send_message(id, "You arrive at '{}'".format(new_room['title']))
39
40 # go through all the players in the game
41 for pid, pl in players.items():
42 # if player is in the same (new) room and isn't the player
43 # sending the command
44 if players[pid]["room"] == players[id]["room"] \
45 and pid != id:
46 # send them a message telling them that the player
47 # entered the room
48 mud.send_message(pid,
49 "{} arrived via exit '{}'".format(
50 players[id]["name"], params))
51
52 # send the player a message telling them where they are now
53 tokens = []
54 return 'look'
55 # the specified exit wasn't found in the current room
56 else:
57 # send back an 'unknown exit' message
58 mud.send_message(id, "Unknown exit '{}'".format(params))
59 if command is None and cmd is not None:
60 command = cmd
61 next_command = go(id, params, players, mud, tokens, command)
62 del go
...\ No newline at end of file ...\ No newline at end of file
1 def help(id, tokens, mud):
2 if len(tokens) > 0:
3 filename = 'help/' + tokens[0] + '.txt'
4 else:
5 filename = 'help/help.txt'
6 try:
7 with open(filename, 'r', encoding='utf-8') as f:
8 for line in f:
9 mud.send_message(id, line, '\r')
10 mud.send_message(id, '')
11 except:
12 mud.send_message(id, 'No help topics available for \"{}\". A list\r\n of all commands is available at: help index'.format(tokens[0]))
13
14 help(id, tokens, mud)
15 del help
...\ No newline at end of file ...\ No newline at end of file
1 def inventory(id, players, mud):
2 mud.send_message(id, " %green+-Item---------------------=Inventory=--------------------Qty--+", nowrap=True)
3 for item, item_list in players[id]['inventory'].items():
4 mud.send_message(id, ' %green|%reset {} {} %green|'.format("%-55s" % item, str(len(item_list)).center(4, ' ')))
5 mud.send_message(id, " %green+--------------------------------------------------------------+", nowrap=True)
6
7 inventory(id, players, mud)
8 del inventory
...\ No newline at end of file ...\ No newline at end of file
1
2 def kill(id, params, players, mud):
3 if len(params) == 0:
4 mud.send_message(id, 'What did you want to attack?')
5 return True
6 room_monsters = utils.load_object_from_file('rooms/{}_monsters.json'.format(players[id]['room']))
7 for mon_name, monster in room_monsters.items():
8 if mon_name in params.lower():
9 if len(monster['active']) > 0:
10 if monster['active'][0]['target'] == players[id]['name']:
11 mud.send_message(id, 'You are already engaged in combat with that target.')
12 return True
13 else:
14 room_monsters[mon_name]['active'][0]['target'] = players[id]['name']
15 mud.send_message(id, 'You attack the {}.'.format(mon_name), color=['red', 'bold'])
16 utils.save_object_to_file(room_monsters, 'rooms/{}_monsters.json'.format(players[id]['room']))
17 return True
18 if params[0] in 'aeiou':
19 mud.send_message(id, 'You do not see an {} here.'.format(params))
20 else:
21 mud.send_message(id, 'You do not see a {} here.'.format(params))
22
23 kill(id, params, players, mud)
24 del kill
...\ No newline at end of file ...\ No newline at end of file
1 def look(id, mud, players, tokens):
2 room_name = players[id]["room"]
3 room_data = utils.load_object_from_file('rooms/' + room_name + '.json')
4 room_monsters = utils.load_object_from_file('rooms/' + room_name + '_monsters.json')
5 mud.send_message(id, "")
6 if len(tokens) > 0 and tokens[0] == 'at':
7 del tokens[0]
8 container = False
9 if len(tokens) > 0 and tokens[0] == 'in':
10 del tokens[0]
11 container = True
12 if len(tokens) == 0:
13 exits = {}
14 for exit_name, exit in room_data.get('exits').items():
15 exits[exit_name] = exit[1]
16 print(room_data)
17 # clid, name, zone, terrain, description, exits, coords
18 mud.send_room(id, room_data.get('num'), room_data.get('title'), room_data.get('zone'),
19 'City', '', exits, room_data.get('coords'))
20 mud.send_message(id, room_data.get('title'), color=['bold', 'green'])
21 mud.send_message(id, room_data.get('description'), line_ending='\r\n\r\n', color='green')
22 else:
23 subject = tokens[0]
24 items = room_data.get('look_items')
25 for item in items:
26 if subject in item:
27 mud.send_message(id, items[item])
28 return True
29 if subject in room_data['inventory']:
30 if container and room_data["inventory"][subject][0].get("inventory") is not None:
31 items = room_data["inventory"][subject][0]["inventory"]
32 if len(items) > 0:
33 mud.send_message(id, 'You look in the {} and see:\r\n'.format(subject))
34 inv_list = []
35 for name, i in items.items():
36 if len(i) > 1:
37 inv_list.append(str(len(i)) + " " + name + "s")
38 else:
39 inv_list.append(name)
40 mud.send_list(id, inv_list, "look")
41
42 else:
43 mud.send_message(id, 'You look in the {} and see nothing.'.format(subject))
44 else:
45 item = utils.load_object_from_file('inventory/' + subject + '.json')
46 mud.send_message(id, 'You see {}'.format(item.get('description')))
47 return True
48 if subject in players[id]['inventory']:
49 if container and players[id]["inventory"][subject][0].get("inventory") is not None:
50 items = players[id]["inventory"][subject][0]["inventory"]
51 if len(items) > 0:
52 mud.send_message(id, 'You look in your {} and see:\r\n'.format(subject))
53 inv_list = []
54 print(items)
55 for name, i in items.items():
56 if len(i) > 1:
57 inv_list.append(str(len(i)) + " " + name + "s")
58 else:
59 inv_list.append(name)
60 mud.send_list(id, inv_list, "look")
61 else:
62 mud.send_message(id, 'You look in your {} and see nothing.'.format(subject))
63 else:
64 item = utils.load_object_from_file('inventory/' + subject + '.json')
65 mud.send_message(id, 'You check your inventory and see {}'.format(item.get('description')))
66 return True
67 if subject in room_monsters:
68 if len(room_monsters[subject]['active']) > 0:
69 monster_template = utils.load_object_from_file('mobs/{}.json'.format(subject))
70 if monster_template:
71 mud.send_message(id, 'You see {}'.format(monster_template.get('desc').lower()))
72 return True
73 mud.send_message(id, "That doesn't seem to be here.")
74 return
75
76 playershere = []
77 # go through every player in the game
78 for pid, pl in players.items():
79 # if they're in the same room as the player
80 if players[pid]["room"] == players[id]["room"]:
81 # ... and they have a name to be shown
82 if players[pid]["name"] is not None and players[id]["name"] != players[pid]["name"]:
83 # add their name to the list
84 playershere.append(players[pid]["name"])
85
86 # send player a message containing the list of players in the room
87 if len(playershere) > 0:
88 mud.send_message(id, "%boldPlayers here:%reset {}".format(", ".join(playershere)))
89
90 mud.send_message(id, "%boldObvious Exits:%reset ", line_ending='')
91 mud.send_list(id, room_data.get('exits'), "go")
92
93 # send player a message containing the list of exits from this room
94 if len(room_data.get('inventory')) > 0:
95 mud.send_message(id, "%boldItems here:%reset ", line_ending='')
96 inv_list = []
97 for name, i in room_data.get('inventory').items():
98 if len(i) > 1:
99 inv_list.append(str(len(i)) + " " + name + "s")
100 else:
101 inv_list.append(name)
102 mud.send_list(id, inv_list, "look")
103
104 # send player a message containing the list of players in the room
105 for mon_name, monster in room_monsters.items():
106 count = len(monster['active'])
107 if count > 1:
108 mud.send_message(id, "{} {} are here.".format(count, mon_name))
109 elif count > 0:
110 mud.send_message(id, "a {} is here.".format(mon_name))
111
112 look(id, mud, players, tokens)
113 del look
...\ No newline at end of file ...\ No newline at end of file
1 import utils
2
3 # for now actions can only be cast on the thing you are fighting since I don't have a good lexer to pull
4 # out targets. This also means that actions are offensive only since you cant cast on 'me'
5 # TODO: Add proper parsing so you can do: cast fireball on turkey or even better, cast fireball on the first turkey
6 def perform(id, params, players, mud, command):
7 if params == '':
8 params = command.strip()
9 else:
10 params = params.strip()
11 if len(params) == 0:
12 mud.send_message(id, 'What action do you want to perform?')
13 return True
14 action = players[id]['at'].get(params)
15 if not action:
16 mud.send_message(id, 'You do not appear to know the action %s.' % (params,))
17 return True
18 sta = players[id]['sta']
19 if sta > 0 and sta > action['cost']:
20 room_monsters = utils.load_object_from_file('rooms/{}_monsters.json'.format(players[id]['room']))
21 if not room_monsters:
22 mud.send_message(id, 'There is nothing here to perform that action on.')
23 for mon_name, monster in room_monsters.items():
24 monster_template = utils.load_object_from_file('mobs/{}.json'.format(mon_name))
25 if not monster_template:
26 continue
27 fighting = False
28 for active_monster_idx, active_monster in enumerate(monster['active']):
29 if active_monster['action'] == "attack" and active_monster['target'] == players[id]['name']:
30 fighting = True
31 att, sta = utils.calc_att(mud, id, [], sta, action)
32
33 players[id]['sta'] = sta
34 active_monster['hp'] -= att
35 # don't let them off without saving cheating sons of bees
36 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
37 room_monsters[mon_name]['active'][active_monster_idx] = active_monster
38 if not fighting:
39 mud.send_message(id, 'You are not currently in combat')
40 return True
41
42 utils.save_object_to_file(room_monsters, 'rooms/{}_monsters.json'.format(players[id]['room']))
43 else:
44 mud.send_message(id, 'You do not have enough stamina to perform that action.')
45
46 if command is None and cmd is not None:
47 command = cmd
48 perform(id, params.strip(), players, mud, command)
49 del perform
...\ No newline at end of file ...\ No newline at end of file
1 def prompt(id, tokens, params, players, mud):
2 if len(tokens) == 0:
3 mud.send_message(id, 'No prompt provided, no changes will be made.\r\nEx: prompt %hp>')
4
5 players[id]['prompt'] = params + ' '
6 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
7
8 prompt(id, tokens, params, players, mud)
9 del prompt
...\ No newline at end of file ...\ No newline at end of file
1 def put(id, tokens, players, mud):
2 if len(tokens) == 0:
3 mud.send_message(id, 'What do you want to put and where do you want to put it?')
4 return True
5 subject = tokens[0]
6 if 'in' == tokens[1]:
7 del tokens[1]
8 dest = tokens[1]
9
10 room_name = players[id]["room"]
11 room_data = utils.load_object_from_file('rooms/' + room_name + '.json')
12
13 if subject in players[id]['inventory']:
14 if dest in players[id]['inventory'] or dest in room_data['inventory']:
15
16 if dest in room_data['inventory']:
17 if len(room_data['inventory'][dest][0]["inventory"]) == 0 and not room_data['inventory'][dest][0]["inventory"].get(subject):
18 room_data['inventory'][dest][0]["inventory"][subject] = [players[id]['inventory'][subject].pop()]
19 else:
20 room_data['inventory'][dest][0]["inventory"][subject].append(players[id]['inventory'][subject].pop())
21 elif dest in players[id]['inventory']:
22 #print(players[id]['inventory'][dest][0]["inventory"])
23 print(players[id]['inventory'][dest][0]["inventory"].get(subject))
24 if len(players[id]['inventory'][dest][0]["inventory"]) == 0 and not players[id]['inventory'][dest][0]["inventory"].get(subject):
25 players[id]['inventory'][dest][0]["inventory"][subject] = [players[id]['inventory'][subject].pop()]
26 else:
27 players[id]['inventory'][dest][0]["inventory"][subject].append(players[id]['inventory'][subject].pop())
28 if len(players[id]['inventory'][tokens[0]]) <= 0:
29 del players[id]['inventory'][tokens[0]]
30
31 utils.save_object_to_file(room_data, 'rooms/' + room_name + '.json')
32 for pid, pl in players.items():
33 # if they're in the same room as the player
34 if players[pid]["room"] == players[id]["room"]:
35 # send them a message telling them what the player said
36 mud.send_message(pid, "{} put a {} in a {}.".format(players[id]["name"], subject, dest))
37 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
38 else:
39 mud.send_message(id, 'You cannot put {} in {} since it is not here.'.format(subject, dest))
40 else:
41 mud.send_message(id, 'You do not have {} in your inventory.'.format(subject))
42
43 put(id, tokens, players, mud)
44 del put
...\ No newline at end of file ...\ No newline at end of file
1 def quit(id, players, mud):
2 # send the player back the list of possible commands
3 mud.send_message(id, "Saving...")
4 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
5 mud.disconnect_player(id)
6
7 quit(id, players, mud)
8 del quit
...\ No newline at end of file ...\ No newline at end of file
1 def remove(id, players, tokens, mud):
2 if len(tokens) == 0:
3 mud.send_message(id, 'What do you want to stop wearing?')
4 else:
5 for item, item_list in players[id]['equipment'].items():
6 if isinstance(item_list, list):
7 for idx, li in enumerate(item_list):
8 print(li)
9 if li == tokens[0]:
10 item_list[idx] = None
11 if tokens[0] in players[id]['inventory']:
12 players[id]['inventory'][tokens[0]].append({"expries": 0})
13 else:
14 players[id]['inventory'][tokens[0]] = [{"expries": 0}]
15 mud.send_message(id, 'You remove the {}.'.format(tokens[0]))
16 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
17 return
18 elif item_list == tokens[0]:
19 players[id]['equipment'][item] = None
20 if tokens[0] in players[id]['inventory']:
21 players[id]['inventory'][tokens[0]].append({"expries": 0})
22 else:
23 players[id]['inventory'][tokens[0]] = [{"expries": 0}]
24 mud.send_message(id, 'You remove the {}.'.format(tokens[0]))
25 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
26 return
27
28 if tokens[0] == players[id]['weapon']:
29 if tokens[0] in players[id]['inventory']:
30 players[id]['inventory'][tokens[0]].append({"expries": 0})
31 else:
32 players[id]['inventory'][tokens[0]] = [{"expries": 0}]
33 mud.send_message(id, 'You unwield the {}.'.format(tokens[0]))
34 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
35 return
36
37 mud.send_message(id, 'You are not wearing a {}.'.format(tokens[0]))
38 # else:
39 # gear = utils.load_object_from_file('inventory/' + tokens[0] + '.json')
40 # if gear["type"] == "weapon":
41 # mud.send_message(id, 'That is a weapon and must be "wield".'.format(tokens[0]))
42 # elif gear["type"] != "armor":
43 # mud.send_message(id, 'That cannot be worn.'.format(tokens[0]))
44 # else:
45 # players[id]["equipment"][gear['loc']] = tokens[0]
46 # mud.send_message(id, 'You wear the {} on your {}.'.format(tokens[0], gear['loc']))
47 # if len(players[id]["inventory"][tokens[0]]) == 0:
48 # del players[id]["inventory"][tokens[0]]
49 # else:
50 # players[id]["inventory"][tokens[0]].pop()
51 # utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
52
53
54 remove(id, players, tokens, mud)
55 del remove
...\ No newline at end of file ...\ No newline at end of file
1 def save(id, players, mud):
2 # send the player back the list of possible commands
3 mud.send_message(id, "Saving...")
4 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
5 mud.send_message(id, "Save complete")
6 return True
7
8 save(id, players, mud)
9 del save
...\ No newline at end of file ...\ No newline at end of file
1 def say(id, params, players, mud):
2 # go through every player in the game
3 for pid, pl in players.items():
4 # if they're in the same room as the player
5 if players[pid]["room"] == players[id]["room"]:
6 # send them a message telling them what the player said
7 mud.send_message(pid, "{} says: {}".format(
8 players[id]["name"], params))
9 say(id, params, players, mud)
10 del say
...\ No newline at end of file ...\ No newline at end of file
1 def score(id, players, mud):
2 from math import floor
3
4 mud.send_message(id, " %green+----------------------------=Score=---------------------------+", nowrap=True)
5 hp = str("%d/%d" % (floor(players[id]['hp']), floor(players[id]['maxhp']))).center(12, ' ')
6 mp = str("%d/%d" % (floor(players[id]['mp']), floor(players[id]['maxmp']))).center(12, ' ')
7 sta = str("%d/%d" % (floor(players[id]['sta']), floor(players[id]['maxsta']))).center(12, ' ')
8
9 mud.send_message(id, " %%green|%%reset%%bold%%white%s%%reset%%green|" % (players[id]["name"].center(62),), nowrap=True)
10 mud.send_message(id, " %green+--------------------------------------------------------------+", nowrap=True)
11 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)
12
13
14 # output = """
15 # --------------------------------------------
16 # HP: {hp} Max HP: {maxhp}
17 # MP: {mp} Max MP: {maxmp}
18 # Sta: {sta} Max Sta: {maxsta}
19 # Experience: {exp}
20 # Skills:""".format(hp=floor(players[id]['hp']),
21 # mp=floor(players[id]['mp']),
22 # maxhp=floor(players[id]['maxhp']),
23 # maxmp=floor(players[id]['maxmp']),
24 # sta=floor(players[id]['sta']),
25 # maxsta=floor(players[id]['maxsta']),
26 # exp=0)
27 # mud.send_message(id, output)
28
29 mud.send_message(id, " %green+---------------------------=Skills=---------------------------+", nowrap=True)
30 skills = ["skillasdfasdfasdfasdf", "skill 2 sdfg sdfg", "Skill 3 asdf ewrewwr"]
31 for skill in skills:
32 mud.send_message(id, " %%green|%%reset %s%%green|%%reset" % (skill.ljust(61),), nowrap=True)
33
34 mud.send_message(id, " %green+--------------------------------------------------------------+", nowrap=True)
35
36
37
38 score(id, players, mud)
39 del score
...\ No newline at end of file ...\ No newline at end of file
1 def spells(id, players, mud):
2 mud.send_message(id, '\r\n-Spell-----------=Spells=-----------Cost-\r\n')
3 for name, spell in players[id]['sp'].items():
4 mud.send_message(id, '{} {}'.format("%-37s" % name, spell['cost']))
5 mud.send_message(id, '\r\n-----------------------------------------\r\n')
6 mud.send_message(id, 'For more detail on a specific spell use "help <spell>"')
7
8
9 spells(id, players, mud)
10 del spells
...\ No newline at end of file ...\ No newline at end of file
1 def whisper(id, tokens, players, mud):
2 # go through every player in the game
3 for pid, pl in players.items():
4 # if they're in the same room as the player
5 if players[pid]["name"] == tokens[0]:
6 # send them a message telling them what the player said
7 mud.send_message(pid, "{} whispers: {}".format(
8 players[id]["name"], ' '.join(tokens[1:])))
9
10 whisper(id, tokens, players, mud)
11 del whisper
...\ No newline at end of file ...\ No newline at end of file
1 def who(id, players, mud):
2 mud.send_message(id, "")
3 mud.send_message(id, "-------- {} Players Currently Online --------".format(len(players)))
4 for pid, player in players.items():
5 if player["name"] is None:
6 continue
7 mud.send_message(id, " " + player["name"])
8 mud.send_message(id, "---------------------------------------------".format(len(players)))
9 mud.send_message(id, "")
10 who(id, players, mud)
11 del who
...\ No newline at end of file ...\ No newline at end of file
1 def wield(id, players, tokens, mud):
2 if len(tokens) == 0:
3 mud.send_message(id, " %greenYou are currently wielding: %reset%bold%white{}".format(players[id]['weapon']))
4 else:
5 if tokens[0] not in players[id]["inventory"]:
6 mud.send_message(id, 'You do not have {} in your inventory.'.format(tokens[0]))
7 else:
8 gear = utils.load_object_from_file('inventory/' + tokens[0] + '.json')
9 if gear["type"] == "armor":
10 mud.send_message(id, 'That is armor and must be "equip".')
11 elif gear["type"] != "weapon":
12 mud.send_message(id, 'That cannot be wielded.')
13 else:
14 players[id]["weapon"] = tokens[0]
15 mud.send_message(id, 'You wield the {}!'.format(tokens[0]))
16 players[id]["inventory"][tokens[0]].pop()
17 if len(players[id]["inventory"][tokens[0]]) == 0:
18 del players[id]["inventory"][tokens[0]]
19
20 utils.save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
21
22
23 wield(id, players, tokens, mud)
24 del wield
...\ No newline at end of file ...\ No newline at end of file
...@@ -299,9 +299,12 @@ class MudServer(object): ...@@ -299,9 +299,12 @@ class MudServer(object):
299 self.send_message(clid, ', '.join(list_items)) 299 self.send_message(clid, ', '.join(list_items))
300 300
301 def gmcp_message(self, clid, message): 301 def gmcp_message(self, clid, message):
302 byte_data = bytearray([self._TN_IAC, self._TN_SUB_START, self._GMCP]) 302 array = [self._TN_IAC, self._TN_SUB_START, self._GMCP]
303 byte_data.extend(message.encode()) 303 for char in message:
304 byte_data.extend([self._TN_IAC, self._TN_SUB_END]) 304 array.append(ord(char))
305 array.append(self._TN_IAC)
306 array.append(self._TN_SUB_END)
307 byte_data = bytearray(array)
305 308
306 print("SENDING GMCP") 309 print("SENDING GMCP")
307 print(byte_data) 310 print(byte_data)
...@@ -309,6 +312,9 @@ class MudServer(object): ...@@ -309,6 +312,9 @@ class MudServer(object):
309 client_socket.sendall(byte_data) 312 client_socket.sendall(byte_data)
310 313
311 def mxp_secure(self, clid, message, mxp_code="1"): 314 def mxp_secure(self, clid, message, mxp_code="1"):
315 if 'esp' in sys.platform:
316 bytes_to_send = bytearray("\x1b[{}z{}\x1b[3z\r\n".format(mxp_code, message))
317 else:
312 bytes_to_send = bytearray("\x1b[{}z{}\x1b[3z\r\n".format(mxp_code, message), 'utf-8') 318 bytes_to_send = bytearray("\x1b[{}z{}\x1b[3z\r\n".format(mxp_code, message), 'utf-8')
313 client_socket = self._clients[clid].socket 319 client_socket = self._clients[clid].socket
314 client_socket.sendall(bytes_to_send) 320 client_socket.sendall(bytes_to_send)
......
1 {"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 ...\ No newline at end of file
1 {"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 ...\ No newline at end of file
......
...@@ -11,7 +11,7 @@ IPADDRESS = '192.168.1.189' ...@@ -11,7 +11,7 @@ IPADDRESS = '192.168.1.189'
11 11
12 BAUDRATE = 115200 12 BAUDRATE = 115200
13 13
14 folders = ['help', 'rooms', 'rooms/town', 'rooms/wilderness', 'inventory', 'commands', 'mobs'] 14 folders = ['help', 'rooms', 'rooms/town', 'rooms/wilderness', 'inventory', 'mobs']
15 15
16 files = [ 16 files = [
17 "welcome.txt", 17 "welcome.txt",
......
...@@ -2,6 +2,7 @@ import os ...@@ -2,6 +2,7 @@ import os
2 import io 2 import io
3 import serial 3 import serial
4 import time 4 import time
5 import sys
5 6
6 ###################################### 7 ######################################
7 # EDIT THIS TO MATCH YOUR SETTINGS 8 # EDIT THIS TO MATCH YOUR SETTINGS
...@@ -21,6 +22,11 @@ baked_files = [ ...@@ -21,6 +22,11 @@ baked_files = [
21 "utils.py" 22 "utils.py"
22 ] 23 ]
23 24
25 def countdown(t):
26 for x in reversed(range(t)):
27 sys.stdout.write('\r{} '.format(x + 1))
28 time.sleep(1)
29 print('\r\n')
24 30
25 def run_command(sio, command, expected='>>>'): 31 def run_command(sio, command, expected='>>>'):
26 sio.write("{}\n".format(command)) 32 sio.write("{}\n".format(command))
...@@ -47,7 +53,7 @@ os.system('esptool --port {} erase_flash'.format(PORT)) ...@@ -47,7 +53,7 @@ os.system('esptool --port {} erase_flash'.format(PORT))
47 os.system('esptool --port {} --baud 460800 write_flash --flash_size=detect 0 image/firmware-combined.bin'.format(PORT)) 53 os.system('esptool --port {} --baud 460800 write_flash --flash_size=detect 0 image/firmware-combined.bin'.format(PORT))
48 54
49 print("Sleeping 10 seconds for reboot") 55 print("Sleeping 10 seconds for reboot")
50 time.sleep(10) 56 countdown(10)
51 57
52 with open('releasepw.conf', 'r', encoding='utf-8') as f: 58 with open('releasepw.conf', 'r', encoding='utf-8') as f:
53 WEBREPL_PASS = f.read() 59 WEBREPL_PASS = f.read()
...@@ -70,6 +76,9 @@ with serial.Serial(PORT, BAUDRATE, timeout=1) as ser: ...@@ -70,6 +76,9 @@ with serial.Serial(PORT, BAUDRATE, timeout=1) as ser:
70 print('Connecting to {}'.format(ESSID)) 76 print('Connecting to {}'.format(ESSID))
71 run_command(sio, "sta_if.connect('{}', '{}')".format(ESSID, WIFI_PASSWORD)) 77 run_command(sio, "sta_if.connect('{}', '{}')".format(ESSID, WIFI_PASSWORD))
72 78
79 print('Waiting 15 seconds for network to connect.\r\n')
80 countdown(15)
81
73 waiting_for_ip = True 82 waiting_for_ip = True
74 while waiting_for_ip: 83 while waiting_for_ip:
75 try: 84 try:
...@@ -87,7 +96,8 @@ with serial.Serial(PORT, BAUDRATE, timeout=1) as ser: ...@@ -87,7 +96,8 @@ with serial.Serial(PORT, BAUDRATE, timeout=1) as ser:
87 96
88 run_command(sio, 'import machine;machine.reset()') 97 run_command(sio, 'import machine;machine.reset()')
89 98
90 print('Starting the squishy mud release') 99 print('Starting the squishy mud release\r\n')
91 time.sleep(5) 100 countdown(5)
101
92 # Run the rest of the mud setup 102 # Run the rest of the mud setup
93 import release 103 import release
...\ No newline at end of file ...\ No newline at end of file
......
1 {
2 "num": 1002,
3 "coords": { "id": 1000, "x": 1, "y": 0, "z": 0 },
4 "look_items": {
5 "wooden,oak,plank": "An old solid oak plank that has a large number of chips and drink marks.",
6 "barrel,barrels": "The old barrels bands are thick with oxidation and stained with the purple of spilled wine.",
7 "bar": "The bar is a long wooden plank thrown over roughly hewn barrels."
8 },
9 "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.",
10 "inventory": {
11 "candle": [{
12 "age": 0
13 }]
14 },
15 "exits": {
16 "tavern": ["town/tavern", 1001]
17 },
18 "title": "Behind the bar",
19 "zone": "town"
20 }
...\ No newline at end of file ...\ No newline at end of file
1 {"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 ...\ No newline at end of file
......
1 {"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 ...\ No newline at end of file
1 {"cricket": {"max": 1, "active": []}}
...\ No newline at end of file ...\ No newline at end of file
......