Back to Parent

Main Game Logic
var inheritsFrom = function(child, parent) {
    child.prototype = Object.create(parent.prototype);
}

var Crop = function($farm) {
    this.wet = 100; //0-100

    this.mature = 0; //cycles to maturity

    this.maxMature = 40;
    this.stage = 0;
    this.$farm = $farm;
};

//called once every updatejjj

Crop.prototype.age = function() {
    if (this.wet == 1) {
        this.$farm.find('.targetmessage').html('Dried out!');
        this.$farm.removeClass('harvest').addClass('dirt');
        this.wet = 0;
        this.wet = 0;
    } else if (this.wet > 1) {
        this.wet -= 0.7;
        this.mature += 1;
        var progressWidth = (this.mature/this.maxMature)*50+50*(this.stage);
        if (this.stage > 1) progressWidth = (this.mature/this.maxMature)*100;
        if (this.stage > 2) progressWidth = 0;
        this.$farm.find('.progressbar').css('width', progressWidth + '%');
        if (this.mature >= this.maxMature) {
            this.mature = 0;
            this.stage++;
            console.log("stage "+this.stage);
            if (this.stage == 2) {
                console.log("TO STAGE 2");
                //harvest time?

                this.$farm.addClass('harvest');
                this.$farm.find('.targetmessage').html('Harvest Now!');
            } else if (this.stage == 3) {
                console.log("TO STAGE 3");
                this.$farm.find('.targetmessage').html('Spoiled!');
                this.$farm.removeClass('harvest').addClass('dirt');
                this.wet = 0;
            }
        }
    }
}

Crop.prototype.water = function() {
    if (this.wet && this.stage < 3)
        this.wet = Math.min(this.wet+4, 100);
}

Crop.prototype.display = function() {
    //correct image

    var state = (this.wet == 0) ? 'dead' : (this.wet < 50 ? 'dry' : 'normal');
    if (this.wet == 50) this.$farm.find('.targetmessage').html('Water Me!');
    this.$farm.find('.target').attr('src', 'img/' + this.images[state][Math.min(2,this.stage)]);
    this.$farm.find('.waterbar').css('width', (this.wet*3.2)+'px');
}

var Tomato = function($farm) {
    Crop.apply(this, [$farm]);
    this.price = 10;
    this.sellPrice = 50;
    this.images = {
        normal: ['growtomato1.png.jpg','growtomato2.png.jpg','growtomato3.png.jpg'],
        dry: ['watermetomato1.png.jpg','watermetomato2.png.jpg','watermetomato3.png.jpg'],
        dead: ['deadtomato1.png.jpg','deadtomato2png.jpg','deadtomato3.png.jpg']
    };
}
inheritsFrom(Tomato, Crop);

var Oat = function($farm) {
    Crop.apply(this, [$farm]);
    this.price = 25;
    this.sellPrice = 70;
    this.maxmature = 60;
    this.images = {
        normal: ['growoat1.png.jpg','growoat2rect.jpg','growoat3rect.jpg'],
        dry: ['watermeoat1.png.jpg','watermeoat2.png.jpg','watermeoat3.png.jpg'],
        dead: ['deadoat2rect.jpg','deadoat2rect.jpg','deadoat3rect.jpg']
    };
}
inheritsFrom(Oat, Crop);

var Peach = function($farm) {
    Crop.apply(this, [$farm]);
    this.price = 110;
    this.sellPrice = 250;
    this.maxMature = 150;
    this.images = {
        normal: ['growpeach1.jpg','growpeach2.jpg','growpeach3.jpg'],
        dry: ['drypeachrect1.jpg','drypeachrect2.jpg','drypeachrect3.jpg'],
        dead: ['deadpeachrect.jpg','deadpeach2rect.jpg','deadpeach3rect.jpg']
    };
}
inheritsFrom(Peach, Crop);
var Farm = function(parent) {
    this.crop = null;
    this.$el = $('<div class="farm dirt"></div>');
    this.money = 50;
    console.log(this.$el);
    parent.append(this.$el);
    this.$el.append('<img src="img/dirt.png" class="target" />' + 
        '<div class="targetmessage"></div>' + 
        '<div class="progressbar"></div>' + 
        '<div class="waterbar"></div>')
    .append('<div class="menu">' + 
        '<div class="menu-left"><img src="img/oatspreview.PNG" /></div>' + 
        '<div class="menu-middle"><img src="img/tomatopreview.PNG" /></div>' + 
        '<div class="menu-right"><img src="img/peachpreview.PNG" /></div>' + 
    '</div>')
    .append('<div class="plough"><img src="img/hoe.jpg" /></div>')
    .append('<div class="harvest-button"><img src="img/harvest.png" /></div>')
    .append('<div class="money">$'+this.money.toFixed(2)+'</div>');
};

