a277bbbb by Barry

Added some new things to the login to get character setup rolling

1 parent a757808c
......@@ -727,20 +727,6 @@ class CommandHandler(object):
if callable(command_method):
params = params.lower().strip()
return command_method(id, params, players, mud, tokens, cmd)
# else:
# ldict = locals()
# with open('commands/{}.txt'.format(cmd), 'r', encoding='utf-8') as f:
# command_text = f.read()
# exec(command_text, globals(), ldict)
# del command_text
# if ldict['next_command'] is not None:
# locals()['tokens'] = []
# tokens = []
# with open('commands/{}.txt'.format(ldict['next_command']), 'r', encoding='utf-8') as f:
# exec(f.read())
# del ldict
#raise Exception("Missing command: {}".format(cmd))
except Exception as e:
print('Command handler exception:')
if 'esp' not in sys.platform:
......
......@@ -48,12 +48,15 @@ class MudServer(object):
# the last time we checked if the client was still connected
lastcheck = 0
color_enabled = True
def __init__(self, socket, address, buffer, lastcheck):
self.socket = socket
self.address = address
self.buffer = buffer
self.lastcheck = lastcheck
# Used to store different types of occurences
_EVENT_NEW_PLAYER = 1
_EVENT_PLAYER_LEFT = 2
......@@ -223,20 +226,29 @@ class MudServer(object):
"""
# we make sure to put a newline on the end so the client receives the
# message on its own line
message = multiple_replace(message, get_color_list())
try:
color_enabled = self._clients[to].color_enabled
except KeyError:
color_enabled = False
message = multiple_replace(message, get_color_list(), color_enabled)
if nowrap:
lines = [message]
else:
chunks, chunk_size = len(message), 80 #len(x)/4
lines = [message[i:i + chunk_size] for i in range(0, chunks, chunk_size)]
if color:
if color and self._clients[to].color_enabled:
if isinstance(color, list):
colors = ''.join([get_color(c) for c in color])
self._attempt_send(to, colors + '\r\n'.join(lines) + line_ending + get_color('reset'))
else:
self._attempt_send(to, get_color(color) + '\r\n'.join(lines) + line_ending + get_color('reset'))
else:
if color_enabled:
self._attempt_send(to, '\r\n'.join(lines) + line_ending + get_color('reset'))
else:
self._attempt_send(to, '\r\n'.join(lines) + line_ending)
def shutdown(self):
"""Closes down the server, disconnecting all clients and
......
......@@ -36,9 +36,12 @@ def get_color(name):
return '\x1b[{}m'.format(codes.get(name, 0))
def multiple_replace(text, replace_words):
def multiple_replace(text, replace_words, color_enabled=True):
for word, replacement in replace_words.items():
if color_enabled:
text = text.replace(word, get_color(replacement))
else:
text = text.replace(word, '')
return text
def save_object_to_file(obj, filename):
......
......@@ -9,7 +9,7 @@ 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 os import listdir, remove
from mudserver import MudServer
from commandhandler import CommandHandler
......@@ -33,6 +33,137 @@ players = {}
# start the server
globals()['mud'] = MudServer()
races = {
"Android": {
"desc":"Androids are artificial creatures with both biological and mechanical elements, originally created by humanity as servants and now free to chart their own destiny among the stars.",
"mods": {"dex": 2, "int": 2, "cha": -2, "hp": 4}
},
"Human": {
"desc":"Ambitious, creative, and endlessly curious, humans have shown more drive to explore their system and the universe beyond than any of their neighbor races for better and for worse. They've helped usher in a new era of system-wide communication and organization and are admired for their passion and tenacity, but their tendency to shoot first and think about the consequences later can make them a liability for those races otherwise inclined to work with them.",
"mods": {"hp": 4}
},
"Kasathas": {
"desc":"Originally from a planet orbiting a dying star far beyond the Pact Worlds, the four-armed kasathas maintain a reputation as a noble and mysterious people. They are famous for their anachronistic warriors, ancient wisdom, and strange traditions.",
"mods": {"str": 2, "wis": 2, "int": -2, "hp": 4}
},
"Korasha Lashuntas": {
"desc":"Idealized by many other humanoid races and gifted with innate psychic abilities, lashuntas are at once consummate scholars and enlightened warriors, naturally divided into two specialized subraces with different abilities and societal roles.",
"mods": {"str": 2, "cha": 2, "wis": -2, "hp": 4}
},
"Damaya Lashuntas": {
"desc":"Idealized by many other humanoid races and gifted with innate psychic abilities, lashuntas are at once consummate scholars and enlightened warriors, naturally divided into two specialized subraces with different abilities and societal roles.",
"mods": {"int": 2, "cha": 2, "con": -2, "hp": 4}
},
"Shirrens": {
"desc":"Once part of a ravenous hive of locust-like predators, the insectile shirrens only recently broke with their hive mind to become a race of telepaths physically addicted to their own individualism, yet dedicated to the idea of community and harmony with other races",
"mods": {"con": 2, "wis": 2, "cha": -2, "hp": 6}
},
"Vesk": {
"desc":"Heavily muscled and covered with thick scales and short, sharp horns, the reptilian vesk are exactly as predatory and warlike as they appear. Originally hailing from a star system near the Pact Worlds, they sought to conquer and subdue their stellar neighbors, as they had all the other intelligent races in their own system, until an overwhelming threat forced them into a grudging alliance with the Pact Worlds for now.",
"mods": {"str": 2, "con": 2, "int": -2, "hp": 6}
},
"Ysoki": {
"desc":"Small and furtive, the ysoki are often overlooked by larger races. Yet through wit and technological prowess, they've spread throughout the solar system, giving truth to the old adage that every starship needs a few rats.",
"mods": {"dex": 2, "int": 2, "str": -2, "hp": 2}
}
}
themes = {
"Ace Pilot": {
"desc": "Skillful operator of starships and other vehicles who is obsessed with all related knowledge and lore.",
"mods": {"dex": 1}
},
"Bounty Hunter": {
"desc": "Unstoppable tracker who knows how to stay hot on the trail of those who flee.",
"mods": {"con": 1}
},
"Icon": {
"desc": "Popular and respected celebrity who can leverage the public's adoration for specific needs.",
"mods": {"cha": 1}
},
"Mercenary": {
"desc": "Well-trained soldier of fortune who can work equally well as a combat grunt or a squad leader.",
"mods": {"str": 1}
},
"Outlaw": {
"desc": "Wanted criminal with back-alley connections to black markets and associates who can fend off legal trouble.",
"mods": {"dex": 1}
},
"Priest": {
"desc": "Dedicated and knowledgeable adherent to a philosophy or religion who commands clout among other followers.",
"mods": {"wis": 1}
},
"Scholar": {
"desc": "Skilled researcher and cutting-edge thinker with a broad base of knowledge and a thirst to expand it.",
"mods": {"int": 1}
},
"Spacefarer": {
"desc": "Restless explorer who has strong intuition and has collected deep knowledge about alien biology and topology.",
"mods": {"con": 1}
},
"Xenoseeker": {
"desc": "Guru of alien life-forms who finds that meeting them is one of life's most rewarding accomplishments.",
"mods": {"cha": 1}
}
# "Themeless":{
# "desc": "One who doesn't fit into any niche above but forges a personal path of determination and training."
# "mods": {"": 1}
# },
}
classes = {
"Envoy": {
"desc": "Charismatic people person good at a wide range of skills who inspires allies to accomplish great heroic feats.",
"skills": ["Acrobatics", "Intimidate", "Athletics", "Medicine", "Bluff", "Perception", "Computers", "Piloting", "Culture", "Profession", "Diplomacy", "Sense Motive", "Disguise", "Sleight of Hand", "Engineering", "Stealth"],
"keyability": "cha",
"proficiencies": ["light armor", "basic melee", "grenades", "small arms"],
"skillperlevel": 8,
},
"Mechanic": {
"desc": "Master of machines and technology whose tinkering produces a drone companion or a powerful brain implant.",
"skills": ["Athletics", "Perception", "Computers", "Physical Science", "Engineering", "Piloting", "Medicine", "Profession"],
"keyability": "int",
"proficiencies": ["light armor", "basic melee", "grenades", "small arms"],
"skillperlevel": 4,
},
"Mystic": {
"desc": "Magic user whose mysterious connection to a powerful force grants abilities that break the laws of the universe.",
"skills": ["Bluff", "Medicine", "Culture", "Mysticism", "Diplomacy", "Perception", "Disguise", "Profession", "Intimidate", "Sense Motive", "Life Science", "Survival"],
"keyability": "wis",
"proficiencies": ["light armor", "basic melee", "small arms"],
"skillperlevel": 6,
},
"Operative": {
"desc": "Stealthy combatant with wide-ranging know-how who is adept at taking advantage of unprepared foes.",
"skills": ["Acrobatics", "Medicine", "Athletics", "Perception", "Bluff", "Piloting", "Computers", "Profession", "Culture", "Sense Motive", "Disguise", "Sleight of Hand", "Engineering", "Stealth", "Intimidate", "Survival"],
"keyability": "dex",
"proficiencies": ["light armor", "basic melee", "small arms", "sniper weapons"],
"skillperlevel": 8,
},
"Solarian": {
"desc": "Disciplined warrior whose mastery of the stars grants either a weapon or armor made of stellar power.",
"skills": ["Acrobatics", "Perception", "Athletics", "Physical Science", "Diplomacy", "Profession", "Intimidate", "Sense Motive", "Mysticism", "Stealth"],
"keyability": "cha",
"proficiencies": ["light armor", "basic melee", "advanced melee", "small arms"],
"skillperlevel": 4,
},
"Soldier": {
"desc": "Expert with a huge range of armor, guns, and melee weapons who specializes in certain types of gear.",
"skills": ["Acrobatics", "Medicine", "Athletics", "Piloting", "Engineering", "Profession", "Intimidate", "Survival"],
"keyability": "str",
"proficiencies": ["light armor", "heavy armor", "basic melee", "advanced melee", "small arms", "long arms", "heavy weapons", "sniper weapons", "grenades"],
"skillperlevel": 4,
},
"Technomancer": {
"desc": "Magic user who is preternaturally attuned to technology and can use it to unlock powerful effects.",
"skills": ["Computers", "Physical Science", "Engineering", "Piloting", "Life Science", "Profession", "Mysticism", "Sleight of Hand"],
"keyability": "int",
"proficiencies": ["light armor", "basic melee", "small arms"],
"skillperlevel": 4,
}
}
def show_prompt(pid):
if "prompt" not in players[pid]:
......@@ -143,6 +274,123 @@ def isalnum(c):
return False
return True
def handle_character_create(id, command, params):
if players[id]["createstep"] == 1:
players[id]["color_enabled"] = command[0] in ['y', 'Y']
mud._clients[id].color_enabled = players[id]["color_enabled"]
if players[id]["color_enabled"]:
mud.send_message(id, '%bold%blueC%yellowo%redl%greeno%cyanr%reset %boldenabled.%reset\r\n')
else:
mud.send_message(id, 'Color disabled.\r\n')
mud.send_message(id, "Are you at least 13 years of age?")
players[id]["createstep"] = 2
elif players[id]["createstep"] == 2:
players[id]["over_13"] = command[0] in ['y', 'Y']
if not players[id]["over_13"]:
mud.send_message(id, "You must be at least 13 years old to play this game.")
try:
mud._clients[id].socket.close()
remove("players/{}.json".format(players[id]["name"]))
del(players[id])
del(mud._clients[id])
except:
pass
return
else:
mud.send_message(id, " %green+------------=Races=------------+", nowrap=True)
for idx, race in enumerate(races):
mud.send_message(id, " %%green|%%reset%%bold%%white%s%%reset%%green|" % ('{}. {:<28}'.format(idx, race),), nowrap=True)
mud.send_message(id, " %green+-------------------------------+", nowrap=True)
mud.send_message(id, 'Please choose a race from the list by number: ')
players[id]["createstep"] = 3
elif players[id]["createstep"] == 3:
if command.lower().startswith("help"):
races_lower = {k.lower():v for k,v in races.items()}
race = races_lower.get(params.lower().strip())
if race:
mods = '\r\n'.join(" %green{!s: <4} %bold{!r}%reset".format(key,val) for (key,val) in race.get("mods").items())
mud.send_message(id, "\r\n%green{}\r\n%bold{}\r\n\n%resetStat Modifiers:".format(params.strip(), race.get("desc")))
mud.send_message(id, mods + "\r\n", nowrap=True)
else:
mud.send_message(id, "Please type the name of the race you want to learn about.", color='cyan')
if not command.isdigit():
mud.send_message(id, " %green+------------=Races=-----------+", nowrap=True)
for idx, race in enumerate(races):
mud.send_message(id, " %%green|%%reset%%bold%%white%s%%reset%%green|" % ('{}. {:<27}'.format(idx, race),), nowrap=True)
mud.send_message(id, " %green+------------------------------+", nowrap=True)
mud.send_message(id, ' (Type %boldhelp [race]%reset for details)\r\n')
mud.send_message(id, 'Please choose a race from the list by number: ')
else:
race = list(races)[int(command)]
mud.send_message(id, 'Race selected: {}'.format(race))
players[id]["race"] = race
players[id]["createstep"] = 4
mud.send_message(id, " %green+------------=Themes=-----------+", nowrap=True)
for idx, theme in enumerate(themes):
mud.send_message(id, " %%green|%%reset%%bold%%white%s%%reset%%green|" % ('{}. {:<27}'.format(idx, theme),), nowrap=True)
mud.send_message(id, " %green+------------------------------+", nowrap=True)
mud.send_message(id, ' (Type %boldhelp [theme]%reset for details)\r\n')
mud.send_message(id, 'Please choose a theme from the list by number: ')
elif players[id]["createstep"] == 4:
if command.lower().startswith("help"):
themes_lower = {k.lower():v for k,v in themes.items()}
theme = themes_lower.get(params.lower().strip())
if theme:
mods = '\r\n'.join(" %green{!s: <4} %bold{!r}%reset".format(key,val) for (key,val) in theme.get("mods").items())
mud.send_message(id, "\r\n%green{}\r\n%bold{}\r\n\n%resetStat Modifiers:".format(params.strip(), theme.get("desc")))
mud.send_message(id, mods + "\r\n", nowrap=True)
else:
mud.send_message(id, "Please type the name of the theme you want to learn about.", color='cyan')
if not command.isdigit():
mud.send_message(id, " %green+------------=Themes=-----------+", nowrap=True)
for idx, theme in enumerate(themes):
mud.send_message(id, " %%green|%%reset%%bold%%white%s%%reset%%green|" % ('{}. {:<27}'.format(idx, theme),), nowrap=True)
mud.send_message(id, " %green+------------------------------+", nowrap=True)
mud.send_message(id, ' (Type %boldhelp [theme]%reset for details)\r\n')
mud.send_message(id, 'Please choose a theme from the list by number: ')
else:
theme = list(themes)[int(command)]
mud.send_message(id, 'Theme selected: {}'.format(theme))
players[id]["theme"] = theme
players[id]["createstep"] = 5
elif players[id]["createstep"] == 5:
if command.lower().startswith("help"):
themes_lower = {k.lower():v for k,v in themes.items()}
theme = themes_lower.get(params.lower().strip())
if theme:
mods = '\r\n'.join(" %green{!s: <4} %bold{!r}%reset".format(key,val) for (key,val) in theme.get("mods").items())
mud.send_message(id, "\r\n%green{}\r\n%bold{}\r\n\n%resetStat Modifiers:".format(params.strip(), theme.get("desc")))
mud.send_message(id, mods + "\r\n", nowrap=True)
else:
mud.send_message(id, "Please type the name of the theme you want to learn about.", color='cyan')
if not command.isdigit():
mud.send_message(id, " %green+------------=Themes=-----------+", nowrap=True)
for idx, theme in enumerate(themes):
mud.send_message(id, " %%green|%%reset%%bold%%white%s%%reset%%green|" % ('{}. {:<27}'.format(idx, theme),), nowrap=True)
mud.send_message(id, " %green+------------------------------+", nowrap=True)
mud.send_message(id, ' (Type %boldhelp [theme]%reset for details)\r\n')
mud.send_message(id, 'Please choose a theme from the list by number: ')
else:
theme = list(themes)[int(command)]
mud.send_message(id, 'Theme selected: {}'.format(theme))
players[id]["theme"] = theme
players[id]["createstep"] = 5
save_object_to_file(players[id], "players/{}.json".format(players[id]["name"]))
# main game loop. We loop forever (i.e. until the program is terminated)
while True:
if 'esp' in platform:
......@@ -261,9 +509,16 @@ while True:
if loaded_player is None:
players[id]["password"] = password_hash(players[pid]["name"], command)
players[id]["room"] = "town/tavern"
players[id]["createstep"] = 1
mud.send_message(pid, "Can you view %bold%bluecolors%reset? ")
continue
else:
if loaded_player["password"] == password_hash(players[pid]["name"], command):
players[id] = loaded_player
mud._clients[id].color_enabled = players[id]["color_enabled"]
if players[id]["createstep"]:
mud.send_message(pid, "Can you view %bold%bluecolors%reset? ")
continue
else:
players[id]["retries"] = players[id].get("retries", 0) + 1
mud.send_message(id, "Invalid Password")
......@@ -283,6 +538,8 @@ while True:
cmd_handler.parse(id, 'look', '', mud, players)
show_prompt(id)
elif players[id].get("createstep"):
handle_character_create(id, command, params)
else:
if 'esp' in platform:
collect()
......