Tucker Flynn
Tucker Flynn

Reputation: 15

Reset Array back to Original values

I'm working on a simple game with Javascript, involving changes to an HTML5 canvas. Have a number (10+) of objects entered in an array:

var boxes = [];
    boxes.push({
        x: 0,
        y:canvas.height - 370,
        width: 400,
        height: 20});
    boxes.push({
        x: 300,
        y:canvas.height - 100,
        width: 150,
        height: 90});

The entire array is then run through an update function, which changes the x value depending on the player's position:

for (var i = 0; i < boxes.length; i++) {
                if (boxes[1].x > -3000 + canvas.width) {
                    boxes[i].x -= robot.speed * modifier;
                    robot.x = canvas.width - 300;
                }; 
            };

When the player dies a reset function is run:

var reset = function () {
            robot.x = 0;
            robot.y = 500;
            ++deaths;
            };

I'm looking for a way to reset all the values of the boxes array to the original values when this function runs, essentially resetting the map, without having to enter each one manually, ie boxes[1].x = 300

https://jsfiddle.net/to31b612/

Upvotes: 0

Views: 3596

Answers (4)

Richard Christensen
Richard Christensen

Reputation: 2166

just use 2 variables

var initBoxes = [];
initBoxes.push({
    x: 0,
    y:canvas.height - 370,
    width: 400,
    height: 20});
initBoxes.push({
    x: 300,
    y:canvas.height - 100,
    width: 150,
    height: 90});

var boxes = initBoxes;

Then when ever you need to reset boxes just

boxes = initBoxes;

Upvotes: 0

AJ Richardson
AJ Richardson

Reputation: 6820

You could just initialize boxes inside the reset() function, and make sure to call call reset() before the first run of the game, too.

var deaths = -1;
var boxes = [];

function reset() {
    robot.x = 0;
    robot.y = 500;
    boxes = [{
        x: 0,
        y:canvas.height - 370,
        width: 400,
        height: 20
    }, {
        x: 300,
        y:canvas.height - 100,
        width: 150,
        height: 90
    }];
    ++deaths;
}

Upvotes: 1

jake
jake

Reputation: 1027

It sounds like you want to use the Memento Pattern

Upvotes: 0

user1693593
user1693593

Reputation:

Simply initialize from a single function:

var boxes;
initBoxes();

function initBoxes() {
    boxes = [];
    boxes.push({
        x: 0,
        y:canvas.height - 370,
        width: 400,
        height: 20});
    boxes.push({
        x: 300,
        y:canvas.height - 100,
        width: 150,
        height: 90});
}

Then just recall initBoxes() every time you need to initialize it.

Upvotes: 2

Related Questions