简体   繁体   中英

HTML 5 Canvas - Proper way of assigning coordinate values to array/object in Javascript

I'm making a basic old school snake game using Node.js to learn. Now instead of 1 "food block" showing up one at a time, I try to make an additional one spawn every second. Now I have multiple "food blocks" with X,Y coordinates that I must emit to the client. How would I accomplish this without sending over a huge array of 100x100 of true and false?

JAVASCRIPT

//Game is 100 by 100

var food = ?;//An array which stores the X & Y coordinates of all spawned food

if(foodEaten){
    removeFood(foodEatenX, foodEatenY);
}
//Call once every second
spawnFood();

socket.emit('foodPositions', food);//send the `food` array to client

function spawnFood(){
    var foodX,
        foodY,
        flag = false;

    while(!flag){
        foodX = Math.floor(Math.random() * 100),
        foodY = Math.floor(Math.random() * 100);

        if(map[foodX][foodY].claim == "empty"){
            flag = true;
            map[foodX][foodY].claim = "notempty";

            /*
            --CODE HERE TO ADD for `food` variable
            */
        }
    }
}
function removeFood(x, y){
    //remove food coordinates in array
}

Simplified

--Not necessarily in specified order

1) Spawn food @ random x/y coordinates (Once a second)

food[x][y] = true

2) Remove food @ x/y coordinates (whenever I want (eg when food gets "eaten")

food[x][y] = delete (not false, simply delete out of array/object)

3) Send pack of food to client

emit(food)

CLIENT

receive food variable and do: //Draw all currently available food blocks for(var i = 0; i < food.length; i++) drawImage(foodImage, foodX, foodY)

PS - Sorry if code messy and question a bit vague, brain is fried

I'd try with a list of "food blocks", each one with its coordinates (smaller than an array of 100x100 elements).

The client would take care of removing any eaten food block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM