26
\$\begingroup\$

The Demo for what I have made is located here

Basically I am trying to make a self playing JavaScript baseball game with the use of no libraries.

Is there anything I could improve on in the code?

var writeDown = {
    delay: 110,
    add: null,
    div: document.getElementById('playArea'),
    log: function() {
        var args = arguments;
        if (args.length == 0) {
            args = [''];
        }
        var div = this.div;
        setTimeout(function() {
            //console.log(args[0]);
            div.innerHTML = args[0] + "<br/>" + div.innerHTML;
        }, this.delay);
        if (this.add == null) {
            this.add = this.delay;
        }
        this.delay += this.add;
    },

    updateDiv: function(msg, div) {
        setTimeout(function() {
            //console.log(msg, div);
            div.innerHTML = msg;
        }, this.delay);
    },

    updateDiv_delay: function(msg, div) {
        setTimeout(function() {
            document.getElementById(div).innerHTML = msg;
        }, this.delay);
    },

    updateDiv_color: function(color, div) {
        setTimeout(function() {
            //console.log(color, div);
            document.getElementById(div).style.background = color;
        }, this.delay);
    }
}


var Diamond = function(d_name, d_id) {

    var name = d_name;
    var diamond = document.getElementById(d_id);

    var bases = {
        first: false,
        second: false,
        third: false,
        home: false
    };

    var players = {
        first: false,
        second: false,
        third: false,
        home: false
    };

    this.clear = function() {
        bases = {
            first: false,
            second: false,
            third: false,
            home: false
        };
        players = {
            first: false,
            second: false,
            third: false,
            home: false
        };
        this.updateBases();
        writeDown.updateDiv('', diamond);
    }

    this.onBase = function(base_amt, PlayerName) {
        var return_runs = 0;
        switch (base_amt) {
        case 0:
            return 0;
            break;
        case 1:
            if (bases.first) {
                if (bases.second) {
                    if (bases.third) {
                        writeDown.log(name + ": BASES LOADED, " + players.third + " scored");
                        return_runs += 1;
                    }
                    else {
                        writeDown.log(name + ": BASES LOADED");
                        bases.third = true;
                    }
                    players.third = players.second;
                    players.second = players.first;
                    players.first = PlayerName;
                }
                else {
                    writeDown.log(name + ": Man on 1st and 2nd");
                    players.second = players.first;
                    players.first = PlayerName;
                    bases.second = true;
                }
            }
            else {
                writeDown.log(name + ": Man on 1st");
                players.first = PlayerName;
                bases.first = true;
            }
            break;
        case 2:
            if (bases.first) {
                writeDown.log(name + ": Man on 2nd, and Third");
                bases.first = false;
                if (bases.third) return_runs += 1;
                bases.third = true;
            }
            if (bases.second) {
                return_runs += 1;
                if (bases.third) {
                    writeDown.log(name + ": Man on 2nd, 2 runs scored (" + players.second + ", " + players.third + ")");
                    bases.third = false;
                    return_runs += 1;
                }
                else {
                    writeDown.log(name + ": Man on 2nd, run scored (" + players.second + ")");
                }
            }
            if (bases.third) {
                return_runs += 1;
                bases.third = false;
                writeDown.log(name + ": Man on 2nd, run scored (" + players.third + ")");
            }
            else {
                writeDown.log(name + ": Man on 2nd");
                bases.second = true;
            }
            players.third = players.first;
            players.second = PlayerName;
            players.first = null;
            break;
        case 3:
            if (bases.first) {
                writeDown.log(name + ": " + players.first + " Scored from 1st");
                bases.first = false;
                return_runs += 1;
            }
            if (bases.second) {
                writeDown.log(name + ": " + players.second + " Scored from 2nd");
                bases.second = false;
                return_runs += 1;
            }
            if (bases.third) {
                writeDown.log(name + ": " + players.third + " Scored from 3rd");
                return_runs += 1;
            }
            else {
                writeDown.log(name + ": Man on 3rd");
                bases.third = true;
            }
            players.third = PlayerName;
            players.second = null;
            players.first = null;
            break;
        case 4:
            if (bases.first) {
                writeDown.log(name + ": " + players.first + " Scored from 1st");
                bases.first = false;
                return_runs += 1;
            }
            if (bases.second) {
                writeDown.log(name + ": " + players.second + " Scored from 2nd");
                bases.second = false;
                return_runs += 1;
            }
            if (bases.third) {
                writeDown.log(name + ": " + players.third + " Scored from 3rd");
                bases.third = false;
                return_runs += 1;
            }
            players.third = null;
            players.second = null;
            players.first = null;
            writeDown.log(name + ": " + PlayerName + " Scored from home");
            return_runs += 1;
            break;
        }

        var man_on = "",
            base_names = ['first', 'second', 'third'];

        for (var i = 0; i < 4; i++) {
            if (players[base_names[i]] != null && players[base_names[i]]) {
                man_on += players[base_names[i]] + " is on " + base_names[i] + " base <br/>";
            }
        }

        writeDown.updateDiv(man_on, diamond);
        this.updateBases();
        return return_runs;
    }

    this.updateBases = function() {
        for (base in bases) {
            if (bases[base] == true) {
                writeDown.updateDiv_color('#F00', base);
            }
            else {
                writeDown.updateDiv_color('#AAA', base);
            }
        }
    }


    this.playGame = function(TeamA, TeamB, innings) {
        var score_div = document.getElementById('score');
        writeDown.updateDiv(TeamA.name + ": <span id='" + TeamA.name + "'>" + TeamA.getScore() + "</span><br/>" + TeamB.name + ": <span id='" + TeamB.name + "'>" + TeamB.getScore() + "</span><hr>" + "Outs: <span id='outs'>0</span><br/>" + "Inning: <span id='inning'>1</span>", score_div);

        for (var i = 0; i < innings; i++) {
            writeDown.log("<br/><b>INNING " + (i + 1) + "</b><br/>");
            writeDown.updateDiv_delay("Top of " + (i + 1), 'inning');
            if (TeamA.teamUp()) {
                writeDown.updateDiv_delay("Bottom of " + (i + 1), 'inning');
                writeDown.log(TeamA.name + " are out <br/>");
                this.clear();
                TeamA.resetOuts();
                writeDown.log("");
                if (TeamB.teamUp()) {
                    writeDown.log(TeamB.name + " are out<br/><br/>");
                    this.clear();
                    TeamB.resetOuts();
                    writeDown.log("");
                }
            }
        }
    }

}

