How to clear image right into next html canvas games? - javascript

I made a game, a race car game. The code is:
index.html
<!DOCTYPE html>
<html>
<head>
<title> Race car </title>
<link rel="stylesheet" type="text/css" href="style.css">
<script>
var ctx;
//save the parameters to variables for easier clearing
var x_Car = 30,
y_Car = 95,
width_Car = 110,
height_Car = 55,
imgCar = new Image();
imgCar.src = "cars/race-car.png";
var nrMonsters = 0,
imgMonster = new Image();
imgMonster.src = "Monster/yellow_monster.png";
var width_Monster = 100;
var height_Monster = 20;
var x_Monster = 50;
var y_Monster = 5;
var speed = 1;
// function drawMonster() {
// ctx.drawImage(imgMonster, x_Monster, y_Monster, width_Monster, height_Monster);
// }
function drawCar() {
ctx.drawImage(imgCar, x_Car, y_Car, width_Car, height_Car);
}
function rand() {
var left = 50;
var right = 150;
var z;
var random = Math.random();
if (random > 0.5) {
z = right;
} else {
z = left;
}
return z;
}
valX = rand();
function draw(x, y) {
//ctx.save();
if (valX == 50 && x_Car > 75) {
ctx.clearRect(x + 5, -5, 150, 150); // 95 cu 150
} else if (valX == 50) {
ctx.clearRect(x + 5, y, 150, 10);
} else if (valX == 150 && x_Car < 32){
ctx.clearRect(x + 150, -5, 260, 150); // 95 cu 150
} else if (valX == 150) {
ctx.clearRect(x + 150, y, 260, 10);
}
ctx.drawImage(imgMonster, valX, y, width_Monster, height_Monster);
ctx.restore();
y += speed;
if (y == y_Car && x_Car < 32 && valX == 50
|| y == y_Car && x_Car > 75 && valX == 150
|| y > y_Car && y < y_Car + height_Car && x_Car < 32 && valX == 50
|| y > y_Car && y < y_Car + height_Car && x_Car > 75 && valX == 150) {
window.location.href = "you_lost_the_game.html";
// alert("You lost the game");
}
var loopTimer = setTimeout("draw(" + x + ", " + y + ")", 20);
if (y == 150 && nrMonsters < 15
|| y == 160 && nrMonsters >= 15) {
valX = rand();
nrMonsters++;
console.log(nrMonsters);
document.getElementById("numarObstacole").innerHTML = nrMonsters;
if (nrMonsters == 5
|| nrMonsters == 10
|| nrMonsters == 20
|| nrMonsters == 25) {
// || nrMonsters == 20 || nrMonsters == 27) {
speed += 1;
} else if (nrMonsters == 15) {
speed += 1;
}
draw(0, 0);
if (nrMonsters == 25) {
window.location.href = "win.html";
}
}
}
function init() {
ctx = document.getElementById("canvas").getContext("2d");
// audio
// myAudio = new Audio('http://static1.grsites.com/archive/sounds/cars/cars002.wav');
myAudio = new Audio("Sounds/Get low NFS.mp3");
myAudio.addEventListener("ended", function() {
this.currentTime = 0;
this.play();
}, false);
myAudio.play();
//draw wall
draw(0, 0);
drawCar();
function moveRight() {
ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
x_Car = x_Car + 120;
if(x_Car > 220){
x_Car -= 120;
drawCar();
} else {
drawCar();
}
}
function moveLeft() {
ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
x_Car = x_Car-120;
if (x_Car < 20) {
x_Car += 120;
drawCar();
} else {
drawCar();
}
}
function moveUp() {
ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
y_Car = y_Car-20;
drawCar();
}
function moveDown() {
ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
y_Car = y_Car + 20;
drawCar();
}
window.addEventListener("keypress", checkKeyPressed, false);
function checkKeyPressed(e) {
if (e.charCode == "97" || e.charCode == 027) {
moveLeft();
}
if (e.charCode == "100" || e.charCode== 026) {
moveRight();
}
if (e.charCode == "119" || e.charCode== 024) {
moveUp();
}
if (e.charCode == "115" || e.charCode== 025) {
moveDown();
}
}
}
function moveRight() {
ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
x_Car = x_Car + 120;
if (x_Car > 220) {
x_Car -= 120;
drawCar();
} else {
drawCar();
}
}
function moveLeft() {
ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
x_Car = x_Car - 120;
if(x_Car < 20) {
x_Car += 120;
drawCar();
} else {
drawCar();
}
}
function moveUp() {
ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
y_Car = y_Car - 20;
drawCar();
}
function moveDown() {
ctx.clearRect(x_Car, y_Car, width_Car, height_Car);
y_Car = y_Car + 20;
drawCar();
}
window.addEventListener("keypress", checkKeyPressed, false);
function checkKeyPressed(e) {
if (e.charCode == "97") {
moveLeft();
}
if (e.charCode == "100") {
moveRight();
}
if (e.charCode == "119") {
moveUp();
}
if (e.charCode == "115") {
moveDown();
}
}
</script>
</head>
<body onLoad="init();">
<div id="moveButons">
<table>
<tr>
<td></td>
<td>
<input class="button" id="up" type="button" value="Move Up" onclick="moveUp()"/>
</td>
<td></td>
</tr>
<tr>
<td>
<input class="button" id="left" type="button" value="Move Left" onclick="moveLeft()"/>
</td>
<td></td>
<td>
<input class="button" id="right" type="button" value="Move Right" onclick="moveRight()"/>
</td>
</tr>
<tr>
<td></td>
<td>
<input class="button" id="down" type="button" value="Move Down" onclick="moveDown()"/>
</td>
<td></td>
</tr>
</table>
</div>
<p class="numarObstacole">
Ai trecut peste <span id="numarObstacole"> 0 </span> obstacole
</p>
<canvas id="canvas">
Your browser doesn't support the HTML5 element canvas.
</canvas>
</body>
</html>
style.css
* {
margin: 0;
padding: 0;
}
body {
background-color: yellow;
}
#canvas {
background: white;
margin-left: 50%;
position: absolute;
left: -206px;
width: 412px;
height: 100%;
background-image: url("street/street (2).jpg");
background-position: 0px 0px;
background-repeat: repeat-y;
-webkit-animation: animatedBackground 5s linear infinite;
-moz-animation: animatedBackground 5s linear infinite;
animation: animatedBackground 5s linear infinite;
}
#moveButons {
position: absolute;
left: 20px;
top: 50px;
}
#-webkit-keyframes animatedBackground {
from { background-position: 0 100%; }
to { background-position: 0 0; }
}
#-moz-keyframes animatedBackground {
from { background-position: 0 100%; }
to { background-position: 0 0; }
}
#keyframes animatedBackground {
from { background-position: 0 100%; }
to { background-position: 0 0; }
}
#lostGame {
text-align: center;
color: red;
margin-top: 175px;
}
#win {
text-align: center;
color: blue;
margin-top: 175px;
}
#canvas_lost {
width: 320px;
height: 240px;
background: url("Joker/the-joker-laughing-1.jpg");
margin-left: 50%;
position: absolute;
left: -160px;
}
#canvas_win {
width: 320px;
height: 240px;
background: url("Joker/joker.gif");
margin-left: 50%;
position: absolute;
left: -160px;
}
.button {
color: blue;
font-size: 17px;
text-align: center;
background: #6BA7FA;
width: 100px;
}
.numarObstacole {
position: absolute;
color: #1F1;
background: silver;
font-size: 20px;
font-family: Serif;
}
#numarObstacole {
color: blue;
font-size: 22px;
font-family: sans-serif;
}
win.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title> Win </title>
<script>
function init() {
var canvas = document.getElementById("canvas_win");
var ctx = canvas.getContext("2d");
var myAudio = new Audio("Sounds/Fireworks Finale.mp3");
myAudio.addEventListener("ended", function() {
this.currentTime = 0;
this.play();
}, false);
myAudio.play();
var otherAudio = new Audio("Sounds/Audience_Applause.mp3");
otherAudio.addEventListener("ended", function() {
this.currentTime = 0;
this.play();
}, false);
otherAudio.play()
}
</script>
</head>
<body onLoad="init();">
<h1 id="win"> You win </h1>
<canvas id="canvas_win">
Your browser doesn't support the HTML5 element canvas.
</canvas>
</body>
</html>
you_lost_the_game.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title> You lost the game </title>
<script>
function init() {
var canvas = document.getElementById("canvas_lost");
var ctx = canvas.getContext("2d");
var myAudio = new Audio("Sounds/hahaha-Peter_De_Lang.mp3");
myAudio.addEventListener("ended", function() {
this.currentTime = 0;
this.play();
}, false);
myAudio.play();
}
</script>
</head>
<body onLoad="init();">
<h1 id="lostGame"> You lost the game </h1>
<canvas id="canvas_lost">
Your browser doesn't support the HTML5 element canvas.
</canvas>
</body>
</html>
The problem is with the monster image.
When this image comes to the car image with a bigger speed, it leaves behind some "trail".
How can I solve it?

The answer
I believe your issue is with your clearing with clearRect. Instead of carefully finding specific places to clear the canvas (i.e. ctx.clearRect(x + 150, -5, 260, 150);), you should just up and do:
// Get <canvas> on a variable
var canvas = document.getElementById("canvas");
// ctx is still the same
var ctx = canvas.getContext("2d");
function draw(x, y) {
// Clears everything on the canvas on every loop
ctx.clearRect(0, 0, canvas.width, canvas.height);
...
That way, any "trail" left by the car or by the monster will be cleared on every frame.
Now, for coding suggestions:
Instead of adding an event listener for when an audio ends, simply turn the loop property to true. Here's some code:
// Your current code
var myAudio = new Audio("Sounds/---.mp3");
myAudio.addEventListener("ended", function() {
this.currentTime = 0;
this.play();
}, false);
myAudio.play();
// Some smaller and more efficient code
var myAudio = new Audio("Sounds/---.mp3");
myAudio.loop = true; // Restarts the audio every time it reaches the end
myAudio.play();
This code doesn't make much sense:
if (nrMonsters == 5
|| nrMonsters == 10
|| nrMonsters == 20
|| nrMonsters == 25) {
// || nrMonsters == 20 || nrMonsters == 27) {
speed += 1;
} else if (nrMonsters == 15) {
speed += 1;
}
If something do this otherwise do the same thing? Here's a quick fix:
if (nrMonsters == 5
|| nrMonsters == 10
|| nrMonsters == 15
|| nrMonsters == 20
|| nrMonsters == 25) {
speed += 1;
}
You don't need this else here:
// From the moveRight() function
if (x_Car > 220) {
x_Car -= 120;
drawCar();
} else {
drawCar();
}
You see, if you're going to drawCar() anyway, you don't need to put it inside the if. Here's better code:
if (x_Car > 220) {
x_Car -= 120;
}
drawCar();
You shouldn't have those leading zeroes:
// From the checkKeyPressed() function
if (e.charCode == "97" || e.charCode == 027) { ... }
That 027 (and some subsequent numbers with leading a 0) gets treated as a base 8 number. I'm pretty sure it wasn't your intention to have an octal number there, but if that's the case, then the proper formatting is prepeding it with 0o instead of simply a zero.
var binal = 0b10; // (0b)10 in base 2 is equal to 2 in decimal
var octal = 0o10; // (0o)10 in base 8 is equal to 8 in decimal
var hexal = 0x10; // (0x)10 in base 16 is equal to 16 in decimal
That's all that I found. I wish you good luck with your game! Cheers!

Related

JavaScript Snake Game with two Snakes (Local Mutiplayer)

Im programing a Snake Webgame with HTML, CSS and JavaScript and im implementing Multiple Gamemodes, one should be a Local Multiplayer where one Person is playing with Arrow keys and the Other Person with WASD.
But I got the problem, that I dont know how to Summon a Second Snake. I tried to just copy the Summon Code and rename the variables. But that didn't work, no matter what I tryed.
The code is 90% made by myself, but because of some JavaScript beginner issues I needed some help by the web.
Can someone may tell me how I can summon a Second snake? I just need the "how to" Summon.
let canvas = document.getElementById('game');
let ctx = canvas.getContext('2d');
let grid = 10;
let count = 0;
//Scores
let Score = 0;
let HighScore = 0;
let Alive = true;
//Snake Speed
let Speed = 15;
//Snake Base Stats
let snake = {
x: 200,
y: 200,
dx: grid,
dy: 0,
cells: [],
maxCells: 4
};
//First Apple Spawn
let apple = {
x: 320,
y: 320
};
//Random Int for Apple Spawn
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function loop() {
requestAnimationFrame(loop);
//Tic speed
if (++count < Speed) {
return;
}
count = 0;
ctx.clearRect(0, 0, canvas.width, canvas.height);
snake.x += snake.dx;
snake.y += snake.dy;
//Automatic Movement
if (snake.x < 0) {
snake.x = canvas.width - grid;
} else if (snake.x >= canvas.width) {
snake.x = 0;
}
if (snake.y < 0) {
snake.y = canvas.height - grid;
} else if (snake.y >= canvas.height) {
snake.y = 0;
}
snake.cells.unshift({
x: snake.x,
y: snake.y
});
if (snake.cells.length > snake.maxCells) {
snake.cells.pop();
}
//Apple Color
ctx.fillStyle = 'gold';
ctx.fillRect(apple.x, apple.y, grid - 1, grid - 1);
//Snake Color
ctx.fillStyle = 'white';
snake.cells.forEach(function(cell, index) {
//Snake Color
ctx.fillRect(cell.x, cell.y, grid - 1, grid - 1);
//Snake Eat Apple
if (cell.x === apple.x && cell.y === apple.y) {
snake.maxCells++;
apple.x = getRandomInt(0, 25) * grid;
apple.y = getRandomInt(0, 25) * grid;
SnakeScore();
}
//Snake Dies
for (var i = index + 1; i < snake.cells.length; i++) {
if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) {
SummonSnake();
Alive = false;
SnakeScore();
}
}
});
}
//Arrow Key Movement
document.addEventListener('keydown', function(e) {
if (e.which === 37 && snake.dx === 0) {
snake.dx = -grid;
snake.dy = 0;
} else if (e.which === 38 && snake.dy === 0) {
snake.dy = -grid;
snake.dx = 0;
} else if (e.which === 39 && snake.dx === 0) {
snake.dx = grid;
snake.dy = 0;
} else if (e.which === 40 && snake.dy === 0) {
snake.dy = grid;
snake.dx = 0;
}
});
requestAnimationFrame(loop);
//Score
function SnakeScore() {
if (Alive === true) {
Score++;
document.getElementById("Score").innerHTML = Score;
} else if (Alive === false) {
Score = 0;
document.getElementById("Score").innerHTML = Score;
Alive = true;
}
if (Score > HighScore) {
SnakeHighscore();
}
}
//Highscore
function SnakeHighscore() {
HighScore = Score;
document.getElementById("Highscore").innerHTML = HighScore;
}
//Snake Summon Stats
function SummonSnake() {
snake.x = 200;
snake.y = 200;
snake.cells = [];
snake.maxCells = 4;
snake.dx = grid;
snake.dy = 0;
}
//Gamemodes
function GameMode() {
value = document.getElementById('valueGames').value;
if (value === "E") {
Speed = 15;
Score = 0;
document.getElementById("Score").innerHTML = Score;
SummonSnake();
} else if (value === "M") {
Speed = 10;
Score = 0;
document.getElementById("Score").innerHTML = Score;
SummonSnake();
} else if (value === "H") {
Speed = 5;
Score = 0;
document.getElementById("Score").innerHTML = Score;
SummonSnake();
} else if (value === "Multiplayer") {
}
}
body {
display: flex;
align-items: center;
justify-content: center;
background-image: url('https://wallpapercave.com/wp/wp3493594.png');
}
canvas {
width: 403px;
height: 403px;
border: 2px solid rgb(255, 213, 0);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#ScoreCSS {
margin-right: 50px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="main.css">
<meta charset="UTF-8">
<title>Snake NICEEE</title>
</head>
<body>
<!-- Scores -->
<h1 id="ScoreCSS">Score: <a id="Score">0</a></h1>
<h1>Highscore: <a id="Highscore">0</a></h1>
<!-- Canvas (Game Field)-->
<canvas id="game" width="400" height="400"></canvas>
<!-- Dropdown for GameModes -->
<select id="valueGames" onchange="GameMode()">
<option value="E" selected>Easy</option>
<option value="M">Middle</option>
<option value="H">Hard</option>
<option value="Multiplayer">Multiplayer</option>
</select>
</body>
</html>
This should get you started. I created a second snake object and moved the alive property to the snake. Then I added functions to draw/move the snake and passed the snake object to those functions so you don't have as much duplicate code in order to handle multiple snakes. (Theoretically, you could add more than 2 snakes this way by creating new snake objects and then adding moveSnake(snake3, canvas); etc).
You'll need to add the event listeners for WASD as well as "dead" game logic in Multiplayer mode, because presumably the game will pause somehow and show the winner and the high score.
let canvas = document.getElementById('game');
let ctx = canvas.getContext('2d');
let grid = 10;
let count = 0;
//Scores
let Score = 0;
let HighScore = 0;
let Speed = 15;
//Snake Base Stats
let snake = {
x: 200,
y: 200,
dx: grid,
dy: 0,
cells: [],
maxCells: 4,
alive: true, // moved the global var here
active: true, // added this in order to track multiple snakes being active
color: 'white' // moved this here to define it per-snake
};
let snake2 = {
x: 200,
y: 200,
dx: grid,
dy: 0,
cells: [],
maxCells: 4,
alive: true,
active: false,
color: 'red'
};
// keep track of active snakes
let snakes = [
snake
];
//First Apple Spawn
let apple = {
x: 320,
y: 320,
color: 'gold'
};
//Random Int for Apple Spawn
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function loop() {
requestAnimationFrame(loop);
//Tic speed
if (++count < Speed) {
return;
}
count = 0;
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveSnakes(snakes, canvas);
//Apple Color
ctx.fillStyle = apple.color;
ctx.fillRect(apple.x, apple.y, grid - 1, grid - 1);
drawSnakes(snakes, ctx, apple);
}
//Arrow Key Movement
document.addEventListener('keydown', function(e) {
if (e.which === 37 && snake.dx === 0) {
snake.dx = -grid;
snake.dy = 0;
} else if (e.which === 38 && snake.dy === 0) {
snake.dy = -grid;
snake.dx = 0;
} else if (e.which === 39 && snake.dx === 0) {
snake.dx = grid;
snake.dy = 0;
} else if (e.which === 40 && snake.dy === 0) {
snake.dy = grid;
snake.dx = 0;
}
});
//TODO: add movement for snake2
requestAnimationFrame(loop);
function moveSnakes(snakes, canvas) {
snakes.forEach(function(snake) {
if (!snake.active) {
return;
}
snake.x += snake.dx;
snake.y += snake.dy;
if (snake.x < 0) {
snake.x = canvas.width - grid;
} else if (snake.x >= canvas.width) {
snake.x = 0;
}
if (snake.y < 0) {
snake.y = canvas.height - grid;
} else if (snake.y >= canvas.height) {
snake.y = 0;
}
snake.cells.unshift({
x: snake.x,
y: snake.y
});
if (snake.cells.length > snake.maxCells) {
snake.cells.pop();
}
});
}
function drawSnakes(snakes, ctx, apple) {
snakes.forEach(function(snake) {
if (!snake.active) {
return;
}
//Snake Color
ctx.fillStyle = snake.color;
snake.cells.forEach(function(cell, index) {
//Snake Color
ctx.fillRect(cell.x, cell.y, grid - 1, grid - 1);
//Snake Eat Apple
if (cell.x === apple.x && cell.y === apple.y) {
snake.maxCells++;
apple.x = getRandomInt(0, 25) * grid;
apple.y = getRandomInt(0, 25) * grid;
SnakeScore(snake);
}
//Snake Dies
for (var i = index + 1; i < snake.cells.length; i++) {
if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) {
SummonSnake(snake);
snake.alive = false;
SnakeScore();
}
}
});
});
}
//Score
function SnakeScore(snake) {
if (snake.alive) {
Score++;
document.getElementById("Score").innerHTML = Score;
} else if (!snake.alive) {
Score = 0;
document.getElementById("Score").innerHTML = Score;
snake.alive = true;
}
if (Score > HighScore) {
SnakeHighscore();
}
}
//Highscore
function SnakeHighscore() {
HighScore = Score;
document.getElementById("Highscore").innerHTML = HighScore;
}
//Snake Summon Stats
function SummonSnake(snake, y) {
snake.x = 200;
snake.y = y;
snake.cells = [];
snake.maxCells = 4;
snake.dx = grid;
snake.dy = 0;
}
function activateSnakes(numberOfSnakes) {
if (numberOfSnakes === 1) {
SummonSnake(snake, 200);
snakes = [snake];
snake2.active = false;
} else if (numberOfSnakes === 2) {
SummonSnake(snake, 180);
SummonSnake(snake2, 220);
snakes = [snake, snake2];
snake2.active = true;
}
}
//Gamemodes
function GameMode() {
value = document.getElementById('valueGames').value;
if (value === "E") {
Speed = 15;
activateSnakes(1);
} else if (value === "M") {
Speed = 10;
activateSnakes(1);
} else if (value === "H") {
Speed = 5;
activateSnakes(1);
} else if (value === "Multiplayer") {
Speed = 5;
activateSnakes(2);
}
Score = 0;
document.getElementById("Score").innerHTML = Score;
}
GameMode();
body {
display: flex;
align-items: center;
justify-content: center;
background-image: url('https://wallpapercave.com/wp/wp3493594.png');
}
canvas {
width: 403px;
height: 403px;
border: 2px solid rgb(255, 213, 0);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#ScoreCSS {
margin-right: 50px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="main.css">
<meta charset="UTF-8">
<title>Snake NICEEE</title>
</head>
<body>
<!-- Scores -->
<h1 id="ScoreCSS">Score: <a id="Score">0</a></h1>
<h1>Highscore: <a id="Highscore">0</a></h1>
<!-- Canvas (Game Field)-->
<canvas id="game" width="400" height="400"></canvas>
<!-- Dropdown for GameModes -->
<select id="valueGames" onchange="GameMode()">
<option value="E">Easy</option>
<option value="M">Middle</option>
<option value="H">Hard</option>
<option value="Multiplayer" selected>Multiplayer</option>
</select>
</body>
</html>

How to make a self playing snake game using JS?

I'm trying to code a snake game that will randomly move through the canvas. for now, I won't worry about the "food" as my main problem is the self-playing part not running. it seems to start but does not change course over time, so not sure if need to implement a timer (?)
Tried with a switch and thought by generating with random() one of the alternatives but only goes in one direction until hits the border
*/<-------------------------HTML----------------------->*/
<html>
<head>
<meta charset='utf-8'/>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class= 'game'>
<div id = 'home'>
<canvas id='mycanvas' width='350' height='350'>
</canvas>
</div>
<button id='btn'>START</button>
</div>
<script src="js/logic.js"></script>
</body>
</html>
CSS:
/*<----------------------CSS----------------------->*/
#home {
width: 350px;
height: 350px;
background-size: auto 350px;
background-repeat: no-repeat;
background-color: lightgrey;
background-position: center center;
padding: 0;
margin: 03;
}
button {
background-color: green;
color: white;
border: none;
bottom: 0;
height: 30px;
font-size: 12pt;
float: left;
width: 90px;
margin: 10px 0 0 0;
}
button:hover {
background-color: darkgreen;
}
button:disabled {
background-color: grey;
}
.game {
margin: 0 auto;
}
JS:
/*<-------------------JS----------------->*/
var mycanvas = document.getElementById('mycanvas');
var ctx = mycanvas.getContext('2d');
var snakeSize = 10;
var w = 350;
var h = 350;
var snake;
var snakeSize = 10;
var pixel;
var drawModule = (function() {
var bodySnake = function(x, y) {
ctx.fillStyle = 'green';
ctx.fillRect(x * snakeSize, y * snakeSize, snakeSize, snakeSize);
ctx.strokeStyle = 'black';
ctx.strokeRect(x * snakeSize, y * snakeSize, snakeSize, snakeSize);
}
var drawSnake = function() {
var length = 4;
snake = [];
for (var i = length - 1; i >= 0; i--) {
snake.push({ x: i, y: 0 });
}
}
var paint = function() {
ctx.fillStyle = 'lightgrey';
ctx.fillRect(0, 0, w, h);
ctx.strokeStyle = 'black';
ctx.strokeRect(0, 0, w, h);
btn.setAttribute('disabled', true);
var snakeX = snake[0].x;
var snakeY = snake[0].y;
if (direction == 'right') {
snakeX++;
} else if (direction == 'left') {
snakeX--;
} else if (direction == 'up') {
snakeY--;
} else if (direction == 'down') {
snakeY++;
}
if (snakeX == -1 || snakeX == w / snakeSize || snakeY == -1 || snakeY == h / snakeSize || checkCollision(snakeX, snakeY, snake)) {
btn.removeAttribute('disabled', true);
ctx.clearRect(0, 0, w, h);
gameloop = clearInterval(gameloop);
return;
}
if (snakeX == pixel.x && snakeY == pixel.y) {
var tail = { x: snakeX, y: snakeY };
} else {
var tail = snake.pop();
tail.x = snakeX;
tail.y = snakeY;
}
snake.unshift(tail);
for (var i = 0; i < snake.length; i++) {
bodySnake(snake[i].x, snake[i].y);
}
}
var createPixels = function() {
pixel = {
x: Math.floor((Math.random() * 30) + 1),
y: Math.floor((Math.random() * 30) + 1)
}
}
var checkCollision = function(x, y, array) {
for (var i = 0; i < array.length; i++) {
if (array[i].x === x && array[i].y === y) {
return true;
//this part should reinitiate the game
//when it hits an edge
/*}
if (x > w - 1 || x < 0 || y > h - 1 || h < 0) {
return true;*/
}
return false;
}
}
var init = function() {
var r = Math.round(Math.random() * 5);
switch (r) {
case 1:
direction = 'left';
console.log('left');
break;
case 2:
direction = 'right';
console.log('right');
break;
case 3:
direction = 'up';
console.log('up');
break;
case 4:
direction = 'down';
console.log('down');
break;
}
drawSnake();
createPixels();
gameloop = setInterval(paint, 80);
}
return {
init: init
};
}());
(function(window, document, undefined) {
var btn = document.getElementById('btn');
btn.addEventListener("click", function() { drawModule.init(); });
}
)(window, document, drawModule);
Assign direction a random value inside the paint() function.
Explanation: Currently, the only call to random() is in the init() function, which is only called once. Thus direction is only set once, and there is no way for it to change.

