Skip to content
Snippets Groups Projects
Commit b31d7baa authored by ys678's avatar ys678
Browse files

New update for Week2

parent 5bec33eb
Branches
No related tags found
1 merge request!5New update for Week2
const BACKGROUND_COLOR = '#27ae60';
const SNAKE_COLOR = '#3498db';
const FOOD_COLOR = '#e74c3c';
const gameScreen = document.getElementById('gameScreen');
let canvas, element;
//Given a position of snake/food (Will be changed in the future to handle multiplayer/randomness)
const gameState = {
player: {
//Give a temporary position for the snake head
headPosition: {
x: 3,
y: 10,
},
//Give a temporary speed
velocity: {
x: 1,
y: 0,
},
//Give a temporary position of the snake body
snake: [
{x: 2, y: 10},
{x: 3, y: 10},
],
},
//Give a temporary position for the food, we will change it later to a random position
food: {
x: 7,
y: 7,
},
//Initialize the gridesize
gridsize: 20,
};
//Initialize the game elements such as canvas size, color, etc.
function init(){
canvas = document.createElement('canvas');
element = canvas.getContext('2d');
canvas.width = 600;
canvas.height = 600;
element.fillStyle = BACKGROUND_COLOR;
element.fillRect(0, 0, canvas.width, canvas.height);
gameScreen.appendChild(canvas);
document.addEventListener('keydown', keydown);
}
//Here is where we will implement movement/direction logic. The server is not implemented yet so we just use console.log(event.keyCode) to represent keys pressed
function keydown(event){
console.log(event.keyCode);
}
init();
//Change background color, initilize game screen size, and place a food object at a set position
function paintGame(state) {
element.fillstyle = BACKGROUND_COLOR;
element.fillRect(0, 0, canvas.width, canvas.height);
const food = state.food;
const gridsize = state.gridsize;
const size = canvas.width / gridsize;
element.fillStyle = FOOD_COLOR;
element.fillRect(food.x * size, food.y * size, size, size);
paintPlayer(state.player, size, SNAKE_COLOR);
}
//Change snake cell color (All elements in the snake length)
function paintPlayer(playerState, size, color){
const snake = playerState.snake;
element.fillStyle = color;
for(let cell of snake){
element.fillRect(cell.x * size, cell.y * size, size, size);
}
}
paintGame(gameState);
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment