weemud.py 37 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
#!/usr/bin/env python

"""
MudServer author: Mark Frimston - mfrimston@gmail.com

Micropython port and extensions for more protocol author: Barry Ruffner - barryruffner@gmail.com
"""

from time import sleep
from math import floor
from sys import platform
from os import listdir, remove

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()

races = {
    "Android": {
        "mods": {"dex": 2, "int": 2, "cha": -2},
        "hp": 4
    },
    "Human": {
        "mods": {},
        "hp": 4
    },
    "Kasathas": {
        "mods": {"str": 2, "wis": 2, "int": -2},
        "hp": 4
    },
    "Korasha Lashuntas": {
        "mods": {"str": 2, "cha": 2, "wis": -2},
        "hp": 4
    },
    "Damaya Lashuntas": {
        "mods": {"int": 2, "cha": 2, "con": -2},
        "hp": 4
    },
    "Shirrens": {
        "mods": {"con": 2, "wis": 2, "cha": -2},
        "hp": 6
    },
    "Vesk": {
        "mods": {"str": 2, "con": 2, "int": -2},
        "hp": 6
    },
    "Ysoki": {
        "mods": {"dex": 2, "int": 2, "str": -2},
        "hp": 2
    }
}

feats = {
"""
    Adaptive Fighting*
     Three or more combat feats Once per day as a move action, gain the benefit of a combat feat you don’t have 
    Amplified Glitch*
     Computers 3 ranks, Intimidate 3 ranks Disrupt devices, causing targets to become shaken for 1 round or more Antagonize Diplomacy 5 ranks, Intimidate 5 ranks Anger a foe, causing it to become off-target and take a −2 penalty to skill checks for 1 round or more 
    Barricade*
     Engineering 1 rank Create your own fragile cover 
    Basic Melee Weapon Proficiency*
     — No penalty to attacks with basic melee weapons 
    Advanced Melee Weapon Proficiency*
     Basic Melee Weapon Proficiency No penalty to attacks with advanced melee weapons 
    Special Weapon Proficiency*
     Basic Melee Weapon Proficiency or Small Arm Proficiency No penalty to attacks with one special weapon 
    Blind-Fight*
     — Reroll miss chances from concealment 
    Bodyguard*
     — Add a +2 bonus to an adjacent ally’s AC as a reaction 
    In Harm’s Way*
     Bodyguard Take the damage of a successful attack against an adjacent ally 
    Cleave*
     Str 13, base attack bonus +1 Make an additional melee attack if the first one hits 
    Great Cleave*
     Str 13, Cleave, base attack bonus +4 Make an additional melee attack after each melee attack that hits Climbing Master Athletics 5 ranks Gain a climb speed equal to your base speed
    Combat Casting*
     Ability to cast 2nd-level spells +2 bonus to AC and saves against attacks of opportunity when casting spells Connection Inkling Wis 15, character level 5th, no mystic levels Gain the ability to cast minor mystic spells
    Coordinated Shot*
     Base attack bonus +1 Allies gain a +1 bonus to ranged attacks against foes you threaten 
    Deadly Aim*
     Base attack bonus +1 Take a −2 penalty to weapon attacks to deal extra damage 
    Deflect Projectiles*
     Base attack bonus +8 Spend 1 Resolve Point to attempt to avoid a ranged attack 
    Reflect Projectiles*
     Deflect Projectiles, base attack bonus +16 Spend 1 Resolve Point to attempt to redirect a ranged attack Diehard — You can spend Resolve Points to stabilize and to stay in the fight in the same round Dive for Cover*
     Base Reflex save bonus +2 Fall prone in an adjacent square to roll a Reflex save twice Diversion — Use Bluff to create a distraction so that your allies can hide 
    Drag Down*
     — When you are tripped, you can attempt to trip an adjacent foe Enhanced Resistance Base attack bonus +4 Gain damage reduction or energy resistance Extra Resolve Character level 5th Gain 2 additional Resolve Points 
    Far Shot*
     Base attack bonus +1 Reduce penalty due to range increments Fast Talk Bluff 5 ranks Baffle a potential foe, causing it to be surprised when combat begins 
    Fleet*
     — Increase your base speed
    Fusillade*
     Base attack bonus +1, 4 or more arms Make an automatic-mode attack with multiple small arms Great Fortitude — +2 bonus to Fortitude saves Improved Great Fortitude Great Fortitude, character level 5th Spend 1 Resolve Point to reroll a Fortitude save 
    Grenade Proficiency*
     — No penalty to attacks made with grenades Harm Undead Healing channel connection power, mystic level 1st Expend a spell slot for healing channel to also damage undead 
    Improved Combat Maneuver*
     Base attack bonus +1 +4 bonus to perform one combat maneuver 
    Pull the Pin*
     Improved Combat Maneuver (disarm) Perform a disarm to activate a foe’s grenade 
    Improved Critical*
     Base attack bonus +8 The DC to resist the critical effects of your critical hits increases by 2 
    Improved Feint*
     — Use Bluff to feint as a move action 
    Greater Feint*
     Improved Feint, base attack bonus +6 Foes you feint against are flat-footed for 1 round 
    Improved Initiative*
     — +4 bonus to initiative checks 
    Improved Unarmed Strike*
     — Deal more damage and threaten squares with unarmed strikes Iron Will — +2 bonus to Will saves Improved Iron Will Iron Will, character level 5th Spend 1 Resolve Point to reroll a Will save Jet Dash — Move faster when running, double height and distance when jumping 
    Kip Up*
     Acrobatics 1 rank Stand from prone as a swift action 
    Light Armor Proficiency*
     — No penalty to attack rolls while wearing light armor 
    Heavy Armor Proficiency*
     Str 13, Light Armor Proficiency No penalty to attack rolls while wearing heavy armor 
    Powered Armor Proficiency*
     Str 13, Light Armor Proficiency, Heavy Armor Proficiency, base attack bonus +5 No penalty to attack rolls while wearing powered armor Lightning Reflexes — +2 bonus to Reflex saves Improved Lightning Reflexes Lightning Reflexes, character level 5th Spend 1 Resolve Point to reroll a 
    Reflex save Lunge*
     Base attack bonus +6 Increase reach of melee attacks by 5 feet until the end of your turn Master Crafter Computers, Engineering, Life Science, Mysticism, Physical Science, or Profession 5 ranks Craft items in half the normal time Medical Expert Life Science 1 rank, Medicine 1 rank, Physical Science 1 rank Treat deadly wounds more quickly, and provide long-term care without a medical lab Minor Psychic Power Cha 11 Cast a 0-level spell as a spell-like ability 3/day Psychic Power Cha 13, Minor Psychic Power, character level 4th Cast a 1st-level spell as a spell-like ability 1/day Major Psychic Power Cha 15, Minor Psychic Power, Psychic Power, character level 7th Cast a 2nd-level spell as a spell-like ability 1/day 
    Mobility*
     Dex 13 +4 bonus to AC against attacks of opportunity from movement Agile Casting Key ability score 15, Dex 15, Mobility, caster level 4th Cast a spell at any point during movement Shot on the 
    Run*
     Dex 15, Mobility, base attack bonus +4 Make a ranged attack at any point during movement 
    Parting Shot*
     Dex 15, Mobility, Shot on the Run, base attack bonus +6 Make a single ranged attack when withdrawing Sidestep* Dex 15, Mobility or trick attack Take guarded step as a reaction when a foe misses you with melee attack 
    Improved Sidestep* Dex 17, Mobility or trick attack class feature, Sidestep Reduce penalties from Sidestep Spring Attack*
     Dex 15, Mobility, base attack bonus +4 Move before and after a melee attack 
    Multi-Weapon Fighting*
     — Reduce the penalty for full attacks when using multiple small arms or operative melee weapons 
    Mystic Strike*
     Ability to cast spells Melee and ranged attacks count as magic 
    Nimble Moves*
     Dex 15 Ignore 20 feet of difficult terrain when you move 
    Opening Volley*
     — +2 bonus to a melee attack against a target you damaged with a ranged attack 
    Penetrating Attack*
     Base attack bonus +12 Reduce enemy's DR and energy resistance against your weapons by 5 Penetrating Spell Ability to cast 4th-level spells Reduce enemy's DR and energy resistance against your spells by 5 
    Quick Draw*
     Base attack bonus +1 Draw a weapon as a swift action Skill Focus — +3 insight bonus to one skill Skill Synergy — Gain two new class skills or a +2 insight bonus to those skills Sky Jockey Piloting 5 ranks Make jetpacks, vehicles, and starships go faster 
    Slippery Shooter*
     Dex 15, base attack bonus +6 +3 bonus to AC against attacks of opportunity when making ranged attacks 
    Small Arm Proficiency*
     — No penalty to attacks with small arms 
    Longarm Proficiency*
     Small Arm Proficiency No penalty to attacks with longarms 
    Heavy Weapon Proficiency*
     Str 13, Longarm Proficiency, Small Arm Proficiency No penalty to attacks with heavy weapons 
    Special Weapon Proficiency*
     Basic Melee Weapon Proficiency or Small Arm Proficiency No penalty to attacks with one special weapon 
    Sniper Weapon Proficiency*
     — No penalty to attacks with sniper weapons Spell Focus Ability to cast spells, character level 3rd DCs of spells you cast increase Spell Penetration — +2 bonus to caster level checks to overcome SR Greater Spell Penetration Spell Penetration Additional +2 bonus to caster level checks to overcome SR Spellbane Unable to cast spells or use spell-like abilities +2 insight bonus to saving throws against spells and spell-like abilities 
    Spry Cover*
     Base attack bonus +1 Covering fire grants a +4 bonus to an ally’s Acrobatics check to tumble 
    Stand Still*
     — Make an attack of opportunity to stop a foe’s movement 
    Improved Stand Still*
     Stand Still +4 bonus to melee attacks with Stand Still
    Step Up*
     Base attack bonus +1 Take a guarded step as a reaction to an adjacent foe moving Step Up 
    and Strike*
     Dex 13, Step Up, base attack bonus +6 Make an attack of opportunity as part of Step Up 
    Suppressive Fire*
     Base attack bonus +1, proficiency with heavy weapons Provide covering fire or harrying fire in an area
    Strike Back*
     Base attack bonus +1 Ready an action to make a melee attack against a foe with reach Swimming Master Athletics 5 ranks Gain a swim speed equal to your base speed Technomantic Dabbler Int 15, character level 5th, no levels in technomancer Gain the ability to cast minor technomancer spells Toughness — +1 Stamina Point per character level and other bonuses 
    Unfriendly Fire*
     Bluff 5 ranks Trick an attacker into shooting at another enemy adjacent to you Veiled Threat Cha 15, Intimidate 1 rank Intimidated foe doesn’t become hostile 
    Weapon Focus*
     Proficiency with selected weapon type +1 bonus to attack rolls with selected weapon type 
    Versatile Focus*
     Weapon Focus +1 bonus to attack rolls with all weapon types you are proficient with 
    Weapon Specialization*
     Character level 3rd, proficiency with selected weapon type Deal extra damage with selected weapon type 
    Versatile Specialization*
     Weapon Specialization, character level 3rd Deal extra damage with all weapon types you are proficient with
"""
}