Snake collides with itself if user presses arrow keys too fast

Iv'e finished my snake game but there's one more bug I can't fix. If the snake is going left for example the user can hit the up key then the right key quick enough so the snake never has a chance to move up 1 unit and resulting in the snake head turning in on itself. Any ideas how I could fix this? My brains telling me I need to have the snake move up 1 unit first before turning right, I just don't know what that looks like
//declare global variables
const canvas = document.querySelector('#canvas');
const score = document.querySelector('.score');
const gameOver = document.querySelector('.game-over');
//set canvas context
const ctx = canvas.getContext('2d');
//put canvas dimensions into variables
const cvsW = canvas.width;
const cvsH = canvas.height;
//load audio files
let eat = new Audio();
let dead = new Audio();
eat.src = 'audio/eat.mp3';
dead.src = 'audio/dead.mp3';
//create snake unit
const unit = 16;
//create points variable
let points = 0;
//create snake and set starting position
let snake = [{
x : cvsW/2,
y : cvsH/2
}]
//create food object and set its position somewhere on board
let food = {
//Math.floor(Math.random()*cvsW + 1)---number from 1 to 784
//Math.floor(Math.random()*cvsW/unit + 1)---number from 1 to 79
//Math.floor(Math.random()*cvsW/unit + 1)*unit---number from 1 to 784(but it's a multiple of unit)
//Math.floor(Math.random()*(cvsW/unit - 1)+1)*unit---same as above but -1 keeps food inside canvas
x : Math.floor(Math.random()*(cvsW/unit - 1)+1)*unit-unit/2,
y : Math.floor(Math.random()*(cvsH/unit - 1)+1)*unit-unit/2
}
//create a variable to store the direction of the snake
let direction;
//add event to read users input then change direction
document.addEventListener('keydown', (e) => {
if(e.keyCode == 37 && direction != 'right') direction = 'left';
else if (e.keyCode == 38 && direction != 'down') direction = 'up';
else if (e.keyCode == 39 && direction != 'left') direction = 'right';
else if (e.keyCode == 40 && direction != 'up') direction = 'down';
})
function draw() {
//clear canvas and redraw snake
ctx.clearRect(0, 0, cvsW, cvsH);
for(let i = 0; i < snake.length; i++) {
ctx.fillStyle = 'limegreen';
ctx.fillRect(snake[i].x-unit/2, snake[i].y-unit/2, unit, unit);
}
//draw food
ctx.fillStyle = 'red';
ctx.fillRect(food.x-unit/2, food.y-unit/2, unit, unit);
//grab heads position
let headX = snake[0].x;
let headY = snake[0].y;
//move snake in chosen direction
if(direction == 'left') headX -= unit;
else if(direction == 'right') headX += unit;
else if(direction == 'up') headY -= unit;
else if(direction == 'down') headY += unit;
//create new snake unit
let newHead = {x : headX, y :headY}
//check to see if snake has hit a wall or itself
if(headX < 0 || headX > cvsW || headY < 0 || headY > cvsH || collision(headX, headY)) {
dead.play();
clearInterval(runGame);
canvas.style.animationName = 'animate';
setTimeout(function() {gameOver.style.opacity = '1';}, 150);
}
//check to see if snakes eaten food
if(headX === food.x && headY === food.y) {
eat.play();
//increase score
points++;
score.innerText = points;
//get new food unit
getFood();
//create 3 new units
for(let i = 3; i > 0; i--) {
//add those units -without this code snake will not grow
snake.unshift(newHead);
}
} else {
//remove tail -without this code snake will keep growing
snake.pop();
}
//add new head position -without this code snake will not move
snake.unshift(newHead);
}
let runGame = setInterval(draw, 65);
function collision(x, y) {
for(let i = 1; i < snake.length; i++) {
if(x == snake[i].x && y == snake[i].y) return true;
}
return false;
}
function getFood() {
food = {
x : Math.floor(Math.random()*(cvsW/unit - 1)+1)*unit-unit/2,
y : Math.floor(Math.random()*(cvsH/unit - 1)+1)*unit-unit/2
}
//loop through snake to see if food generates inside snake
for(let i = 0; i < snake.length; i++) {
//if so call the function again
if(food.x == snake[i].x && food.y == snake[i].y) return getFood();
}
//else return new random point
return food;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake</title>
<link href="https://fonts.googleapis.com/css?family=Nova+Square" rel="stylesheet">
<style>
body {
background-color: #333;
}
.game-over {
z-index: 1;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
width: 784px;
height: 528px;
margin: auto;
color: red;
font-family: 'Nova Square';
font-size: 5rem;
font-weight: bolder;
display: flex;
justify-content: center;
align-items: center;
opacity: 0;
text-shadow: -7px 7px #333;
}
#canvas {
background-color: #4d4d4d;
display: block;
margin: auto;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
animation-duration: 0.1s;
animation-fill-mode: forwards;
}
#keyframes animate {
0% {left: 0; right: 0;}
25% {left: 50px; right: 0;}
50% {left: 0; right: 50px;}
75% {left: 50px; right: 0;}
100% {left: 0; right: 0;}
}
.score {
width: 80px;
height: 80px;
margin-left: auto;
margin-right: auto;
color: white;
font-family: 'Nova Square';
font-size: 4rem;
display: flex;
justify-content: center;
align-items: center;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="score">0</div>
<canvas id="canvas" width="784" height="528"></canvas>
<div class="game-over">Game Over</div>
<script src="script.js"></script>
</body>
</html>
You can add a variable to hold the next direction, then update the actual direction from draw, so it will be in synch with what is actually happening:
//declare global variables
const canvas = document.querySelector('#canvas');
const score = document.querySelector('.score');
const gameOver = document.querySelector('.game-over');
//set canvas context
const ctx = canvas.getContext('2d');
//put canvas dimensions into variables
const cvsW = canvas.width;
const cvsH = canvas.height;
//load audio files
let eat = new Audio();
let dead = new Audio();
eat.src = 'audio/eat.mp3';
dead.src = 'audio/dead.mp3';
//create snake unit
const unit = 16;
//create points variable
let points = 0;
//create snake and set starting position
let snake = [{
x : cvsW/2,
y : cvsH/2
}]
//create food object and set its position somewhere on board
let food = {
//Math.floor(Math.random()*cvsW + 1)---number from 1 to 784
//Math.floor(Math.random()*cvsW/unit + 1)---number from 1 to 79
//Math.floor(Math.random()*cvsW/unit + 1)*unit---number from 1 to 784(but it's a multiple of unit)
//Math.floor(Math.random()*(cvsW/unit - 1)+1)*unit---same as above but -1 keeps food inside canvas
x : Math.floor(Math.random()*(cvsW/unit - 1)+1)*unit-unit/2,
y : Math.floor(Math.random()*(cvsH/unit - 1)+1)*unit-unit/2
}
//create a variable to store the direction of the snake
let direction;
let nextDirection
//add event to read users input then change direction
document.addEventListener('keydown', (e) => {
if(e.keyCode == 37 && direction != 'right') nextDirection = 'left';
else if (e.keyCode == 38 && direction != 'down') nextDirection = 'up';
else if (e.keyCode == 39 && direction != 'left') nextDirection = 'right';
else if (e.keyCode == 40 && direction != 'up') nextDirection = 'down';
})
function draw() {
//clear canvas and redraw snake
ctx.clearRect(0, 0, cvsW, cvsH);
for(let i = 0; i < snake.length; i++) {
ctx.fillStyle = 'limegreen';
ctx.fillRect(snake[i].x-unit/2, snake[i].y-unit/2, unit, unit);
}
//draw food
ctx.fillStyle = 'red';
ctx.fillRect(food.x-unit/2, food.y-unit/2, unit, unit);
//grab heads position
let headX = snake[0].x;
let headY = snake[0].y;
//move snake in chosen direction
if(nextDirection == 'left') headX -= unit;
else if(nextDirection == 'right') headX += unit;
else if(nextDirection == 'up') headY -= unit;
else if(nextDirection == 'down') headY += unit;
// update the direction the snake is travelling:
direction = nextDirection;
//create new snake unit
let newHead = {x : headX, y :headY}
//check to see if snake has hit a wall or itself
if(headX < 0 || headX > cvsW || headY < 0 || headY > cvsH || collision(headX, headY)) {
dead.play();
clearInterval(runGame);
canvas.style.animationName = 'animate';
setTimeout(function() {gameOver.style.opacity = '1';}, 150);
}
//check to see if snakes eaten food
if(headX === food.x && headY === food.y) {
eat.play();
//increase score
points++;
score.innerText = points;
//get new food unit
getFood();
//create 3 new units
for(let i = 3; i > 0; i--) {
//add those units -without this code snake will not grow
snake.unshift(newHead);
}
} else {
//remove tail -without this code snake will keep growing
snake.pop();
}
//add new head position -without this code snake will not move
snake.unshift(newHead);
}
let runGame = setInterval(draw, 65);
function collision(x, y) {
for(let i = 1; i < snake.length; i++) {
if(x == snake[i].x && y == snake[i].y) return true;
}
return false;
}
function getFood() {
food = {
x : Math.floor(Math.random()*(cvsW/unit - 1)+1)*unit-unit/2,
y : Math.floor(Math.random()*(cvsH/unit - 1)+1)*unit-unit/2
}
//loop through snake to see if food generates inside snake
for(let i = 0; i < snake.length; i++) {
//if so call the function again
if(food.x == snake[i].x && food.y == snake[i].y) return getFood();
}
//else return new random point
return food;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake</title>
<link href="https://fonts.googleapis.com/css?family=Nova+Square" rel="stylesheet">
<style>
body {
background-color: #333;
}
.game-over {
z-index: 1;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
width: 784px;
height: 528px;
margin: auto;
color: red;
font-family: 'Nova Square';
font-size: 5rem;
font-weight: bolder;
display: flex;
justify-content: center;
align-items: center;
opacity: 0;
text-shadow: -7px 7px #333;
}
#canvas {
background-color: #4d4d4d;
display: block;
margin: auto;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
animation-duration: 0.1s;
animation-fill-mode: forwards;
}
#keyframes animate {
0% {left: 0; right: 0;}
25% {left: 50px; right: 0;}
50% {left: 0; right: 50px;}
75% {left: 50px; right: 0;}
100% {left: 0; right: 0;}
}
.score {
width: 80px;
height: 80px;
margin-left: auto;
margin-right: auto;
color: white;
font-family: 'Nova Square';
font-size: 4rem;
display: flex;
justify-content: center;
align-items: center;
margin-top: 50px;
}
</style>
</head>
<body>
<div class="score">0</div>
<canvas id="canvas" width="784" height="528"></canvas>
<div class="game-over">Game Over</div>
<script src="script.js"></script>
</body>
</html>