var Player = function(pitcher, name) {
    var name = (name == undefined) ? "Nothing" : name;
    var balls = 0;
    var strikes = 0;

    this.getName = function() {
        return name;
    }

    this.atBat = function() {
        var pitch = pitcher.show_pitch();
        var random = Math.floor(Math.random() * 1000);
        var swing_rate = 500 - (75 * strikes);

        if (random < swing_rate) { //swing
            strikes += 1;
            writeDown.log(name + " swung and missed.");
            writeDown.log(name + " has " + strikes + " strikes.");
            if (strikes >= 3) {
                strikes = 0;
                balls = 0;
                writeDown.log(name + " struck out");
                return {
                    out: 1,
                    type: 0
                };
            }
        }
        else if (random < 880) { //wait for pitch
            writeDown.log(name + " watches the pitch.");
            if (pitch == "Strike") {
                strikes += 1;
                writeDown.log(name + " has " + strikes + " strikes.");
                if (strikes >= 3) {
                    strikes = 0;
                    balls = 0;
                    writeDown.log(name + " struck out");
                    return {
                        out: 1,
                        type: 0
                    };
                }
            }
            if (pitch == "Ball") {
                balls += 1;
                writeDown.log(name + " has " + balls + " balls.");
                if (balls >= 4) {
                    balls = 0;
                    strikes = 0;
                    writeDown.log(name + " has been walked");
                    return {
                        out: 0,
                        type: 1
                    };
                }
            }
        }
        else if (random <= 1000) { //hit ball
            balls = 0;
            strikes = 0;
            var hit = "Single";
            if (random > 940 && random < 970) {
                hit = "Double";
            }
            else if (random >= 970 && random < 995) {
                hit = "Triple";
            }
            else if(random >= 995){
                hit = "Homerun";
            }
            writeDown.log(name + " hit a " + hit);
            var hit_type = 1;
            if (hit == "Double") hit_type = 2;
            if (hit == "Triple") hit_type = 3;
            if (hit == "Homerun") hit_type = 4;
            writeDown.log(name + " going to base");
            return {
                out: 0,
                type: hit_type
            };
        }

        //writeDown.log(name + " waiting for next pitch");
        return this.atBat();
    }
}

