Desmond  Gerber

Desmond Gerber

1619630100

Functional JavaScript: Writing a Simple Command-line Game (Part 1)

If you read my previous post on defining objects in JavaScipt using closures, I thought a working example might help. This is based on some code I wrote with my son to help him understand programming and make it a fun experience. He chose to build a simple command-line adventure, very 80s-style, where you have to escape from a maze while finding items and fighting monsters.

Firstly, we define a player object. The player has an experience level, a bag to hold items, and is carrying a weapon. Initially, the weapon is their hand — the player better not run into anything dangerous! We also define a few weapons and how powerful they are.

const character = function(who, attrib) {
    attrib = attrib || {};
    const _name = who;
    const dv = (value,def ) 
           => (typeof value === "undefined")?def:value;
    let _hp = dv( attrib.hp, 10 );
    let _level = dv( attrib.level, 1 );
    const _bag = [];
    let _weapon =  dv( attrib.weapon, "hand");

    const weapons = {
        "hand": 1,
        "Iron Sword" : 2,
        "Diamond Sword" : 5,
        "Hammer" : 2

#programming #nodejs #coding #javascript #node

Functional JavaScript: Writing a Simple Command-line Game (Part 1)