Uncaught TypeError: Cannot read property 'getContext' of null. In chrome app development

I am making an app for the Chrome Web Store. It is a clone of the Doodle Jump game. When I test and load it as an unpacked extension, this error keeps coming up.
Uncaught TypeError: Cannot read property 'getContext' of null
My code is here:
Javascript
function startGame() {
// RequestAnimFrame: a browser API for getting smooth animations
window.requestAnimFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width = 422,
height = 552;
canvas.width = width;
canvas.height = height;
//Variables for game
var platforms = [],
image = document.getElementById("sprite"),
player, platformCount = 10,
position = 0,
gravity = 0.2,
animloop,
flag = 0,
menuloop, broken = 0,
dir, score = 0, firstRun = true;
//Base object
var Base = function() {
this.height = 5;
this.width = width;
//Sprite clipping
this.cx = 0;
this.cy = 614;
this.cwidth = 100;
this.cheight = 5;
this.moved = 0;
this.x = 0;
this.y = height - this.height;
this.draw = function() {
try {
ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
} catch (e) {}
};
};
var base = new Base();
//Player object
var Player = function() {
this.vy = 11;
this.vx = 0;
this.isMovingLeft = false;
this.isMovingRight = false;
this.isDead = false;
this.width = 55;
this.height = 40;
//Sprite clipping
this.cx = 0;
this.cy = 0;
this.cwidth = 110;
this.cheight = 80;
this.dir = "left";
this.x = width / 2 - this.width / 2;
this.y = height;
//Function to draw it
this.draw = function() {
try {
if (this.dir == "right") this.cy = 121;
else if (this.dir == "left") this.cy = 201;
else if (this.dir == "right_land") this.cy = 289;
else if (this.dir == "left_land") this.cy = 371;
ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
} catch (e) {}
};
this.jump = function() {
this.vy = -8;
document.getElementById('audio').innerHTML='<audio src="sounds/pup.mp3" preload="auto" autoplay autobuffer></audio>'
};
this.jumpHigh = function() {
this.vy = -16;
document.getElementById('audio').innerHTML='<audio src="sounds/high.mp3" preload="auto" autoplay autobuffer></audio>'
};
};
player = new Player();
//Platform class
function Platform() {
this.width = 70;
this.height = 17;
this.x = Math.random() * (width - this.width);
this.y = position;
position += (height / platformCount);
this.flag = 0;
this.state = 0;
//Sprite clipping
this.cx = 0;
this.cy = 0;
this.cwidth = 105;
this.cheight = 31;
//Function to draw it
this.draw = function() {
try {
if (this.type == 1) this.cy = 0;
else if (this.type == 2) this.cy = 61;
else if (this.type == 3 && this.flag === 0) this.cy = 31;
else if (this.type == 3 && this.flag == 1) this.cy = 1000;
else if (this.type == 4 && this.state === 0) this.cy = 90;
else if (this.type == 4 && this.state == 1) this.cy = 1000;
ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
} catch (e) {}
};
//Platform types
//1: Normal
//2: Moving
//3: Breakable (Go through)
//4: Vanishable
//Setting the probability of which type of platforms should be shown at what score
if (score >= 5000) this.types = [2, 3, 3, 3, 4, 4, 4, 4];
else if (score >= 2000 && score < 5000) this.types = [2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4];
else if (score >= 1000 && score < 2000) this.types = [2, 2, 2, 3, 3, 3, 3, 3];
else if (score >= 500 && score < 1000) this.types = [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3];
else if (score >= 100 && score < 500) this.types = [1, 1, 1, 1, 2, 2];
else this.types = [1];
this.type = this.types[Math.floor(Math.random() * this.types.length)];
//We can't have two consecutive breakable platforms otherwise it will be impossible to reach another platform sometimes!
if (this.type == 3 && broken < 1) {
broken++;
} else if (this.type == 3 && broken >= 1) {
this.type = 1;
broken = 0;
}
this.moved = 0;
this.vx = 1;
}
for (var i = 0; i < platformCount; i++) {
platforms.push(new Platform());
}
//Broken platform object
var Platform_broken_substitute = function() {
this.height = 30;
this.width = 70;
this.x = 0;
this.y = 0;
//Sprite clipping
this.cx = 0;
this.cy = 554;
this.cwidth = 105;
this.cheight = 60;
this.appearance = false;
this.draw = function() {
try {
if (this.appearance === true) ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
else return;
} catch (e) {}
};
};
var platform_broken_substitute = new Platform_broken_substitute();
//Spring Class
var spring = function() {
this.x = 0;
this.y = 0;
this.width = 26;
this.height = 30;
//Sprite clipping
this.cx = 0;
this.cy = 0;
this.cwidth = 45;
this.cheight = 53;
this.state = 0;
this.draw = function() {
try {
if (this.state === 0) this.cy = 445;
else if (this.state == 1) this.cy = 501;
ctx.drawImage(image, this.cx, this.cy, this.cwidth, this.cheight, this.x, this.y, this.width, this.height);
} catch (e) {}
};
};
var Spring = new spring();
function init() {
//Variables for the game
var dir = "left",
jumpCount = 0;
firstRun = false;
//Function for clearing canvas in each consecutive frame
function paintCanvas() {
ctx.clearRect(0, 0, width, height);
}
//Player related calculations and functions
function playerCalc() {
if (dir == "left") {
player.dir = "left";
if (player.vy < -7 && player.vy > -15) player.dir = "left_land";
} else if (dir == "right") {
player.dir = "right";
if (player.vy < -7 && player.vy > -15) player.dir = "right_land";
}
//Adding keyboard controls
document.onkeydown = function(e) {
var key = e.keyCode;
if (key == 37) {
dir = "left";
player.isMovingLeft = true;
} else if (key == 39) {
dir = "right";
player.isMovingRight = true;
}
if(key == 32) {
if(firstRun === true)
init();
else
reset();
}
};
document.onkeyup = function(e) {
var key = e.keyCode;
if (key == 37) {
dir = "left";
player.isMovingLeft = false;
} else if (key == 39) {
dir = "right";
player.isMovingRight = false;
}
};
//Accelerations produces when the user hold the keys
if (player.isMovingLeft === true) {
player.x += player.vx;
player.vx -= 0.15;
} else {
player.x += player.vx;
if (player.vx < 0) player.vx += 0.1;
}
if (player.isMovingRight === true) {
player.x += player.vx;
player.vx += 0.15;
} else {
player.x += player.vx;
if (player.vx > 0) player.vx -= 0.1;
}
//Jump the player when it hits the base
if ((player.y + player.height) > base.y && base.y < height) player.jump();
//Gameover if it hits the bottom
if (base.y > height && (player.y + player.height) > height && player.isDead != "lol") {
player.isDead = true;
document.getElementById('audio').innerHTML='<audio src="sounds/gameover.mp3" preload="auto" autoplay autobuffer></audio>'
}
//Make the player move through walls
if (player.x > width) player.x = 0 - player.width;
else if (player.x < 0 - player.width) player.x = width;
//Movement of player affected by gravity
if (player.y >= (height / 2) - (player.height / 2)) {
player.y += player.vy;
player.vy += gravity;
}
//When the player reaches half height, move the platforms to create the illusion of scrolling and recreate the platforms that are out of viewport...
else {
platforms.forEach(function(p, i) {
if (player.vy < 0) {
p.y -= player.vy;
}
if (p.y > height) {
platforms[i] = new Platform();
platforms[i].y = p.y - height;
}
});
base.y -= player.vy;
player.vy += gravity;
if (player.vy >= 0) {
player.y += player.vy;
player.vy += gravity;
}
score++;
}
//Make the player jump when it collides with platforms
collides();
if (player.isDead === true) gameOver();
}
//Spring algorithms
function springCalc() {
var s = Spring;
var p = platforms[0];
if (p.type == 1 || p.type == 2) {
s.x = p.x + p.width / 2 - s.width / 2;
s.y = p.y - p.height - 10;
if (s.y > height / 1.1) s.state = 0;
s.draw();
} else {
s.x = 0 - s.width;
s.y = 0 - s.height;
}
}
//Platform's horizontal movement (and falling) algo
function platformCalc() {
var subs = platform_broken_substitute;
platforms.forEach(function(p, i) {
if (p.type == 2) {
if (p.x < 0 || p.x + p.width > width) p.vx *= -1;
p.x += p.vx;
}
if (p.flag == 1 && subs.appearance === false && jumpCount === 0) {
subs.x = p.x;
subs.y = p.y;
subs.appearance = true;
jumpCount++;
}
p.draw();
});
if (subs.appearance === true) {
subs.draw();
subs.y += 8;
}
if (subs.y > height) subs.appearance = false;
}
function collides() {
//Platforms
platforms.forEach(function(p, i) {
if (player.vy > 0 && p.state === 0 && (player.x + 15 < p.x + p.width) && (player.x + player.width - 15 > p.x) && (player.y + player.height > p.y) && (player.y + player.height < p.y + p.height)) {
if (p.type == 3 && p.flag === 0) {
p.flag = 1;
jumpCount = 0;
return;
} else if (p.type == 4 && p.state === 0) {
player.jump();
p.state = 1;
} else if (p.flag == 1) return;
else {
player.jump();
}
}
});
//Springs
var s = Spring;
if (player.vy > 0 && (s.state === 0) && (player.x + 15 < s.x + s.width) && (player.x + player.width - 15 > s.x) && (player.y + player.height > s.y) && (player.y + player.height < s.y + s.height)) {
s.state = 1;
player.jumpHigh();
}
}
function updateScore() {
var scoreText = document.getElementById("score");
scoreText.innerHTML = score;
}
function gameOver() {
platforms.forEach(function(p, i) {
p.y -= 12;
});
if(player.y > height/2 && flag === 0) {
player.y -= 8;
player.vy = 0;
}
else if(player.y < height / 2) flag = 1;
else if(player.y + player.height > height) {
showGoMenu();
hideScore();
player.isDead = "lol";
}
}
//Function to update everything
function update() {
paintCanvas();
platformCalc();
springCalc();
playerCalc();
player.draw();
base.draw();
updateScore();
}
menuLoop = function(){return;};
animloop = function() {
update();
requestAnimFrame(animloop);
};
animloop();
hideMenu();
showScore();
}
function reset() {
hideGoMenu();
showScore();
player.isDead = false;
flag = 0;
position = 0;
score = 0;
base = new Base();
player = new Player();
Spring = new spring();
platform_broken_substitute = new Platform_broken_substitute();
platforms = [];
for (var i = 0; i < platformCount; i++) {
platforms.push(new Platform());
}
}
//Hides the menu
function hideMenu() {
var menu = document.getElementById("mainMenu");
menu.style.zIndex = -1;
}
//Shows the game over menu
function showGoMenu() {
var menu = document.getElementById("gameOverMenu");
menu.style.zIndex = 1;
menu.style.visibility = "visible";
var scoreText = document.getElementById("go_score");
scoreText.innerHTML = "Ваш результат " + score + " очков!";
}
//Hides the game over menu
function hideGoMenu() {
var menu = document.getElementById("gameOverMenu");
menu.style.zIndex = -1;
menu.style.visibility = "hidden";
}
//Show ScoreBoard
function showScore() {
var menu = document.getElementById("scoreBoard");
menu.style.zIndex = 1;
}
//Hide ScoreBoard
function hideScore() {
var menu = document.getElementById("scoreBoard");
menu.style.zIndex = -1;
}
function playerJump() {
player.y += player.vy;
player.vy += gravity;
if (player.vy > 0 &&
(player.x + 15 < 260) &&
(player.x + player.width - 15 > 155) &&
(player.y + player.height > 475) &&
(player.y + player.height < 500))
player.jump();
if (dir == "left") {
player.dir = "left";
if (player.vy < -7 && player.vy > -15) player.dir = "left_land";
} else if (dir == "right") {
player.dir = "right";
if (player.vy < -7 && player.vy > -15) player.dir = "right_land";
}
//Adding keyboard controls
document.onkeydown = function(e) {
var key = e.keyCode;
if (key == 37) {
dir = "left";
player.isMovingLeft = true;
} else if (key == 39) {
dir = "right";
player.isMovingRight = true;
}
if(key == 32) {
if(firstRun === true) {
init();
firstRun = false;
}
else
reset();
}
};
document.onkeyup = function(e) {
var key = e.keyCode;
if (key == 37) {
dir = "left";
player.isMovingLeft = false;
} else if (key == 39) {
dir = "right";
player.isMovingRight = false;
}
};
//Accelerations produces when the user hold the keys
if (player.isMovingLeft === true) {
player.x += player.vx;
player.vx -= 0.15;
} else {
player.x += player.vx;
if (player.vx < 0) player.vx += 0.1;
}
if (player.isMovingRight === true) {
player.x += player.vx;
player.vx += 0.15;
} else {
player.x += player.vx;
if (player.vx > 0) player.vx -= 0.1;
}
//Jump the player when it hits the base
if ((player.y + player.height) > base.y && base.y < height) player.jump();
//Make the player move through walls
if (player.x > width) player.x = 0 - player.width;
else if (player.x < 0 - player.width) player.x = width;
player.draw();
}
function update() {
ctx.clearRect(0, 0, width, height);
playerJump();
}
menuLoop = function() {
update();
requestAnimFrame(menuLoop);
};
menuLoop();
}
document.addEventListener("DOMContentLoaded", startGame, false);
<!DOCTYPE HTML>
<html>
<head>
<title>Doodle Jump</title>
<style type="text/css">
#import url(Gloria%20Hallelujah);
*{box-sizing: border-box;}
body {
margin: 0; padding: 0;
font-family: 'Gloria Hallelujah', cursive;
}
.container {
height: 552px;
width: 422px;
position: relative;
margin: 20px auto;
overflow: hidden;
}
canvas {
height: 552px;
width: 422px;
display: block;
background: url(images/Y0BMP.png) top left;
}
#scoreBoard {
width: 420px;
height: 50px;
background: rgba(182, 200, 220, 0.7);
position: absolute;
top: -3px;
left: 0;
z-index: -1;
border-image: url(images/5BBsR.png) 100 5 round;
}
#scoreBoard p {
font-size: 20px;
padding: 0;
line-height: 47px;
margin: 0px 0 0 5px;
}
img {display: none}
#mainMenu, #gameOverMenu {
height: 100%;
width: 100%;
text-align: center;
position: absolute;
top: 0;
left: 0;
z-index: 2;
}
#gameOverMenu {
visibility: hidden;
}
h2, h3, h1 {font-weight: normal}
h1 {
font-size: 60px;
color: #5a5816;
transform: rotate(-10deg);
margin: 0px;
}
h3 {text-align: right; margin: -10px 20px 0 0; color: #5e96be}
h3 a {color: #5a5816}
.button {
width: 105px;
height: 31px;
background: url(images/2WEhF.png) 0 0 no-repeat;
display: block;
color: #000;
font-size: 12px;
line-height: 31px;
text-decoration: none;
position: absolute;
left: 50%;
bottom: 50px;
margin-left: -53px;
}
.info {position: absolute; right: 20px; bottom: 00px; margin: 0; color: green}
.info .key {
width: 16px;
height: 16px;
background: url(images/2WEhF.png) no-repeat;
text-indent: -9999px;
display: inline-block;
}
.info .key.left {background-position: -92px -621px;}
.info .key.right {background-position: -92px -641px;}
</style>
</head>
<body><div style="position:absolute;z-index:999;padding:10px;top:0;right:0;background:#000" id="sxz03">
<div style="float:right;padding-left:10px"><img onclick="document.getElementById('sxz03').style.display='none'" src="images/x.gif" width="15" alt="" /></div>
<br>
<div style="position:absolute;top:-100px"></div>
</div>
<div class="container">
<canvas id="canvas"></canvas>
<div id="mainMenu">
<h1>doodle jump</h1>
<h3>A HTML5 game</h3>
<a class="button" href="javascript:init()">Play</a>
</div>
<div id="gameOverMenu">
<h1>Game Over!</h1>
<h3 id="go_score">Your score was ...</h3>
<a class="button" href="javascript:reset()">Play Again</a>
</div>
<!-- Preloading image ;) -->
<img id="sprite" src="images/2WEhF.png"/>
<div id="scoreBoard">
<p id="score">0</p>
</div>
</div>
<div id="audio"></div>
<script src="jquery.min.js"></script>
<script src="game.js"></script>
</body>
</html>
So when I run this, the intro works, but when I click the play button, nothing happens. If you want to run this code, I will put a download link for the folder that I used in this question.

Can't draw canvas

I have a few problem with html5. I created a new webpage and add canvas at the middle of that page.Then created new js file that have a script for canvas and import it to webpage but webpage's canvas still nothing happen.
This is my code. index.html in root folder, style.css in css/ , script.js in js/
function startnewgame(){
score =0;
player.hp =10;
timewhenlasthit = Date.now();
timewhengamestart = Date.now();
frameCount =0;
enemylist ={} ;
bulletlist ={};
upgradelist ={};
randomspwanenemy();
}
function update(){
ctx.clearRect(0,0,WIDTH,HEIGHT);
ctx.fillText("Score = "+score,200,30);
score ++;
frameCount++;
if(frameCount % 100 === 0)random
spwanenemy();
if(frameCount % 75 === 0)randomspwanupgrade();
player.attackcounter += player.atkspd;
updateplayerposition();
drawplayer(player);
for(var i in bulletlist){
updateplayer(bulletlist[i]);
bulletlist[i].timer++;
var toRemove = false ;
if (bulletlist[i].timer > 100) {
toRemove = true;
}
for (var j in enemylist) {
var cod = getdistant(bulletlist[i],enemylist[j]);
if(cod){
toRemove = true;
delete enemylist[j];
score+=1000;
break;
}
}
if(toRemove)delete bulletlist[i];
}
for(var i in upgradelist){
updateplayer(upgradelist[i]);
var temp = getdistant(player,upgradelist[i]);
if(temp){
if(upgradelist[i].type === 'score'){
score += 100;
}
if(upgradelist[i].type ==='atkspd'){
player.atkspd +=5;
}
delete upgradelist[i];
}
}
for(var i in enemylist){
updateplayer(enemylist[i]);
var temp = getdistant(player,enemylist[i]);
death(temp);
}
}
function drawplayer(x){
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x-x.width/2,x.y-x.height/2,x.width,x.height);
ctx.restore();
ctx.fillText("HP = "+player.hp,20,30);
ctx.fillText("bullet = "+player.attackcounter,20,80);
}
function drawenemy(x){
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x-x.width/2,x.y-x.height/2,x.width,x.height);
ctx.restore();
}
function updateplayer(x){
if(x.x+x.width/2>=WIDTH){
x.x=WIDTH-x.width/2;
x.spdX=-x.spdX;
}
if(x.x-x.width/2<=0){
x.x = x.width/2;
x.spdX=-x.spdX;
}
if(x.y+x.height/2>=HEIGHT){
x.y = HEIGHT-x.height/2;
x.spdY=-x.spdY;
}
if(x.y-x.height/2<=0){
x.y = x.height/2;
x.spdY=-x.spdY;
}
x.x+=x.spdX;
x.y+=x.spdY;
drawenemy(x);
}
function adde(id,x,y,spdX,spdY,width,height){
var earth ={
name:'A',
x : x,
spdX :spdX,
y : y,
spdY : spdY,
id : id,
width : width,
height : height,
color : 'red'
};
enemylist[id]= earth;
}
function addupgrade(id,x,y,spdX,spdY,width,height,color,type){
var earth ={
name:'A',
x : x,
spdX :spdX,
y : y,
spdY : spdY,
id : id,
width : width,
height : height,
color : color,
type : type
};
upgradelist[id]= earth;
}
function addbullet(id,x,y,spdX,spdY,width,height){
var earth ={
name:'A',
x : x,
spdX :spdX,
y : y,
spdY : spdY,
id : id,
width : width,
height : height,
color : 'black',
timer: 0
};
bulletlist[id]= earth;
}
function getdistant(earth1,earth2){
var rect1 ={
x:earth1.x-earth1.width/2,
y:earth1.y-earth1.height/2,
width:earth1.width,
height:earth1.height
};
var rect2 ={
x:earth2.x-earth2.width/2,
y:earth2.y-earth2.height/2,
width:earth2.width,
height:earth2.height
};
return testcol(rect1,rect2);
}
function death(x){
if(x){
player.hp -= 1;
if(player.hp == 0){
var ttime = Date.now() - timewhengamestart;
timewhengamestart = Date.now();
console.log("DEAD!! you score "+ score );
startnewgame();
}
}
}
function randomspwanenemy(){
var x = Math.random()*WIDTH;
var y = Math.random()*HEIGHT;
var height = 10 +Math.random()*30;
var width= 10 + Math.random()*30;
var spdY = Math.random()*5 +5;
var spdX = Math.random()*5 +5;
var id = Math.random();
//console.log(x,y,height,width,spdX,spdY);
adde(id,x,y,spdX,spdY,width,height);
}
function randomspwanupgrade(){
var x = Math.random()*WIDTH;
var y = Math.random()*HEIGHT;
var height = 10 ;
var width= 10 ;
var spdY = 0;
var spdX = 0;
var id = Math.random();
var sample = Math.random();
if(sample >0.5){
var type = 'score';
var color ='lightblue';
}
else {
var type = 'atkspd';
var color = 'purple';
}
addupgrade(id,x,y,spdX,spdY,width,height,color,type);
}
function randomspwanbullet(earth,overangle){
var x = player.x;
var y = player.y;
var height = 10 ;
var width= 10 ;
//var tid = pp(Math.random());
var angle = earth.aimAngle;
if (overangle !== undefined) {
angle = overangle;
}
var spdY = (Math.sin(angle)*10 );
var spdX = (Math.cos(angle)*10 );
var id = Math.random();
addbullet(id,x,y,spdX,spdY,width,height);
}
function testcol(earth1,earth2){
var lasthit = Date.now()-timewhenlasthit;
if( earth1.x <= earth2.x+earth2.width
&& earth2.x <= earth1.x+earth1.width
&& earth1.y <= earth2.y+earth2.height
&& earth2.y <= earth1.y+earth1.height
&& lasthit >= 1000)
{
timewhenlasthit=Date.now();
return 1;
}
}
function pp(x){
if(x>0.5)return 1;
else return -1;
}
var canvas = document.getElementById("ctx")
var ctx = canvas.getContext('2d');
var frameCount =0;
ctx.font = '30 px Arial';
var score =0
var HEIGHT = 500;
var WIDTH = 500;
var timewhengamestart = Date.now();
var timewhenlasthit = Date.now();
document.onmousemove = function(mouse){
var mouseX = mouse.clientX- document.getElementById('ctx').getBoundingClientRect().left;
var mouseY = mouse.clientY-document.getElementById('ctx').getBoundingClientRect().top;;
mouseX -= player.x;
mouseY -= player.y;
player.aimAngle = Math.atan2(mouseY,mouseX) ;
/* if(mouseX <player.width/2)mouseX=player.width/2;
if(mouseX>WIDTH-player.width/2)mouseX = WIDTH-player.width/2;
if(mouseY<player.height/2)mouseY=player.height/2;
if(mouseY>HEIGHT-player.height/2)mouseY = HEIGHT-player.height/2;
player.x = mouseX;
player.y = mouseY;*/
}
document.onclick = function(mouse){
if (player.attackcounter > 25) {
randomspwanbullet(player,player.aimAngle);
player.attackcounter = 0;
}
}
document.oncontextmenu = function(mouse){
if (player.attackcounter > 1000) {
for (var i = 1; i < 361; i++) {
randomspwanbullet(player,i);
}
player.attackcounter = 0;
}
mouse.preventDefault();
}
document.onkeydown = function(event){
if (event.keyCode===68) {
player.pressingRight = true;
}
else if (event.keyCode===83) {
player.pressingDown = true ;
}
else if (event.keyCode===65) {
player.pressingLeft = true ;
}
else if (event.keyCode===87) {
player.pressingUp = true ;
}
}
document.onkeyup = function(event){
if (event.keyCode===68) {
player.pressingRight = false;
}
else if (event.keyCode===83) {
player.pressingDown = false ;
}
else if (event.keyCode===65) {
player.pressingLeft = false ;
}
else if (event.keyCode===87) {
player.pressingUp = false ;
}
}
function updateplayerposition() {
if(player.pressingRight)player.x+=10
if(player.pressingLeft)player.x-=10
if(player.pressingUp)player.y-=10
if(player.pressingDown)player.y+=10
if(player.x <player.width/2)player.x=player.width/2;
if(player.x>WIDTH-player.width/2)player.x = WIDTH-player.width/2;
if(player.y<player.height/2)player.y=player.height/2;
if(player.y>HEIGHT-player.height/2)player.y = HEIGHT-player.height/2;
}
var player = {
name :'E' ,
x : 40 ,
spdX : 30 ,
y : 40 ,
spdY : 5 ,
hp : 10 ,
width : 20 ,
height : 20,
atkspd : 1,
color : 'green',
attackcounter : 0,
pressingDown : false,
pressingUp : false,
pressingLeft : false,
pressingRight : false,
aimAngle : 0
};
var enemylist ={};
var upgradelist = {};
var bulletlist = {};
function drawCanvas() {
startnewgame();
setInterval(update,40);
}
#header{
background: #202020 ;
font-size: 36px;
text-align: center;
padding:0;
margin: 0;
font-style: italic;
color: #FFFFFF;
}
#ctx{
border: 2px solid #000000;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
margin-top: 20px;
position: absolute;
background: #ffffff;
}
#leftmenu{
margin-top: 20px;
margin-bottom: 65px;
padding-right: 10px;
float: left;
width: 300px;
height: 580px;
background: #C8C8C8;
border-radius: 10px;
border: 10px solid #002699;
}
nav#leftmenu h2{
text-align: center;
font-size: 30px;
}
nav#leftmenu ul{
list-style: none;
padding: 0;
}
nav#leftmenu li{
list-style: none;
font-size: 24px;
margin-top: 20px;
border-bottom: 2px dashed #000;
margin-left: 0px;
text-align: center;
}
nav#leftmenu a{
text-decoration: none;
font-weight: bold;
color: #1c478e;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Awesome Game</title>
<link href="css/style.css" rel="stylesheet">
<script src="js/script.js" type="text/javascript"></script>
</head>
<body onload="drawCanvas();" style="background: linear-gradient(to bottom left, #0000ff -10%, #33ccff 100%);">
<h1 id="header">Welcome to my GAME!!</h1>
<!--Canvas-->
<canvas id ="ctx" width ="800" height="600" style = "border:1px solid #000000;"></canvas>
<!--leftMenu-->
<section>
<nav id="leftmenu">
<h2>Menu</h2>
<ul>
<li>New Game</li>
<li>Pause Game</li>
<li>Option</li>
<li>End it now</li>
</ul>
</nav>
</section>
</body>
</html>
Ps. this ti my first post,Sorry if I did something wrong.
Edit: canvas id from canvas to ctx
Here's a snippet that's working and drawing correctly. It was just a little typo in the update function, writing it like:
if (frameCount % 100 === 0) random
spwanenemy();
instead of:
if (frameCount % 100 === 0) randomspwanenemy();
So, yea, just a little typo! Understanding errors from the developer console (F12) and spotting what's wrong is a vital skill. Keep practicing!
function startnewgame() {
score = 0;
player.hp = 10;
timewhenlasthit = Date.now();
timewhengamestart = Date.now();
frameCount = 0;
enemylist = {};
bulletlist = {};
upgradelist = {};
randomspwanenemy();
}
function update() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
ctx.fillText("Score = " + score, 200, 30);
score++;
frameCount++;
if (frameCount % 100 === 0) randomspwanenemy();
if (frameCount % 75 === 0) randomspwanupgrade();
player.attackcounter += player.atkspd;
updateplayerposition();
drawplayer(player);
for (var i in bulletlist) {
updateplayer(bulletlist[i]);
bulletlist[i].timer++;
var toRemove = false;
if (bulletlist[i].timer > 100) {
toRemove = true;
}
for (var j in enemylist) {
var cod = getdistant(bulletlist[i], enemylist[j]);
if (cod) {
toRemove = true;
delete enemylist[j];
score += 1000;
break;
}
}
if (toRemove) delete bulletlist[i];
}
for (var i in upgradelist) {
updateplayer(upgradelist[i]);
var temp = getdistant(player, upgradelist[i]);
if (temp) {
if (upgradelist[i].type === 'score') {
score += 100;
}
if (upgradelist[i].type === 'atkspd') {
player.atkspd += 5;
}
delete upgradelist[i];
}
}
for (var i in enemylist) {
updateplayer(enemylist[i]);
var temp = getdistant(player, enemylist[i]);
death(temp);
}
}
function drawplayer(x) {
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x - x.width / 2, x.y - x.height / 2, x.width, x.height);
ctx.restore();
ctx.fillText("HP = " + player.hp, 20, 30);
ctx.fillText("bullet = " + player.attackcounter, 20, 80);
}
function drawenemy(x) {
ctx.save();
ctx.fillStyle = x.color;
ctx.fillRect(x.x - x.width / 2, x.y - x.height / 2, x.width, x.height);
ctx.restore();
}
function updateplayer(x) {
if (x.x + x.width / 2 >= WIDTH) {
x.x = WIDTH - x.width / 2;
x.spdX = -x.spdX;
}
if (x.x - x.width / 2 <= 0) {
x.x = x.width / 2;
x.spdX = -x.spdX;
}
if (x.y + x.height / 2 >= HEIGHT) {
x.y = HEIGHT - x.height / 2;
x.spdY = -x.spdY;
}
if (x.y - x.height / 2 <= 0) {
x.y = x.height / 2;
x.spdY = -x.spdY;
}
x.x += x.spdX;
x.y += x.spdY;
drawenemy(x);
}
function adde(id, x, y, spdX, spdY, width, height) {
var earth = {
name: 'A',
x: x,
spdX: spdX,
y: y,
spdY: spdY,
id: id,
width: width,
height: height,
color: 'red'
};
enemylist[id] = earth;
}
function addupgrade(id, x, y, spdX, spdY, width, height, color, type) {
var earth = {
name: 'A',
x: x,
spdX: spdX,
y: y,
spdY: spdY,
id: id,
width: width,
height: height,
color: color,
type: type
};
upgradelist[id] = earth;
}
function addbullet(id, x, y, spdX, spdY, width, height) {
var earth = {
name: 'A',
x: x,
spdX: spdX,
y: y,
spdY: spdY,
id: id,
width: width,
height: height,
color: 'black',
timer: 0
};
bulletlist[id] = earth;
}
function getdistant(earth1, earth2) {
var rect1 = {
x: earth1.x - earth1.width / 2,
y: earth1.y - earth1.height / 2,
width: earth1.width,
height: earth1.height
};
var rect2 = {
x: earth2.x - earth2.width / 2,
y: earth2.y - earth2.height / 2,
width: earth2.width,
height: earth2.height
};
return testcol(rect1, rect2);
}
function death(x) {
if (x) {
player.hp -= 1;
if (player.hp == 0) {
var ttime = Date.now() - timewhengamestart;
timewhengamestart = Date.now();
console.log("DEAD!! you score " + score);
startnewgame();
}
}
}
function randomspwanenemy() {
var x = Math.random() * WIDTH;
var y = Math.random() * HEIGHT;
var height = 10 + Math.random() * 30;
var width = 10 + Math.random() * 30;
var spdY = Math.random() * 5 + 5;
var spdX = Math.random() * 5 + 5;
var id = Math.random();
//console.log(x,y,height,width,spdX,spdY);
adde(id, x, y, spdX, spdY, width, height);
}
function randomspwanupgrade() {
var x = Math.random() * WIDTH;
var y = Math.random() * HEIGHT;
var height = 10;
var width = 10;
var spdY = 0;
var spdX = 0;
var id = Math.random();
var sample = Math.random();
if (sample > 0.5) {
var type = 'score';
var color = 'lightblue';
} else {
var type = 'atkspd';
var color = 'purple';
}
addupgrade(id, x, y, spdX, spdY, width, height, color, type);
}
function randomspwanbullet(earth, overangle) {
var x = player.x;
var y = player.y;
var height = 10;
var width = 10;
//var tid = pp(Math.random());
var angle = earth.aimAngle;
if (overangle !== undefined) {
angle = overangle;
}
var spdY = (Math.sin(angle) * 10);
var spdX = (Math.cos(angle) * 10);
var id = Math.random();
addbullet(id, x, y, spdX, spdY, width, height);
}
function testcol(earth1, earth2) {
var lasthit = Date.now() - timewhenlasthit;
if (earth1.x <= earth2.x + earth2.width && earth2.x <= earth1.x + earth1.width && earth1.y <= earth2.y + earth2.height && earth2.y <= earth1.y + earth1.height && lasthit >= 1000) {
timewhenlasthit = Date.now();
return 1;
}
}
function pp(x) {
if (x > 0.5) return 1;
else return -1;
}
var canvas = document.getElementById("ctx")
var ctx = canvas.getContext('2d');
var frameCount = 0;
ctx.font = '30 px Arial';
var score = 0
var HEIGHT = 500;
var WIDTH = 500;
var timewhengamestart = Date.now();
var timewhenlasthit = Date.now();
document.onmousemove = function(mouse) {
var mouseX = mouse.clientX - document.getElementById('ctx').getBoundingClientRect().left;
var mouseY = mouse.clientY - document.getElementById('ctx').getBoundingClientRect().top;;
mouseX -= player.x;
mouseY -= player.y;
player.aimAngle = Math.atan2(mouseY, mouseX);
/* if(mouseX <player.width/2)mouseX=player.width/2;
if(mouseX>WIDTH-player.width/2)mouseX = WIDTH-player.width/2;
if(mouseY<player.height/2)mouseY=player.height/2;
if(mouseY>HEIGHT-player.height/2)mouseY = HEIGHT-player.height/2;
player.x = mouseX;
player.y = mouseY;*/
}
document.onclick = function(mouse) {
if (player.attackcounter > 25) {
randomspwanbullet(player, player.aimAngle);
player.attackcounter = 0;
}
}
document.oncontextmenu = function(mouse) {
if (player.attackcounter > 1000) {
for (var i = 1; i < 361; i++) {
randomspwanbullet(player, i);
}
player.attackcounter = 0;
}
mouse.preventDefault();
}
document.onkeydown = function(event) {
if (event.keyCode === 68) {
player.pressingRight = true;
} else if (event.keyCode === 83) {
player.pressingDown = true;
} else if (event.keyCode === 65) {
player.pressingLeft = true;
} else if (event.keyCode === 87) {
player.pressingUp = true;
}
}
document.onkeyup = function(event) {
if (event.keyCode === 68) {
player.pressingRight = false;
} else if (event.keyCode === 83) {
player.pressingDown = false;
} else if (event.keyCode === 65) {
player.pressingLeft = false;
} else if (event.keyCode === 87) {
player.pressingUp = false;
}
}
function updateplayerposition() {
if (player.pressingRight) player.x += 10
if (player.pressingLeft) player.x -= 10
if (player.pressingUp) player.y -= 10
if (player.pressingDown) player.y += 10
if (player.x < player.width / 2) player.x = player.width / 2;
if (player.x > WIDTH - player.width / 2) player.x = WIDTH - player.width / 2;
if (player.y < player.height / 2) player.y = player.height / 2;
if (player.y > HEIGHT - player.height / 2) player.y = HEIGHT - player.height / 2;
}
var player = {
name: 'E',
x: 40,
spdX: 30,
y: 40,
spdY: 5,
hp: 10,
width: 20,
height: 20,
atkspd: 1,
color: 'green',
attackcounter: 0,
pressingDown: false,
pressingUp: false,
pressingLeft: false,
pressingRight: false,
aimAngle: 0
};
var enemylist = {};
var upgradelist = {};
var bulletlist = {};
function drawCanvas() {
startnewgame();
setInterval(update, 40);
}
#header {
background: #202020;
font-size: 36px;
text-align: center;
padding: 0;
margin: 0;
font-style: italic;
color: #FFFFFF;
}
#ctx {
border: 2px solid #000000;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
margin-top: 20px;
position: absolute;
background: #ffffff;
}
#leftmenu {
margin-top: 20px;
margin-bottom: 65px;
padding-right: 10px;
float: left;
width: 300px;
height: 580px;
background: #C8C8C8;
border-radius: 10px;
border: 10px solid #002699;
}
nav#leftmenu h2 {
text-align: center;
font-size: 30px;
}
nav#leftmenu ul {
list-style: none;
padding: 0;
}
nav#leftmenu li {
list-style: none;
font-size: 24px;
margin-top: 20px;
border-bottom: 2px dashed #000;
margin-left: 0px;
text-align: center;
}
nav#leftmenu a {
text-decoration: none;
font-weight: bold;
color: #1c478e;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Awesome Game</title>
<link href="css/style.css" rel="stylesheet">
<script src="js/script.js" type="text/javascript"></script>
</head>
<body onload="drawCanvas();" style="background: linear-gradient(to bottom left, #0000ff -10%, #33ccff 100%);">
<h1 id="header">Welcome to my GAME!!</h1>
<!--Canvas-->
<canvas id="ctx" width="800" height="600" style="border:1px solid #000000;"></canvas>
<!--leftMenu-->
<section>
<nav id="leftmenu">
<h2>Menu</h2>
<ul>
<li>New Game
</li>
<li>Pause Game
</li>
<li>Option
</li>
<li>End it now
</li>
</ul>
</nav>
</section>
</body>
</html>

Categories

Resources