themes = {
    "Ace Pilot": {
        "mods": {"dex": 1}
    },
    "Bounty Hunter": {
        "mods": {"con": 1}
    },
    "Icon": {
        "mods": {"cha": 1}
    },
    "Mercenary": {
        "mods": {"str": 1}
    },
    "Outlaw": {
        "mods": {"dex": 1}
    },
    "Priest": {
        "mods": {"wis": 1}
    },
    "Scholar": {
        "mods": {"int": 1}
    },
    "Spacefarer": {
        "mods": {"con": 1}
    },
    "Xenoseeker": {
        "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": {
        "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,
        "hp": 6
    },
    "Mechanic": {
        "skills": ["Athletics", "Perception", "Computers", "Physical Science", "Engineering", "Piloting", "Medicine", "Profession"],
        "keyability": "int",
        "proficiencies": ["light armor", "basic melee", "grenades", "small arms"],
        "skillperlevel": 4,
        "hp": 6
    },
    "Mystic": {
        "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,
        "hp": 6
    },
    "Operative": {
        "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,
        "hp": 6
    },
    "Solarian": {
        "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,
        "hp": 7
    },
    "Soldier": {
        "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,
        "hp": 7
    },
    "Technomancer": {
        "skills": ["Computers", "Physical Science", "Engineering", "Piloting", "Life Science", "Profession", "Mysticism", "Sleight of Hand"],
        "keyability": "int",
        "proficiencies": ["light armor", "basic melee", "small arms"],
        "skillperlevel": 4,
        "hp": 5
    }
}


def get_ability_mod(id, ability):
    ability_modifiers = [-5, -4, -4, -3, -2, -2, -1, -1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8]
    return ability_modifiers[players[id]["abilities"][ability]]

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

def show_list(id, title, singular_title, subject_list, instructions='Please choose a {} from the list by number: '):
    mud.send_message(id, "  %green+------------={}=------------+".format(title), nowrap=True)
    for idx, subject in enumerate(subject_list):
        mud.send_message(id, "  %%green|%%reset%%bold%%white%s%%reset%%green|" % ('{:<2}. {:<28}'.format(idx, subject),), nowrap=True)
    mud.send_message(id, "  %green+--------------------------------+", nowrap=True)

    mud.send_message(id, '   (Type %boldhelp [{}]%reset for details)\r\n'.format(singular_title))
    mud.send_message(id, instructions.format(singular_title))

def get_base_abilities(id):
    base = {"str": 10, "dex": 10, "con": 10, "int": 10, "wis": 10, "cha": 10}
    for name, value in races[players[id]["race"]]["mods"].items():
        base[name] += value
    for name, value in themes[players[id]["theme"]]["mods"].items():
        base[name] += value
    return base

def show_skills(id):
    mud.send_message(id, "%greenEnter the number of the skill you wish to modify, 1 point will be added to that skill rank. You may not exceed the available skill points.")
    mud.send_message(id, '%greenYou can reset to the base values by typing %boldreset')
    mud.send_message(id, "  %green+--------=Skill Ranks=-------+", nowrap=True)
    for idx, skill in enumerate(classes[players[id]["class"]]["skills"]):
        skill_rank = players[id]["skills"].get(skill, 0)
        mud.send_message(id, "  %%green|%%reset%%bold%%white%s%%reset%%green|" % ('{:<2}. {:<19} {:^4}'.format(idx, skill, skill_rank),), nowrap=True)
    mud.send_message(id, "  %green+- Points: %bold{:<2}%reset%green ---------------+".format(players[id]["skillpoints"]), nowrap=True)

    mud.send_message(id, '   (Type %boldhelp [skill]%reset for details)\r\n')
    mud.send_message(id, '%greenWhen finished type %bolddone')

def show_abilities(id):
    mud.send_message(id, "%greenEnter the number of the ability you wish to modify, 1 point will be added to that ability. You may not exceed the available ability points.")
    mud.send_message(id, '%greenYou can reset to the base values by typing %boldreset')
    mud.send_message(id, "  %green+-----=Abilities=-----+", nowrap=True)
    for idx, ability in enumerate(players[id]["abilities"]):
        mud.send_message(id, "  %%green|%%reset%%bold%%white%s%%reset%%green|" % ('{}. {:<13} {:^4}'.format(idx, ability, players[id]["abilities"][ability]),), nowrap=True)
    mud.send_message(id, "  %green+- Points: %bold{:<2}%reset%green --------+".format(players[id]["abilitypoints"]), nowrap=True)

    mud.send_message(id, '   (Type %boldhelp [ability]%reset for details)\r\n')
    mud.send_message(id, '%greenWhen finished type %bolddone')

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:
            show_list(id, "Races", "race", races)
            players[id]["createstep"] = 3

    elif players[id]["createstep"] == 3:
        if command.lower().startswith("help"):
            cmd_handler.parse(id, command, params.lower().strip(), mud, players)
        if not command.isdigit() or int(command) + 1 > len(races) or int(command) < 0:
            show_list(id, "Races", "race", races)
        else:
            race = list(races)[int(command)]
            mud.send_message(id, 'Race selected: {}'.format(race))

            players[id]["race"] = race
            players[id]["createstep"] = 4
            show_list(id, "Themes", "theme", themes)
    elif players[id]["createstep"] == 4:
        if command.lower().startswith("help"):
            cmd_handler.parse(id, command, params.lower().strip(), mud, players)
        if not command.isdigit() or int(command) + 1 > len(themes) or int(command) < 0:
            show_list(id, "Themes", "theme", themes)
        else:
            theme = list(themes)[int(command)]
            mud.send_message(id, 'Theme selected: {}'.format(theme))

            players[id]["theme"] = theme
            players[id]["createstep"] = 5
            show_list(id, "Classes", "class", classes)

    elif players[id]["createstep"] == 5:
        if command.lower().startswith("help"):
            cmd_handler.parse(id, command, params.lower().strip(), mud, players)
        if not command.isdigit() or int(command) + 1 > len(classes) or int(command) < 0:
            show_list(id, "Classes", "class", classes)
        else:
            selected_class = list(classes)[int(command)]
            mud.send_message(id, 'Class selected: {}'.format(selected_class))

            players[id]["class"] = selected_class
            players[id]["createstep"] = 6
            if players[id]["race"] == "Human":
                players[id]["abilitypoints"] = 12
            else:
                players[id]["abilitypoints"] = 10
            players[id]["abilities"] = get_base_abilities(id)
            show_abilities(id)
    elif players[id]["createstep"] == 6:
        if command.lower().startswith("help"):
            cmd_handler.parse(id, command, params.lower().strip(), mud, players)
        elif command.lower().startswith("reset"):
            players[id]["abilities"] = get_base_abilities(id)
            if players[id]["race"] == "Human":
                players[id]["abilitypoints"] = 12
            else:
                players[id]["abilitypoints"] = 10
            show_abilities(id)
        elif command.lower().startswith("done"):
            if players[id]["abilitypoints"] > 0:
                mud.send_message(id, '%cyanPlease spend all available ability points.')
                show_abilities(id)
            else:
                pclass = classes[players[id]["class"]]
                class_bonuses = load_object_from_file('data/{}_bonus.json'.format(players[id]["class"].lower()))
                players[id]["baseattack"] = class_bonuses[0]["atk"]
                players[id]["fort"] = class_bonuses[0]["fort"]
                players[id]["ref"] = class_bonuses[0]["ref"]
                players[id]["will"] = class_bonuses[0]["will"]
                players[id]["maxhp"] = races[players[id]["race"]]["hp"] + pclass["hp"]
                players[id]["hp"] = players[id]["maxhp"]
                # Class SP is the same HP, so no need to store both in the classes dict
                players[id]["maxsp"] = get_ability_mod(id, "con") + pclass["hp"]
                players[id]["sp"] = players[id]["maxsp"]
                players[id]["maxrp"] = 1 + get_ability_mod(id, pclass["keyability"])
                if players[id]["maxrp"] < 1:
                    players[id]["maxrp"] = 1
                players[id]["rp"] = players[id]["maxrp"]                
                players[id]["skillpoints"] = get_ability_mod(id, 'int') + pclass["skillperlevel"]

                players[id]["createstep"] = 7
                show_skills(id)
        elif not command.isdigit() or int(command) + 1 > len(players[id]["abilities"]) or int(command) < 0:
            mud.send_message(id, '%cyanInvalid number')
            show_abilities(id)
        else:
            ability_name = list(players[id]["abilities"])[int(command)]
            if players[id]["abilities"][ability_name] >= 18:
                mud.send_message(id, '%cyanYou cannot raise an ability higher than 18 during character creation.')
            elif players[id]["abilitypoints"] > 0:
                players[id]["abilities"][ability_name] += 1
                players[id]["abilitypoints"] -= 1
            show_abilities(id)
    elif players[id]['createstep'] == 7:
        if command.lower().startswith("help"):
            cmd_handler.parse(id, command, params.lower().strip(), mud, players)
        elif command.lower().startswith("reset"):
            pclass = classes[players[id]["class"]]
            players[id]["skills"] = { }
            players[id]["skillpoints"] = get_ability_mod(id, 'int') + pclass["skillperlevel"]
            show_skills(id)
        elif command.lower().startswith("done"):
            if players[id]["skillpoints"] > 0:
                mud.send_message(id, '%cyanPlease spend all available skill points.')
                show_skills(id)
            else:
                players[id]["createstep"] = 8
                show_list(id, "Feats", "feat", feats)
        elif not command.isdigit() or int(command) + 1 > len(themes) or int(command) < 0:
            show_skills(id)
        else:
            skill_name = classes[players[id]["class"]]["skills"][int(command)]
            if players[id]["skillpoints"] > 0:
                if players[id]["skills"].get(skill_name):
                    players[id]["skills"][skill_name] += 1
                else:
                    players[id]["skills"][skill_name] = 1
                players[id]["skillpoints"] -= 1
            show_skills(id)
    elif players[id]['createstep'] == 8:
        if command.lower().startswith("help"):
            cmd_handler.parse(id, command, params.lower().strip(), mud, players)
        elif not command.isdigit() or int(command) + 1 > len(themes) or int(command) < 0:
            show_list(id, "Feats", "feat", feats)
        else:
            # skill_name = classes[players[id]["class"]]["skills"][int(command)]
            # if players[id]["skillpoints"] > 0:
            #     if players[id]["skills"].get(skill_name):
            #         players[id]["skills"][skill_name] += 1
            #     else:
            #         players[id]["skills"][skill_name] = 1
            #     players[id]["skillpoints"] -= 1
            show_list(id, "Feats", "feat", feats)
    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:
        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"
                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")
                    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)
        elif players[id].get("createstep"):
            handle_character_create(id, command, params)                
        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