Farm.prototype.age = function() {
    if (this.crop != null) {
        this.crop.age()
        this.crop.display(this.$el.find('.target'), this.$el.find('.waterbar'));
    }
};

Farm.prototype.water = function() {
    if (this.crop != null) {
        this.crop.water();
    }
}

Farm.prototype.plant = function(crop) {
    if (this.money >= crop.price) {
        this.money -= crop.price;
        this.countMoney();
        this.crop = crop;
        this.$el.removeClass('plowed').find('.menu').removeClass('seed');
        this.crop.display(this.$el.find('.target'), this.$el.find('.waterbar'));
    } else {
        this.$el.find('.money').css('color','red');
        var obj = this;
        setTimeout(function() {
            obj.$el.find('.money').css('color','white');
        }, 500);
    }
}

Farm.prototype.countMoney = function() {
    this.$el.find('.money').html('$' + this.money.toFixed(2));
}
var Game = function() {
    this.farms = [];
    for (var i = 0; i < settings.numPlayers; i++) {
        this.farms.push(new Farm($("#farms")));
    }
    this.header = new Header($("#header"));
    this.inputBuffer = {};
    this.inMessage = false;
    this.truck = new Truck($("#truck"));
    console.log(this.truck);
    this.time = 180;
    this.countMoney();
    $("#countdown").html("Time: "+this.time.toFixed(1));
    this.message("Press any key to begin!");
    var obj = this;
    $(window).keypress(function() {
        $(window).unbind();
        obj.start();
    });
}

Game.prototype.message = function(text) {
    $("#message").html(text).css('display', 'block');
    $("#message-bg").css('opacity', '0.5').css('display', 'block');
}

Game.prototype.endMessage = function() {
    $("#message").css('display', 'none');
    $("#message-bg").css('opacity', '0').css('display', 'none');
}

Game.prototype.start = function() {
    var obj = this;
    this.endMessage();
    $(window).keypress(function(event) {
        obj.input(event.which);
    });

    var gameInterval = setInterval(function() {
        obj.farms[obj.header.activeFarm()].water();
        for (var i = 0; i < obj.farms.length; i++) {
            obj.farms[i].age();
        }
        obj.time = Math.max(0, Math.round(obj.time*10 - 1)/10);
        if (obj.time == 0) {
            $(window).unbind();
            clearInterval(gameInterval);
            var maxPlayer = 0;
            var maxScore = 0;
            for (var i = 0; i < 4; i++) {
                if (obj.farms[i].money > maxScore) {
                    maxScore = obj.farms[i].money;
                    maxPlayer = i+1;
                }
            }
            obj.message("Time's Up!<br/>Group Score: " + obj.countMoney()
                + "<br/>Player " + maxPlayer + " has high score.<br/>" + 
                "Press any key to restart."
            );
            setTimeout(function() {
                $(window).keypress(function() {
                    $(window).unbind();
                    $(window).keypress(function() {
                        location.reload();
                    });
                });
            }, 2000);
        }
        $("#countdown").html("Time: " + obj.time.toFixed(1));
    }, 100);
}

Game.prototype.middle = function(farmIndex) {
    var f = this.farms[farmIndex];
    var $farm = f.$el;
    if ($farm.is('.dirt')) {
        //ploughing

        f.crop = null;
        $farm.removeClass('dirt').addClass('plowed');
        $farm.find('.target').attr('src', 'img/dirt.png');
        $farm.find('.targetmessage').html('');
        $farm.find('.progressbar').css('width', '0');
        this.truck.showMenu();
    } else if ($farm.is('.harvest')) {
        //time to harvest!

        f.money += f.crop.sellPrice;
        $farm.find('.progressbar').css('width', '0');
        $farm.removeClass('harvest').addClass('dirt');
        f.crop = null;
        $farm.find('.target').attr('src', 'img/dirt.png');
        $farm.find('.targetmessage').html('');
        f.countMoney();
        this.countMoney();
    } else if ($farm.is('.plowed') && $farm.find('.menu').is('.seed')) {
        //seed!!

        f.plant(new Tomato($farm));
        this.countMoney();
    }
}

Game.prototype.left = function(farmIndex) {
    var $farm = this.farms[farmIndex].$el;
    if ($farm.is('.plowed') && $farm.find('.menu').is('.seed')) {
        this.farms[farmIndex].plant(new Oat($farm));
        this.countMoney();
    }
}

Game.prototype.right = function(farmIndex) {
    var $farm = this.farms[farmIndex].$el;
    if ($farm.is('.plowed') && $farm.find('.menu').is('.seed')) {
        this.farms[farmIndex].plant(new Peach($farm));
        this.countMoney();
    }
}

Game.prototype.countMoney = function() {
    var money = 0;
    for (var i = 0; i < 4; i++) {
        money += this.farms[i].money;
    }
    $("#money").html('Group Funds: $' + money.toFixed(2));
    return money;
}