var Pitcher = function(team) {
    var types = ["Ball", "Strike"];
    var Team = team;
    this.show_pitch = function() {
        var random = Math.floor(Math.random() * (types).length);
        writeDown.log();
        writeDown.log(Team.name + " pitcher threw the ball.");
        return types[random];
    }
}


var Team = function() {

    var amt_of_players = 9;
    var players = [];
    var pitcher = new Pitcher(this);
    var otherPitcher = null;
    var outs = 0;
    var score = 0;
    var stadium = null;
    var player_up_to = 0;

    this.name = "Nobody's";

    this.createTeam = function(TeamName, Opponent, Diamond) {
        stadium = Diamond;
        otherPitcher = Opponent.getPitcher();
        this.name = (TeamName == undefined) ? "Nothing" : TeamName;
        for (var i = 0; i < amt_of_players; i++) {
            players[i] = new Player(otherPitcher, "Player " + (i + 1) + " on " + this.name);
        }
        return this;
    }

    this.teamUp = function() {
        for (var i = player_up_to; i < players.length; i++) {
            var atBat = players[i].atBat();
            outs += atBat.out;
            score += stadium.onBase(atBat.type, players[i].getName());
            writeDown.updateDiv_delay(score, this.name);
            writeDown.updateDiv_delay(outs, 'outs');
            if (outs >= 3) {
                player_up_to = (i + 1) % players.length; //start with next player;
                return true;
            }
        }

        if (outs >= 3) {
            player_up_to = 0;
            return true;
        }
        else {
            player_up_to = 0;
            return this.teamUp();
        }
    }

    this.getScore = function() {
        return score;
    }

    this.resetOuts = function() {
        outs = 0;
        writeDown.updateDiv_delay(outs, 'outs');
    }

    this.getPitcher = function() {
        return pitcher;
    }
}

var TeamA = new Team();
var TeamB = new Team();
var Stadium = new Diamond("Citi Field", 'move');

TeamA.createTeam("Yankees", TeamB, Stadium);
TeamB.createTeam("Mets", TeamA, Stadium);

Stadium.playGame(TeamA, TeamB, 9);

writeDown.log("GAME OVER!");
\$\endgroup\$
  • 2
    \$\begingroup\$ I'm strangely conflicted, the architect in me wants to say choosing to use zero frameworks is reinventing the wheel to the max and you don't get to leverage a hammer that's gone through 500 design phases to hammer nails, that you have your hammer that was only built in a couple phases. But then the other side of me sees the value of reaching for the maximum for performance since this is a game we're talking about. \$\endgroup\$ – Chris Marisic May 26 '11 at 17:32
  • \$\begingroup\$ Is the only way batters can get out is by striking out? I didn't see any ground outs, fly outs, or double plays for that matter. I'm not a javascript guy, but I wrote something similar this weekend in python. bitbucket.org/jgrigonis/baseball_simulator/overview I didn't take it as far as you, so far I just have the game class that handles game state changing events. \$\endgroup\$ – jgritty Apr 30 '12 at 21:07
  • \$\begingroup\$ Well done. Just one thing...if the home team (second team listed) is ahead when it comes to the bottom of the 9th, that team does not hit. They already won. \$\endgroup\$ – dberm22 Sep 6 '14 at 2:23
13
\$\begingroup\$
var writeDown = {
    delay: 110,
    add: null,
    div: document.getElementById('playArea'),
    log: function() {
        var args = arguments;
        if (args.length == 0) {
            args = [''];
        }
        var div = this.div;
        setTimeout(function() {
            //console.log(args[0]);
            div.innerHTML = args[0] + "<br/>" + div.innerHTML;
        }, this.delay);

What are you doing with the arguments? You seem to be taking a roundabout method to have log optionally take a single parameter. But it's not clear why logging without any arguments would make any sense.

        if (this.add == null) {
            this.add = this.delay;
        }
        this.delay += this.add;

You've done this by scheduling a series of events to happen later and later from now. That's kinda clever but not something that you should do in a JavaScript context. A better way would be to structure your code so that a single function is called repeatedly to perform logic so that the processing is ongoing rather than done all upfront.

    },

    updateDiv: function(msg, div) {
        setTimeout(function() {
            //console.log(msg, div);
            div.innerHTML = msg;
        }, this.delay);
    },

    updateDiv_delay: function(msg, div) {
        setTimeout(function() {
            document.getElementById(div).innerHTML = msg;
        }, this.delay);
    },

These very similar functions as well as the similar code above is begging to be combined.

    updateDiv_color: function(color, div) {
        setTimeout(function() {
            //console.log(color, div);
            document.getElementById(div).style.background = color;
        }, this.delay);
    }
}


var Diamond = function(d_name, d_id) {

    var name = d_name;
    var diamond = document.getElementById(d_id);

    var bases = {
        first: false,
        second: false,
        third: false,
        home: false
    };

When elements have a sequential interpretation, you are usually better of using numbers rather than names. Bases should be an array not an object.

    var players = {
        first: false,
        second: false,
        third: false,
        home: false
    };

Instead of storing players like this, put everything in the bases array. Use null or false for no player, and the player's name otherwise.

    this.clear = function() {
        bases = {
            first: false,
            second: false,
            third: false,
            home: false
        };
        players = {
            first: false,
            second: false,
            third: false,
            home: false
        };
        this.updateBases();
        writeDown.updateDiv('', diamond);
    }

You should use the clear function inside this constructor so that you don't have to duplicate its contents.

    this.onBase = function(base_amt, PlayerName) {

Either use variable_like_this or VariablesLikeThis or variablesLikeThis. Avoid mixing styles. Also base_amt isn't really clear what it means.

        var return_runs = 0;
        switch (base_amt) {
        ...

Your code to determine the new bases and runs is way too complicated. Your code should look something like:

 for each base
      if man on base, move forward base_amt places
             if move is past home, score a run
             otherwise set new position

You should never need to write such repetitive code as you wrote above.

        var man_on = "",
            base_names = ['first', 'second', 'third'];

        for (var i = 0; i < 4; i++) {
            if (players[base_names[i]] != null && players[base_names[i]]) {
                man_on += players[base_names[i]] + " is on " + base_names[i] + " base <br/>";
            }
        }

If you take my advice about using arrays instead of objects for keeping track of bases this code will be much simpler.

        writeDown.updateDiv(man_on, diamond);
        this.updateBases();
        return return_runs;
    }

    this.updateBases = function() {
        for (base in bases) {
            if (bases[base] == true) {

Don't == true, just use if(bases[base]

                writeDown.updateDiv_color('#F00', base);
            }
            else {
                writeDown.updateDiv_color('#AAA', base);
            }
        }
    }


    this.playGame = function(TeamA, TeamB, innings) {
        var score_div = document.getElementById('score');
        writeDown.updateDiv(TeamA.name + ": <span id='" + TeamA.name + "'>" + TeamA.getScore() + "</span><br/>" + TeamB.name + ": <span id='" + TeamB.name + "'>" + TeamB.getScore() + "</span><hr>" + "Outs: <span id='outs'>0</span><br/>" + "Inning: <span id='inning'>1</span>", score_div);

        for (var i = 0; i < innings; i++) {
            writeDown.log("<br/><b>INNING " + (i + 1) + "</b><br/>");
            writeDown.updateDiv_delay("Top of " + (i + 1), 'inning');
            if (TeamA.teamUp()) {

As far as I can tell teamUp never returns false. Its also deceiving because I'd expect something like that in an if to be answering a question not running a complete half-inning. Neither the name nor how it's used hint that the function does that.

                writeDown.updateDiv_delay("Bottom of " + (i + 1), 'inning');
                writeDown.log(TeamA.name + " are out <br/>");
                this.clear();
                TeamA.resetOuts();
                writeDown.log("");
                if (TeamB.teamUp()) {
                    writeDown.log(TeamB.name + " are out<br/><br/>");
                    this.clear();
                    TeamB.resetOuts();
                    writeDown.log("");
                }
            }
        }
    }

}

var Player = function(pitcher, name) {
    var name = (name == undefined) ? "Nothing" : name;
    var balls = 0;
    var strikes = 0;

    this.getName = function() {
        return name;
    }

    this.atBat = function() {
        var pitch = pitcher.show_pitch();
        var random = Math.floor(Math.random() * 1000);
        var swing_rate = 500 - (75 * strikes);

        if (random < swing_rate) { //swing
            strikes += 1;
            writeDown.log(name + " swung and missed.");
            writeDown.log(name + " has " + strikes + " strikes.");
            if (strikes >= 3) {
                strikes = 0;
                balls = 0;
                writeDown.log(name + " struck out");
                return {
                    out: 1,
                    type: 0
                };
            }
        }
        else if (random < 880) { //wait for pitch
            writeDown.log(name + " watches the pitch.");
            if (pitch == "Strike") {
                strikes += 1;
                writeDown.log(name + " has " + strikes + " strikes.");
                if (strikes >= 3) {
                    strikes = 0;
                    balls = 0;
                    writeDown.log(name + " struck out");
                    return {
                        out: 1,
                        type: 0
                    };
                }
            }
            if (pitch == "Ball") {
                balls += 1;
                writeDown.log(name + " has " + balls + " balls.");
                if (balls >= 4) {
                    balls = 0;
                    strikes = 0;
                    writeDown.log(name + " has been walked");
                    return {
                        out: 0,
                        type: 1
                    };
                }
            }

You have code checking for strike outs in two places. You should move that code out of the if(random) block so that it can be shared.

        }
        else if (random <= 1000) { //hit ball
            balls = 0;
            strikes = 0;
            var hit = "Single";
            if (random > 940 && random < 970) {
                hit = "Double";
            }
            else if (random >= 970 && random < 995) {
                hit = "Triple";
            }
            else if(random >= 995){
                hit = "Homerun";
            }
            writeDown.log(name + " hit a " + hit);
            var hit_type = 1;
            if (hit == "Double") hit_type = 2;
            if (hit == "Triple") hit_type = 3;
            if (hit == "Homerun") hit_type = 4;
            writeDown.log(name + " going to base");
            return {
                out: 0,
                type: hit_type
            };
        }

        //writeDown.log(name + " waiting for next pitch");
        return this.atBat();
    }
}

This function would be simpler if you separated out the logic deciding whether it was a strike/ball/single/double/triple/home run into a separate function and just decided what the consequences would be.

var Pitcher = function(team) {
    var types = ["Ball", "Strike"];
    var Team = team;
    this.show_pitch = function() {
        var random = Math.floor(Math.random() * (types).length);
        writeDown.log();
        writeDown.log(Team.name + " pitcher threw the ball.");
        return types[random];
    }
}


var Team = function() {

    var amt_of_players = 9;
    var players = [];
    var pitcher = new Pitcher(this);
    var otherPitcher = null;
    var outs = 0;
    var score = 0;
    var stadium = null;
    var player_up_to = 0;

    this.name = "Nobody's";

    this.createTeam = function(TeamName, Opponent, Diamond) {
        stadium = Diamond;
        otherPitcher = Opponent.getPitcher();
        this.name = (TeamName == undefined) ? "Nothing" : TeamName;
        for (var i = 0; i < amt_of_players; i++) {
            players[i] = new Player(otherPitcher, "Player " + (i + 1) + " on " + this.name);
        }
        return this;
    }

Passing Opponent is slightly odd here. It implies that a team can only have a single opponent which isn't true to how teams work.

    this.teamUp = function() {
        for (var i = player_up_to; i < players.length; i++) {
            var atBat = players[i].atBat();
            outs += atBat.out;
            score += stadium.onBase(atBat.type, players[i].getName());
            writeDown.updateDiv_delay(score, this.name);
            writeDown.updateDiv_delay(outs, 'outs');
            if (outs >= 3) {
                player_up_to = (i + 1) % players.length; //start with next player;
                return true;
            }
        }

        if (outs >= 3) {
            player_up_to = 0;
            return true;
        }
        else {
            player_up_to = 0;
            return this.teamUp();
        }
    }

    this.getScore = function() {
        return score;
    }

    this.resetOuts = function() {
        outs = 0;
        writeDown.updateDiv_delay(outs, 'outs');
    }

    this.getPitcher = function() {
        return pitcher;
    }
}

var TeamA = new Team();
var TeamB = new Team();
var Stadium = new Diamond("Citi Field", 'move');

TeamA.createTeam("Yankees", TeamB, Stadium);
TeamB.createTeam("Mets", TeamA, Stadium);

Stadium.playGame(TeamA, TeamB, 9);

writeDown.log("GAME OVER!");
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ @Winston, how would you do the log? \$\endgroup\$ – Naftali aka Neal May 27 '11 at 5:44
  • \$\begingroup\$ @Winston and the only reason i need to pass the Opponent is because my Player objects need to know who the opposing pitcher is, how else can i do it? \$\endgroup\$ – Naftali aka Neal May 27 '11 at 5:48
  • \$\begingroup\$ @Neal, re: log in terms of dealing with arguments or in terms of your ever-building arrays? \$\endgroup\$ – Winston Ewert May 27 '11 at 13:36
  • \$\begingroup\$ @Neal, I'd pass the pitcher as an argument to your teamUp method. \$\endgroup\$ – Winston Ewert May 27 '11 at 13:37
  • \$\begingroup\$ @Winston, my intention was for each team to have their own pitcher, so the opposite team has to know the opposing pitcher \$\endgroup\$ – Naftali aka Neal May 27 '11 at 14:37
5
\$\begingroup\$

Javascript is not my primary language, and neither am I game a programmer. With that being said this is mostly pseudo-codeish way as to how I would structure the game loop

var game = Coaches.StartGame()

while(game.IsPlaying)
{
    var pitcher = game.CurrentPitcher;
    var batter = game.CurrentBatter;


    var ball = pitcher.Pitch();
    var swing = batter.HandlePitch(ball);

    var decision = Umpire.HandleSwing(swing);

    var isInningOver = Umpire.CallInning(decision, game);

    if(isInningOver)
    {
        var isGameOver = Umpire.CallGame(decision, game);

        if(isGameOver)
        {
            game = Umpire.EndGame(game);
        }
        else
        {
            game = Coaches.AdvaceInning(game);
        }
    }
    else
    {    
        var field = Coaches.SendBaseRunners(decision, game)
        game = Umpire.Advance(field);   
        //theoretically at this point you could need to check whether game/inning ended
        //from base runners getting thrown out if you want to support that 
        game = Coaches.NextBatter(game);
    }
}

Following this you have coaches starting a game and fielding players, with the Umpire affiliating the game.

This allow will allow you to have the logic of the game without any single responsibility principle violations that none of the methods I've shown above would ever need to change for any reason other than their specific logic.

This is different from your current setup where there is shared responsibility such as the atBat method that is both scoring the bat outcome and scoring the game.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Other than replacing your while loop with a window.setTimeout() loop (to not cause the "this script is taking too long" popup), this is exactly how I would do it. +1 \$\endgroup\$ – Bill Barry Apr 30 '12 at 22:17
  • \$\begingroup\$ @BillBarry thanks for the feedback, I'm glad to see my thoughts were on track. I've never done any programming like this in JS personally so that input about the setTimeout would never have entered my mind until I would likely have gotten that unresponsive warning and went digging. \$\endgroup\$ – Chris Marisic May 2 '12 at 18:02
2
\$\begingroup\$

biggest thing thats going to make a difference to your programming style / quality from the looks of it :- functions

break the code up into a lot more little useful functions. A lot of the awkwardness of the code is because you haven't done this.

look for the repeated code / code with the same structure but slight variations, look at how you could wrap it up in a little function.

in programming terms there's a concept called levels of perspective. there are 3 levels, conceptual / specification / implementation ( I wrote something about it here http://designingcode.blogspot.com/2006/12/its-matter-of-perspective.html)

basically you are mixing specification with implementation and it makes the code a bit messy.

so

yhe code should look something like this (perhaps) at the specification perhaps:-

if( pitch == pitches.BALL)    // or more probably as part of a switch/case
{
   if( this.reachedBallLimit() )
   {
       this.walk();
   }

}
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Bearing in mind that this post is more than seven years old, there are zombies I should be spending my time on instead of this, and you have likely learned much about JavaScript since then(Edit: it appears you have a gold badge for JS on SO so it seems like you have learned a lot), there is something that I feel should be mentioned that hasn't already.... For posterity.

As this post explains, the methods should be declared on the prototypes instead of in the constructor functions. That way the memory usage will be dramatically less.

Take for example the constructor function for Player - it can be simplified to the following, with the variables declared inside set on this.

var Player = function(pitcher, name) {
    this.name = (name == undefined) ? "Nothing" : name;
    this.balls = 0;
    this.strikes = 0;
}

Then add the methods on the prototype:

Player.prototype.getName = function() {
    return this.name;
}
Player.prototype.atBat = function() {
    ...

While there are only two Player objects it would still be beneficial to do this, in order to reduce memory consumption.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.