e8845005 by Barry

Added image release tool to rebuild automatically and put the bin file

out.
1 parent c272edb4
......@@ -12,6 +12,14 @@ I like the NodeMcu devices. They have 4mb flash and work well and are fairly rob
### How to Load on a New ESP8266
Vagrant setup
https://learn.adafruit.com/building-and-running-micropython-on-the-esp8266/build-firmware
Setup Vagrant SCP
vagrant plugin install vagrant-scp
Use python 3.6+
Create a virtual environment to save your brainspace.
......@@ -38,6 +46,14 @@ Install esptool and the other required pip modules which will let you install th
pip install -r requirements.txt
```
NEW
Custom Vagrant image:
```
python release_image.py
```
<!-- THIS IS REPLACED BY THE NEW RELEASE IMAGE SCRIPT
After the modules are installed you will need to use esptool to erase the flash.
if things go wrong... https://docs.micropython.org/en/latest/esp8266/esp8266/tutorial/intro.html
......@@ -60,6 +76,7 @@ After the file has been downloaded (use wget? browser? curl? whatever makes you
```
esptool --port COM1 --baud 460800 write_flash --flash_size=detect 0 esp8266-20171101-v1.9.3.bin
```
-->
This will write the binary micropython os to the device. After this you will want to validate the write was successful.
......
#!/usr/bin/env python
"""
MudServer author: Mark Frimston - mfrimston@gmail.com
Micropython port and expansion author: Barry Ruffner - barryruffner@gmail.com
"""
from time import sleep
from math import floor
from sys import platform
from os import listdir
from mudserver import MudServer
from commandhandler import CommandHandler
from utils import load_object_from_file, save_object_to_file, password_hash, calc_att, get_att
if 'esp' in platform:
from gc import collect, mem_free
from machine import Pin
# import the MUD server class
print('STARTING MUD\r\n\r\n\r\n')
# Setup button so when pressed the mud goes in to wifi hotspot mode on 192.168.4.1
if 'esp' in platform:
flash_button = Pin(0, Pin.IN, Pin.PULL_UP)
# stores the players in the game
players = {}
# start the server
globals()['mud'] = MudServer()
def show_prompt(pid):
if "prompt" not in players[pid]:
players[pid]["prompt"] = "> "
if 'hp' not in players[pid]:
players[pid]["hp"] = 100
if 'mp' not in players[pid]:
players[pid]["mp"] = 100
if 'sta' not in players[pid]:
players[pid]["sta"] = 10
prompt = players[pid]["prompt"].replace('%st', str(floor(players[pid]['sta']))).replace('%hp', str(floor(players[pid]["hp"]))).replace('%mp', str(floor(players[pid]["mp"])))
mud.send_message(pid, "\r\n" + prompt, '')
tick = 0.0
spawn = 0.0
cmd_handler = CommandHandler()
def spawn_mobs(players):
rooms = listdir('rooms')
for room in rooms:
if '_monsters.json' not in room:
continue
room_monsters = load_object_from_file('rooms/{}'.format(room))
for mon_name, monster in room_monsters.items():
monster_template = load_object_from_file('mobs/{}.json'.format(mon_name))
if not monster_template:
continue
while len(room_monsters[mon_name]['active']) < monster['max']:
print('Spawning {} in {}'.format(mon_name, room))
mp = get_att(monster_template['spawn']["mp"])
hp = get_att(monster_template['spawn']["hp"])
sta = get_att(monster_template['spawn']["sta"])
new_active = {
"mp": mp,
"maxhp": hp,
"hp": hp,
"sta": sta,
"maxmp": mp,
"target": "",
"action": "attack",
"maxsta": sta}
room_monsters[mon_name]['active'].append(new_active)
for pid, pl in players.items():
if players[pid]['room'].lower() == room.split('_')[0]:
mud.send_message(pid, "a {} arrived".format(mon_name))
save_object_to_file(room_monsters, 'rooms/{}'.format(room))
def run_mobs(players, mud):
for pid, player in players.items():
if not player or not player.get("name") or not player.get('password'):
continue
if player['mp'] < player['maxmp']:
players[pid]['mp'] += player['mpr']
if player['sta'] < player['maxsta']:
players[pid]['sta'] += player['star']
room_monsters = load_object_from_file('rooms/{}_monsters.json'.format(player['room']))
for mon_name, monster in room_monsters.items():
monster_template = load_object_from_file('mobs/{}.json'.format(mon_name))
for active_monster_idx, active_monster in enumerate(monster['active']):
sta = active_monster['sta']
if active_monster['mp'] < active_monster['maxmp']:
active_monster['mp'] += monster_template['mpr']
if sta < active_monster['maxsta']:
sta += monster_template['star']
active_monster['sta'] = sta
if active_monster['action'] == "attack" and active_monster['target'] == player['name']:
if player.get("weapon"):
weapon = load_object_from_file('inventory/{}.json'.format(player['weapon']))
att = get_att(weapon['damage'])
mud.send_message(pid, "Your %s strikes the %s for %d" % (weapon['title'], mon_name, att,), color='yellow')
else:
att = get_att(player['aa'])
mud.send_message(pid, "You hit the %s for %d" % (mon_name, att,), color='yellow')
active_monster['hp'] -= att
if active_monster['hp'] <= 0:
del room_monsters[mon_name]['active'][active_monster_idx]
mud.send_message(pid, "The %s dies." % (mon_name,), color=['bold', 'blue'])
break
if active_monster.get("weapon"):
weapon = load_object_from_file('inventory/{}.json'.format(active_monster['weapon']))
att = get_att(weapon['damage'])
mud.send_message(pid, "The %s strikes you with a %s for %d" % (mon_name, weapon['title'], att,), color='magenta')
else:
att = get_att(monster_template['aa'])
mud.send_message(pid, "You were hit by a %s for %d" % (mon_name, att,), color='magenta')
players[pid]['hp'] -= att
if (active_monster['hp']/active_monster['maxhp'] < 0.25) or (active_monster['mp'] > 0 and active_monster['mp']/active_monster['maxmp'] > 0.5) or (sta > 0 and sta/active_monster['maxsta'] > 0.5):
magic_cast = False
if active_monster['mp'] > 0:
att, active_monster['mp'] = calc_att(mud, pid, monster_template['sp'], active_monster['mp'])
players[pid]['hp'] -= att
if att > 0:
magic_cast = True
if not magic_cast:
if sta > 0:
att, sta = calc_att(mud, pid, monster_template['at'], sta)
active_monster['sta'] = sta
players[pid]['hp'] -= att
room_monsters[mon_name]['active'][active_monster_idx] = active_monster
save_object_to_file(room_monsters, 'rooms/{}_monsters.json'.format(player['room']))
# main game loop. We loop forever (i.e. until the program is terminated)
while True:
if 'esp' in platform:
collect()
if flash_button.value() == 0:
break
# pause for 1/5 of a second on each loop, so that we don't constantly
sleep(0.002)
if 'esp' in platform:
tick += 0.001
else:
tick += 0.0005
if spawn >= 10:
spawn = 0
try:
spawn_mobs(players)
except Exception as e:
print('spawner error:')
print(e)
if 'esp' in platform:
collect()
if tick >= 1:
if 'esp' in platform:
print(mem_free())
spawn += tick
tick = 0
try:
run_mobs(players, mud)
except Exception as e:
print('mob error:')
print(e)
# 'update' must be called in the loop to keep the game running and give
# us up-to-date information
mud.update()
# go through any newly connected players
for id in mud.get_new_players():
# add the new player to the dictionary, noting that they've not been
# named yet.
# The dictionary key is the player's id number. We set their room to
# None initially until they have entered a name
# Try adding more player stats - level, gold, inventory, etc
players[id] = load_object_from_file("defaultplayer.json")
with open('welcome.txt', 'r', encoding='utf-8') as f:
for line in f:
mud.send_message(id, line, "\r")
# send the new player a prompt for their name
#bytes_to_send = bytearray([mud._TN_INTERPRET_AS_COMMAND, mud._TN_WONT, mud._ECHO])
#mud.raw_send(id, bytes_to_send)
mud.send_message(id, "What is your name?")
# go through any recently disconnected players
for id in mud.get_disconnected_players():
# if for any reason the player isn't in the player map, skip them and
# move on to the next one
if id not in players:
continue
# go through all the players in the game
for pid, pl in players.items():
# send each player a message to tell them about the diconnected
# player
if players[pid].get("name") is not None:
mud.send_message(pid, "{} quit the game".format(players[pid]["name"]))
# remove the player's entry in the player dictionary
if players[id]["name"] is not None:
save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
del(players[id])
# go through any new commands sent from players
for id, command, params in mud.get_commands():
# if for any reason the player isn't in the player map, skip them and
# move on to the next one
if id not in players:
continue
# if the player hasn't given their name yet, use this first command as
# their name and move them to the starting room.
if players[id].get("name") is None:
if command.strip() == '' or len(command) > 12 or not command.isalnum() or command is None:
mud.send_message(id, "Invalid Name")
print("Bad guy!")
print(mud.get_remote_ip(id))
continue
already_logged_in = False
for pid, pl in players.items():
if players[pid].get("name") == command:
mud.send_message(id, "{} is already logged in.".format(command))
mud.disconnect_player(id)
continue
loaded_player = load_object_from_file("players/{}.json".format(command))
mud.remote_echo(id, False)
players[id]["name"] = command
if not loaded_player:
# Player does not exist.
mud.send_message(id, "Character does not exist. Please enter a password to create a new character: ")
else:
mud.send_message(id, "Enter Password: ")
elif players[id]["password"] is None:
if players[id].get("retries", 0) > 1:
mud.send_message(id, "Too many attempts")
mud.disconnect_player(id)
continue
if command.strip() == '' or command is None:
players[id]["retries"] = players[id].get("retries", 0) + 1
mud.send_message(id, "Invalid Password")
continue
loaded_player = load_object_from_file("players/{}.json".format(players[pid]["name"]))
if loaded_player is None:
players[id]["password"] = password_hash(players[pid]["name"], command)
players[id]["room"] = "town/tavern"
else:
if loaded_player["password"] == password_hash(players[pid]["name"], command):
players[id] = loaded_player
else:
players[id]["retries"] = players[id].get("retries", 0) + 1
mud.send_message(id, "Invalid Password")
continue
# go through all the players in the game
for pid, pl in players.items():
# send each player a message to tell them about the new player
mud.send_message(pid, "{} entered the game".format(players[id]["name"]))
mud.remote_echo(id, True)
# send the new player a welcome message
mud.send_message(id, "\r\n\r\nWelcome to the game, {}. ".format(players[id]["name"]) +
"\r\nType 'help' for a list of commands. Have fun!\r\n\r\n")
# send the new player the description of their current room
cmd_handler.parse(id, 'look', '', mud, players)
show_prompt(id)
else:
if 'esp' in platform:
collect()
cmd_handler.parse(id, command, params, mud, players)
show_prompt(id)
# Start WIFI Setup
if 'esp' in platform:
if flash_button.value() == 0:
print('Starting WIFIWeb')
import wifiweb
import weemud
\ No newline at end of file
......
......@@ -12,9 +12,13 @@ import socket
import select
import time
import sys
import struct
import json
if 'esp' in sys.platform:
import ustruct
else:
import struct
from utils import get_color, get_color_list, multiple_replace
......@@ -426,7 +430,7 @@ class MudServer(object):
try:
# read data from the socket, using a max length of 4096
data = cl.socket.recv(4096)
data = cl.socket.recv(1024)
# process the data, stripping out any special Telnet commands
message = self._process_sent_data(cl, data)
......@@ -640,7 +644,10 @@ class MudServer(object):
if option_state == self._READ_NAWS:
height = 30
width = 100
height, width = struct.unpack('>hh', option_data)
if 'esp' in sys.platform:
height, width = ustruct.unpack('>hh', option_data)
else:
height, width = struct.unpack('>hh', option_data)
if height > 0:
client.height = height
if width > 0:
......
......@@ -11,15 +11,12 @@ IPADDRESS = '192.168.1.189'
BAUDRATE = 115200
folders = ['help', 'rooms', 'inventory', 'commands', 'mobs']
folders = ['help', 'rooms', 'rooms/town', 'rooms/wilderness', 'inventory', 'commands', 'mobs']
files = [
"main.py",
"mobs.txt",
"spawner.txt",
"welcome.txt",
"wifiweb.py",
"defaultplayer.json"
"defaultplayer.json",
"main.py"
]
def run_command(sio, command, expected='>>>'):
......@@ -27,18 +24,21 @@ def run_command(sio, command, expected='>>>'):
sio.flush() # it is buffering. required to get the data out *now*
res = ''
while expected not in res:
res = sio.readline()
# print(res)
try:
res = sio.readline()
except UnicodeDecodeError:
return ''
return res
with serial.Serial(PORT, BAUDRATE, timeout=1) as ser:
sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser))
run_command(sio, '\x03')
run_command(sio, 'import os')
root = eval(run_command(sio, 'os.listdir()', expected=']'))
if not set(folders).issubset(root):
root = run_command(sio, 'os.listdir()', expected=']')
if 'EEXIST' in root:
print('Folders already created.')
else:
print('Creating folders.')
# we are missing folders so they need to be created.
tmp_folders = folders
......@@ -48,18 +48,19 @@ with serial.Serial(PORT, BAUDRATE, timeout=1) as ser:
continue
print('Creating folder: {}'.format(folder))
run_command(sio, 'os.mkdir("{}")'.format(folder))
else:
print('Folders already created.')
for folder in folders:
for f in os.listdir(folder):
files.append('{}/{}'.format(folder, f))
if not os.path.isdir(f):
files.append('{}/{}'.format(folder, f))
with open('releasepw.conf', 'r', encoding='utf-8') as f:
password = f.read()
for file in files:
os.system("python webrepl\webrepl_cli.py -p {} {} {}:/{}".format(password, file, IPADDRESS, file))
# print("python webrepl\\webrepl_cli.py -p {} {} {}:/{}".format(password, file, IPADDRESS, file))
os.system("python webrepl\\webrepl_cli.py -p {} {} {}:/{}".format(password, file, IPADDRESS, file))
run_command(sio, 'import machine;machine.reset')
print("Rebooting via machine reset")
run_command(sio, 'import machine;machine.reset()')
......
import os
import io
import serial
import time
######################################
# EDIT THIS TO MATCH YOUR SETTINGS
PORT = 'COM17'
VMID = '1e5fc8c'
ESSID = 'Volley'
WIFI_PASSWORD = '6198472223'
######################################
BAUDRATE = 115200
baked_files = [
"weemud.py",
"mudserver.py",
"commandhandler.py",
"wifiweb.py",
"utils.py"
]
def run_command(sio, command, expected='>>>'):
sio.write("{}\n".format(command))
sio.flush() # it is buffering. required to get the data out *now*
res = ''
while expected not in res:
try:
res = sio.readline()
except UnicodeDecodeError:
return ''
return res
# Compile vagrant image
for file in baked_files:
os.system("vagrant scp {} {}:micropython/ports/esp8266/modules/{}".format(file, VMID, file))
os.system('vagrant ssh {} -c "cd micropython/ports/esp8266;make"'.format(VMID))
try:
os.mkdir('image')
except FileExistsError:
pass
os.system('vagrant scp {}:micropython/ports/esp8266/build/firmware-combined.bin image/firmware-combined.bin'.format(VMID))
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)
with open('releasepw.conf', 'r', encoding='utf-8') as f:
WEBREPL_PASS = f.read()
with serial.Serial(PORT, BAUDRATE, timeout=1) as ser:
sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser))
run_command(sio, '\x03')
run_command(sio, 'import os')
print('Setting up Webrepl')
run_command(sio, "f = open('webrepl_cfg.py', 'w+').write(\"PASS = '{}'\\n\")".format(WEBREPL_PASS))
run_command(sio, 'f = open("boot.py", "w+").write("# This file is executed on every boot (including wake-boot from deepsleep)\\n#import esp\\n#esp.osdebug(None)\\nimport gc\\nimport webrepl\\nwebrepl.start()\\ngc.collect()\\n")')
print('Setting up Wifi Network')
run_command(sio, 'import network')
run_command(sio, 'sta_if = network.WLAN(network.STA_IF)')
run_command(sio, 'ap_if = network.WLAN(network.AP_IF)')
run_command(sio, 'sta_if.active(True)')
print('Connecting to {}'.format(ESSID))
run_command(sio, "sta_if.connect('{}', '{}')".format(ESSID, WIFI_PASSWORD))
waiting_for_ip = True
while waiting_for_ip:
try:
ifconfig = eval(run_command(sio, "sta_if.ifconfig()", expected='('))
if ifconfig[0] != '0.0.0.0':
print("New IP Address: {}".format(ifconfig[0]))
waiting_for_ip = False
except SyntaxError:
pass
except NameError:
pass
print("Rebooting via machine reset")
run_command(sio, 'import machine;machine.reset()')
print('Starting the squishy mud release')
time.sleep(5)
# Run the rest of the mud setup
import release
\ No newline at end of file
import json
import sys
import re
if 'esp' in sys.platform:
from urandom import getrandbits
......@@ -12,7 +11,7 @@ codes = {'resetall': 0, 'bold': 1, 'underline': 4,
'blinkoff': 25, 'underlineoff': 24, 'reverseoff': 27,
'reset': 0, 'black': 30, 'red': 31, 'green': 32,
'yellow': 33, 'blue': 34, 'magenta': 35, 'cyan': 36,
'white': 37}
'white': 37 }
def password_hash(name, password):
......@@ -37,13 +36,10 @@ def get_color(name):
return '\x1b[{}m'.format(codes.get(name, 0))
def multiple_replace(text, adict):
rx = re.compile('|'.join(map(re.escape, adict)))
def one_xlat(match):
return get_color(adict[match.group(0)])
return rx.sub(one_xlat, text)
def multiple_replace(text, replace_words):
for word, replacement in replace_words.items():
text = text.replace(word, get_color(replacement))
return text
def save_object_to_file(obj, filename):
with open(filename.lower(), 'w', encoding='utf-8') as f:
......
#!/usr/bin/env python
"""
MudServer author: Mark Frimston - mfrimston@gmail.com
Micropython port and expansion author: Barry Ruffner - barryruffner@gmail.com
"""
from time import sleep
from math import floor
from sys import platform
from os import listdir
from mudserver import MudServer
from commandhandler import CommandHandler
from utils import load_object_from_file, save_object_to_file, password_hash, calc_att, get_att
if 'esp' in platform:
from gc import collect, mem_free
from machine import Pin
# import the MUD server class
print('STARTING MUD\r\n\r\n\r\n')
# Setup button so when pressed the mud goes in to wifi hotspot mode on 192.168.4.1
if 'esp' in platform:
flash_button = Pin(0, Pin.IN, Pin.PULL_UP)
# stores the players in the game
players = {}
# start the server
globals()['mud'] = MudServer()
def show_prompt(pid):
if "prompt" not in players[pid]:
players[pid]["prompt"] = "> "
if 'hp' not in players[pid]:
players[pid]["hp"] = 100
if 'mp' not in players[pid]:
players[pid]["mp"] = 100
if 'sta' not in players[pid]:
players[pid]["sta"] = 10
prompt = players[pid]["prompt"].replace('%st', str(floor(players[pid]['sta']))).replace('%hp', str(floor(players[pid]["hp"]))).replace('%mp', str(floor(players[pid]["mp"])))
mud.send_message(pid, "\r\n" + prompt, '')
tick = 0.0
spawn = 0.0
cmd_handler = CommandHandler()
def spawn_mobs(players):
rooms = listdir('rooms')
for room in rooms:
if '_monsters.json' not in room:
continue
room_monsters = load_object_from_file('rooms/{}'.format(room))
for mon_name, monster in room_monsters.items():
monster_template = load_object_from_file('mobs/{}.json'.format(mon_name))
if not monster_template:
continue
while len(room_monsters[mon_name]['active']) < monster['max']:
print('Spawning {} in {}'.format(mon_name, room))
mp = get_att(monster_template['spawn']["mp"])
hp = get_att(monster_template['spawn']["hp"])
sta = get_att(monster_template['spawn']["sta"])
new_active = {
"mp": mp,
"maxhp": hp,
"hp": hp,
"sta": sta,
"maxmp": mp,
"target": "",
"action": "attack",
"maxsta": sta}
room_monsters[mon_name]['active'].append(new_active)
for pid, pl in players.items():
if players[pid]['room'].lower() == room.split('_')[0]:
mud.send_message(pid, "a {} arrived".format(mon_name))
save_object_to_file(room_monsters, 'rooms/{}'.format(room))
def run_mobs(players, mud):
for pid, player in players.items():
if not player or not player.get("name") or not player.get('password'):
continue
if player['mp'] < player['maxmp']:
players[pid]['mp'] += player['mpr']
if player['sta'] < player['maxsta']:
players[pid]['sta'] += player['star']
room_monsters = load_object_from_file('rooms/{}_monsters.json'.format(player['room']))
for mon_name, monster in room_monsters.items():
monster_template = load_object_from_file('mobs/{}.json'.format(mon_name))
for active_monster_idx, active_monster in enumerate(monster['active']):
sta = active_monster['sta']
if active_monster['mp'] < active_monster['maxmp']:
active_monster['mp'] += monster_template['mpr']
if sta < active_monster['maxsta']:
sta += monster_template['star']
active_monster['sta'] = sta
if active_monster['action'] == "attack" and active_monster['target'] == player['name']:
if player.get("weapon"):
weapon = load_object_from_file('inventory/{}.json'.format(player['weapon']))
att = get_att(weapon['damage'])
mud.send_message(pid, "Your %s strikes the %s for %d" % (weapon['title'], mon_name, att,), color='yellow')
else:
att = get_att(player['aa'])
mud.send_message(pid, "You hit the %s for %d" % (mon_name, att,), color='yellow')
active_monster['hp'] -= att
if active_monster['hp'] <= 0:
del room_monsters[mon_name]['active'][active_monster_idx]
mud.send_message(pid, "The %s dies." % (mon_name,), color=['bold', 'blue'])
break
if active_monster.get("weapon"):
weapon = load_object_from_file('inventory/{}.json'.format(active_monster['weapon']))
att = get_att(weapon['damage'])
mud.send_message(pid, "The %s strikes you with a %s for %d" % (mon_name, weapon['title'], att,), color='magenta')
else:
att = get_att(monster_template['aa'])
mud.send_message(pid, "You were hit by a %s for %d" % (mon_name, att,), color='magenta')
players[pid]['hp'] -= att
if (active_monster['hp']/active_monster['maxhp'] < 0.25) or (active_monster['mp'] > 0 and active_monster['mp']/active_monster['maxmp'] > 0.5) or (sta > 0 and sta/active_monster['maxsta'] > 0.5):
magic_cast = False
if active_monster['mp'] > 0:
att, active_monster['mp'] = calc_att(mud, pid, monster_template['sp'], active_monster['mp'])
players[pid]['hp'] -= att
if att > 0:
magic_cast = True
if not magic_cast:
if sta > 0:
att, sta = calc_att(mud, pid, monster_template['at'], sta)
active_monster['sta'] = sta
players[pid]['hp'] -= att
room_monsters[mon_name]['active'][active_monster_idx] = active_monster
save_object_to_file(room_monsters, 'rooms/{}_monsters.json'.format(player['room']))
def isalnum(c):
for letter in c:
if not letter.isalpha() and not letter.isdigit():
return False
return True
# main game loop. We loop forever (i.e. until the program is terminated)
while True:
if 'esp' in platform:
collect()
if flash_button.value() == 0:
break
# pause for 1/5 of a second on each loop, so that we don't constantly
sleep(0.002)
if 'esp' in platform:
tick += 0.001
else:
tick += 0.0005
if spawn >= 10:
spawn = 0
try:
spawn_mobs(players)
except Exception as e:
print('spawner error:')
print(e)
if 'esp' in platform:
collect()
if tick >= 1:
if 'esp' in platform:
print(mem_free())
spawn += tick
tick = 0
try:
run_mobs(players, mud)
except Exception as e:
print('mob error:')
print(e)
# 'update' must be called in the loop to keep the game running and give
# us up-to-date information
mud.update()
# go through any newly connected players
for id in mud.get_new_players():
# add the new player to the dictionary, noting that they've not been
# named yet.
# The dictionary key is the player's id number. We set their room to
# None initially until they have entered a name
# Try adding more player stats - level, gold, inventory, etc
players[id] = load_object_from_file("defaultplayer.json")
with open('welcome.txt', 'r', encoding='utf-8') as f:
for line in f:
mud.send_message(id, line, "\r")
# send the new player a prompt for their name
#bytes_to_send = bytearray([mud._TN_INTERPRET_AS_COMMAND, mud._TN_WONT, mud._ECHO])
#mud.raw_send(id, bytes_to_send)
mud.send_message(id, "What is your name?")
# go through any recently disconnected players
for id in mud.get_disconnected_players():
# if for any reason the player isn't in the player map, skip them and
# move on to the next one
if id not in players:
continue
# go through all the players in the game
for pid, pl in players.items():
# send each player a message to tell them about the diconnected
# player
if players[pid].get("name") is not None:
mud.send_message(pid, "{} quit the game".format(players[pid]["name"]))
# remove the player's entry in the player dictionary
if players[id]["name"] is not None:
save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
del(players[id])
# go through any new commands sent from players
for id, command, params in mud.get_commands():
# if for any reason the player isn't in the player map, skip them and
# move on to the next one
if id not in players:
continue
# if the player hasn't given their name yet, use this first command as
# their name and move them to the starting room.
if players[id].get("name") is None:
if command.strip() == '' or len(command) > 12 or not isalnum(command) or command is None:
mud.send_message(id, "Invalid Name")
print("Bad guy!")
print(mud.get_remote_ip(id))
continue
already_logged_in = False
for pid, pl in players.items():
if players[pid].get("name") == command:
mud.send_message(id, "{} is already logged in.".format(command))
mud.disconnect_player(id)
continue
loaded_player = load_object_from_file("players/{}.json".format(command))
mud.remote_echo(id, False)
players[id]["name"] = command
if not loaded_player:
# Player does not exist.
mud.send_message(id, "Character does not exist. Please enter a password to create a new character: ")
else:
mud.send_message(id, "Enter Password: ")
elif players[id]["password"] is None:
if players[id].get("retries", 0) > 1:
mud.send_message(id, "Too many attempts")
mud.disconnect_player(id)
continue
if command.strip() == '' or command is None:
players[id]["retries"] = players[id].get("retries", 0) + 1
mud.send_message(id, "Invalid Password")
continue
loaded_player = load_object_from_file("players/{}.json".format(players[pid]["name"]))
if loaded_player is None:
players[id]["password"] = password_hash(players[pid]["name"], command)
players[id]["room"] = "town/tavern"
else:
if loaded_player["password"] == password_hash(players[pid]["name"], command):
players[id] = loaded_player
else:
players[id]["retries"] = players[id].get("retries", 0) + 1
mud.send_message(id, "Invalid Password")
continue
# go through all the players in the game
for pid, pl in players.items():
# send each player a message to tell them about the new player
mud.send_message(pid, "{} entered the game".format(players[id]["name"]))
mud.remote_echo(id, True)
# send the new player a welcome message
mud.send_message(id, "\r\n\r\nWelcome to the game, {}. ".format(players[id]["name"]) +
"\r\nType 'help' for a list of commands. Have fun!\r\n\r\n")
# send the new player the description of their current room
cmd_handler.parse(id, 'look', '', mud, players)
show_prompt(id)
else:
if 'esp' in platform:
collect()
cmd_handler.parse(id, command, params, mud, players)
show_prompt(id)
# Start WIFI Setup
if 'esp' in platform:
if flash_button.value() == 0:
print('Starting WIFIWeb')
import wifiweb