JavaScript Snake Game with two Snakes (Local Mutiplayer) - javascript

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>

Related

Check if a certain value has been logged to the console

I'm trying to make an adventure game and am trying to check if the value 100 ms have elapsed is in the console.log.
Please comment a fix or some way I can do that i would really be happy if you helped!!
All I need is a way for the code to check if the console.log() has a certain value in it. I need a fix or way to check if it has that value.
var ground = createSprite(0, 425);
ground.setAnimation("ground_grass");
ground.width = 1000000000;
ground.setCollider("rectangle", 0, 25, 1000000000, 0.5);
var player = createSprite(200, 0);
player.setAnimation("player_fall");
player.scale = 0.4;
var hpbar = createSprite(85, 25);
hpbar.setAnimation("hpbar");
hpbar.scale = 0.3;
function draw() {
background(rgb(102, 204, 255));
//player mechanics
player.collide(ground);
player.setCollider("rectangle", -19, 75, 120, 210);
//move right
if (keyDown("d")) {
player.setAnimation("player_run");
ground.x = ground.x + 6;
} else if ((keyWentUp("d"))) {
player.setAnimation("player_idle");
}
//move left
if (keyDown("a")) {
player.setAnimation("player_run_left");
ground.x = ground.x - 6;
} else if ((keyWentUp("a"))) {
player.setAnimation("player_idle_left");
}
//crouch
if (keyWentDown("s")) {
player.setAnimation("player_crouch");
} else if ((keyWentDown("w"))) {
player.setAnimation("player_idle");
}
//jump
if (keyWentDown("w")) {
player.setAnimation("player_jump");
player.velocityY = -7;
}
if (player.y < 200) {
player.velocityY = player.velocityY + 1.5;
player.setAnimation("player_fall");
}
if (player.y > 300) {
player.setAnimation("player_idle");
player.velocityY = 0;
player.y = 300;
}
//slide right
if (keyWentDown("e")) {
ground.velocityX = ground.velocityX + 25;
player.setAnimation("player_slide");
} else if ((keyWentUp("e"))) {
ground.velocityX = ground.velocityX - 25;
player.setAnimation("player_idle");
}
//slide left
if (keyWentDown("q")) {
ground.velocityX = ground.velocityX - 25;
player.setAnimation("player_slide_left");
} else if ((keyWentUp("q"))) {
ground.velocityX = ground.velocityX + 25;
player.setAnimation("player_idle_left");
}
//attack
if (keyWentDown("space")) {
player.setAnimation("attack");
player.x = player.x + 0.001;
setTimeout(function() {
console.log("10000 milliseconds have elapsed");
}, 10000);
if (player.x + 0.001) {
player.setAnimation("attack");
}
if (console.log("10000 milliseconds have elapsed")) {
player.setAnimation("player_idle");
}
}
drawSprites();
}

How to move an object across a game board. Multiple Objects

I am an extreme beginner in the field of P5.JS. I am way more knowledgeable in Java which will be apparent in my broken code. I have attempted a multitude of Java approaches to cycling through objects of the same class and applying methods to them. My attempt is to implement buttons that will move them forward as of now and once I understand that move on to more complicated interactions.
https://openprocessing.org/sketch/1564721 6
This is the link to the code I am attempting to fix it currently, but if you have any tips or advice for streamlining this please let me know.
var gridCellSizeX = 80;
var gridCellSizeY = 100;
var gridAlpha = 1000;
let img;
var gridCellSizeSlider;
turnValue = 1;
var count = 1;
var gameOn = true;
var forward = false;
function preload() {
img = loadImage('vagg02.jpg');
}
function setup() {
createCanvas(800, 600);
image(img, 0,0,800,500);
image( img ,0, 500, 800,100);
stroke(0, gridAlpha);
for (var x = 0; x < width; x += gridCellSizeX) {
line(x, 0, x, 500);
}
for (var y = 0; y < height; y += gridCellSizeY) {
line(0, y, width, y);
}
token1 = new token(15, 5, 100, 5000, 'reb', 1)
token2 = new token(15, 205, 100, 5000,'reb', 2 )
token3 = new token(15, 405, 100, 5000, 'reb', 3)
token4 = new token(735, 5, 100, 5000,'union', 4)
token5 = new token(735, 205, 100, 5000, 'union', 5)
token6 = new token(735, 405, 100, 5000, 'union', 6)
const tokens = new Array(token1, token2, token3, token4, token5, token6);
forwardButton = createButton('Move -->')
forwardButton.position(300, 525);
forwardButton.mousePressed(moveForward());
//button = createButton('Move -->'); button.position(300, 525); button.mousePressed();
button2 = createButton('Move Up');
button2.position(400, 525);
button2.mousePressed();
button3 = createButton('Move Down');
button3.position(500, 525);
button3.mousePressed();
button4 = createButton('Move <--');
button4.position(600, 525);
button4.mousePressed();
}
function draw() {
if(forward == true) token1.x =+ 500;
//for(let i = 0; gameOn == true; i++){ if(i > 6){ i = 0; }}
}
function mousePressed() {
if (mouseX >= 300 && mouseX <= 325 &&
mouseY >= 525 && mouseY <= 500){
token1.moveForward();
}
return false;
}
// new file token
class token {
constructor(xpos, ypos, t, a, s, turn) {
this.x = xpos;
this.y = ypos;
this.troopSize = t / 2;
this.accuracy = a / 100.0;
this.side = s;
this.moveTurn = turn;
this.loaded = true;
if(this.side == 'reb'){
fill('red');
rect(this.x, this.y, this.troopSize, 90)
}
if(this.side == 'union'){
fill('blue');
rect(this.x, this.y, this.troopSize, 90)
}
}
getToken(){
if(count > 6){
count = 1;
}
if(count == 1) {
return token1;
}
else if(count == 2){
return token2;
}
else if(count == 3){
return token3;
}
else if(count == 4){
return token4;
}
else if(count == 5){
return token5;
}
else if(count == 6){
return token6;
}
count++;
}
///////// Beginning of Basic Functions for the TOKEN CLASS
moveForward(){
if(this.side == 'reb'){
token1.x += 50;
redraw(token1);
}
if(this.side == 'union'){
this.x += -50;
redraw();
}
}
////
moveBackward(){
if(this.side == 'reb'){
this.x = this.x - 50;
}
if(this.side == 'union'){
this.x = this.x + 50;
}
}
/////
fire(){
if(loaded == true){
}
}
//////
load(){
}
///////
fixBayonet(){
}
////////
charge(){
}
///////// END of Basic Functions for the TOKEN CLASS
}

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.

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.

How to clear image right into next html canvas games?

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!

Categories

Resources