Game.prototype.input = function(ch) {
    if (!this.inputBuffer[ch]) {
        this.inputBuffer[ch] = 1;
        var obj = this;
        var commands = {
            "a": function() { obj.truck.to(1, 0); },

            "b": function() { obj.truck.to(0, 1); },
            "c": function() { obj.truck.to(2, 1); },
            
            "d": function() { obj.truck.to(1, 2); },
            "e": function() { obj.truck.to(3, 2); },
            
            "f": function() { obj.truck.to(2, 3); },

            "g": function() { obj.header.switchGate('top'); },
            "h": function() { obj.header.switchGate('left'); },
            "i": function() { obj.header.switchGate('right'); },

            "j": function() { obj.left(0); },
            "k": function() { obj.middle(0); },
            "l": function() { obj.right(0); },
            
            "m": function() { obj.left(1); },
            "n": function() { obj.middle(1); },
            "o": function() { obj.right(1); },
            
            "p": function() { obj.left(2); },
            "q": function() { obj.middle(2); },
            "r": function() { obj.right(2); },
            
            "s": function() { obj.left(3); },
            "t": function() { obj.middle(3); },
            "u": function() { obj.right(3); },
        }
        console.log(commands[String.fromCharCode(ch)]);
        commands[String.fromCharCode(ch)]();
        setTimeout(function() {
            obj.inputBuffer[ch] -= 1;
        }, 100);
    } else {
        //reset buffer as if just pressed

    }
}
var Truck = function($el) {
    this.pos = 0;
    this.$el = $el;
    this.isMoving = false;
}

Truck.prototype.to = function(pos, from) {
    if (!this.isMoving && this.pos == from) {
        this.pos = pos;
        this.moving();
    }
}

Truck.prototype.moving = function() {
    console.log('moving...');
    this.$el.css('margin-left', (this.pos*320)+'px');
    this.isMoving = true;
    this.$el.addClass('moving');
    $(".menu").removeClass('seed');
    var obj = this;
    setTimeout(function() {
        obj.isMoving = false;
        obj.$el.removeClass('moving');
        obj.showMenu();
    }, 1000);
}

Truck.prototype.showMenu = function() {
    var $curPlot = $(".farm:nth-child("+(this.pos+1)+")");
    if ($curPlot.is('.plowed')) {
        var $m = $curPlot.find('.menu');
        $m.addClass('seed');
    }
}
var Header = function($el) {
    this.$el = $el;
    this.canvas = this.$el[0];
    this.context = this.canvas.getContext('2d');
    this.gatePos = {top:1,left:1,right:1}; //1:right, 0:left

    this.createRiverbed();
};

Header.prototype.activeFarm = function() {
    return (this.gatePos.top ? 1-this.gatePos.left : (3 - this.gatePos.right));
}

Header.prototype.switchGate = function(gate) {
    this.gatePos[gate] = 1 - this.gatePos[gate];
    this.createRiverbed();
}

Header.prototype.createRiverbed = function() {
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.context.beginPath();

    this.context.moveTo(640, -10);
    this.context.lineWidth = 30;

    var curves = {
        curve: [610, 100, 670, 160, 640, 280],
        left : {
            curve: [520, 390, 400, 60, 300, 210],
            left : {
                curve: [250, 300, 100, 300, 100, 400]
            },
            right: {
                curve: [270, 250, 300, 300, 420, 420]
            }
        },
        right: {
            curve: [650, 450, 850, 200, 1000, 260],
            left : {
                curve: [1050, 350, 850, 350, 780, 410]
            },
            right: {
                curve: [1100, 300, 1150, 350, 1150, 400]
            }
        }
    };
    var obj = this;

    function drawCurve(i, color) {
        obj.context.beginPath();
        obj.context.lineWidth = 30;
        obj.context.strokeStyle = color;
        obj.context.moveTo(640, -10);
        obj.context.bezierCurveTo.apply(obj.context, curves.curve);
        var curCurve = (i < 2) ? curves.left : curves.right;
        obj.context.bezierCurveTo.apply(obj.context, curCurve.curve);
        curCurve = (i % 2) ? curCurve.right : curCurve.left;
        obj.context.bezierCurveTo.apply(obj.context, curCurve.curve);
        obj.context.stroke();
        obj.context.closePath();
    }

    for (var i = 0; i < 4; i++) {
        if (i != this.activeFarm()) {
            drawCurve(i, '#552500');
        }
    }
    drawCurve(this.activeFarm(), '#3080e4');

    var gates = {
        top: {
            pos:[ 640, 280],
            left: [640, 260], 
            right: [660, 280],
        }, left: {
            pos:[ 290, 280],
            left: [290, 250], 
            right: [300, 250],
        }, right: {
            pos:[1010, 300],
            left: [990, 290],
            right: [1010, 290]
        }
    };


};
var settings = {
    numPlayers : 4
};

$(function() {
    new Game();
});
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

0