Image stops for a second while switching arrow keys - javascript

I have another question. When I move the main player image Left or Right it moves great except for when you are moving right and then you hurry and press the left key while the right key is still down, the image stops for a second and then it decides to move left. Vise-Versa.
Main.js
var getPlatF1POSX = 0;
var getPlatF1POSY = 0;
var addVar = 0;
var addVar2 = 0;
var addVar3 = 0;
function loadGame() {
document.getElementsByTagName("DIV")[4].style.visibility = "visible";
addEventListener('mousemove', getData, false);
addEventListener('keydown', movePlayer, false);
addEventListener('keyup', stopPlayer, false);
movePlat();
moveP();
document.getElementById("player").style.left = xPos + "px";
document.getElementById("player").style.top = yPos + "px";
}
function getData(gData) {
}
var thisThis = 1;
var moveBlock1 = 350;
var stLandT = 0;
var gPos = "";
var rightPos = false;
var leftPos = false;
function movePlat() {
}
function movePlayer(mPlayer) {
switch (mPlayer.keyCode) {
case 39: // RIGHT
if (stLandT == 0 && gPos == "" && rightPos == false) {
setThis = setTimeout(landT, 500);
thisSet = setTimeout(moveLand, 30);
stLandT = 1;
}
gPos = "RIGHT";
rightPos = true;
leftPos = false;
break;
case 37: // LEFT
if (stLandT == 0 && gPos == "" && leftPos == false) {
setThis = setTimeout(landT, 500);
thisSet = setTimeout(moveLand, 30);
stLandT = 1;
}
gPos = "LEFT";
rightPos = false;
leftPos = true;
break;
case 38: // UP
break;
case 40: // DOWN
break;
}
}
function stopPlayer(sPlayer) {
switch (sPlayer.keyCode) {
case 39:
clearTimeout(setThis);
clearTimeout(thisSet);
stLandT = 0;
gPos = "";
rightPos = false;
leftPos = false;
break;
case 37:
clearTimeout(setThis);
clearTimeout(thisSet);
stLandT = 0;
gPos = "";
rightPos = false;
leftPos = false;
break;
}
}
Move Land And Player
var cTAdd = 0;
var setThis = 1;
var GAPlayer = 3;
function landT() {
setThis = setTimeout(landT, 500);
if (xPos >= 500) {
cTAdd = Math.floor(Math.random() * 100 + 1);
var block00 = document.createElement("img");
if (cTAdd > 0 && cTAdd < 25) {
block00.src = "images/sep2.png";
}
if (cTAdd > 25 && cTAdd < 50) {
block00.src = "images/sep1.png";
}
if (cTAdd > 50 && cTAdd < 100) {
block00.src = "images/platform00.png";
}
document.getElementById("land01").appendChild(block00);
var block01 = document.createElement("img");
var getB = block01.getBoundingClientRect();
if (cTAdd > 0 && cTAdd < 25) {
block01.src = "images/platform00.png";
}
if (cTAdd > 25 && cTAdd < 50) {
block01.src = "images/sep2.png";
}
if (cTAdd > 50 && cTAdd < 100) {
block01.src = "images/sep1.png";
}
document.getElementById("land00").appendChild(block01);
GAPlayer = GAPlayer + 2;
}
}
var thisSet = 1;
var cPlayer = 0;
var moveSpeed = 5;
var xPos = 50;
var yPos = 300;
function moveLand() {
thisSet = setTimeout(moveLand, 30);
if (xPos >= 500) {
moveBlock1 = moveBlock1 - 10;
document.getElementById("land00").style.left = moveBlock1 + "px";
document.getElementById("land01").style.left = moveBlock1 + "px";
}
cPlayer++;
if (cPlayer >= 4)
cPlayer = 0;
document.images[GAPlayer].src = gPlayer[cPlayer].src;
}
function moveP() {
var setThis = setTimeout(moveP, 10);
if (leftPos == false) {
xPos = xPos + moveSpeed;
}
if (rightPos == false) {
xPos = xPos - moveSpeed;
}
document.getElementById("player").style.left = xPos + "px";
document.getElementById("player").style.top = yPos + "px";
if (xPos >= 500) {
xPos = 500;
}
if (xPos <= 50) {
xPos = 50;
}
}

This is because you stop your player no matter what key is up. You should store what key down is last pressed, than on key up you need to check if last key is released.
It was hard to me to debug your code, so I made it in jQuery (and had same troubles as you had):
var game = {
settings: {
moveSpeed: 5, // 5 milliseconds, 200fps
moveBy: 2 // 2 pixels
},
land: null,
landWidth: null,
landLeft: null,
viewport: null,
viewportWidth: null,
landMinLeft: null,
init: function() {
game.land = $('.land');
game.landWidth = game.land.width();
game.landLeft = game.land.position().left;
game.viewport = $('.viewport');
game.viewportWidth = game.viewport.width();
game.landMinLeft = -(game.landWidth-game.viewportWidth);
},
movingInterval: null,
lastKey: null,
keyDown: function (e) {
switch (e.keyCode) {
case 39: // RIGHT
game.lastKey = e.keyCode;
clearInterval( game.movingInterval );
game.movingInterval = setInterval( function() {
game.move('right');
}, game.settings.moveSpeed);
break;
case 37: // LEFT
game.lastKey = e.keyCode;
clearInterval( game.movingInterval );
game.movingInterval = setInterval( function() {
game.move('left');
}, game.settings.moveSpeed);
break;
}
},
keyUp: function(e) {
if( e.keyCode==game.lastKey ) {
game.stopMoving();
};
},
move: function( direction ) {
switch( direction ) {
case 'left':
var newLeft = game.land.position().left+game.settings.moveBy;
if( newLeft>0 ) newLeft=0;
game.land.css({
'left': newLeft+'px'
});
break;
case 'right':
var newLeft = game.land.position().left-game.settings.moveBy;
if( newLeft<game.landMinLeft ) newLeft=game.landMinLeft;
game.land.css({
'left': newLeft+'px'
});
break;
};
},
stopMoving: function() {
clearInterval( game.movingInterval );
}
};
game.init();
$(window).on('keydown', game.keyDown);
$(window).on('keyup', game.keyUp);
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body, html, .viewport {
width: 100%;
height: 100%;
}
.viewport {
position: relative;
overflow: hidden;
}
.land {
position: absolute;
left: 0;
top: 0;
width: 2300px;
height: 200px;
background: url('//dummyimage.com/2300x400/000/fff&text=Mario+is+great!+Mario+is+our+hero!+We+love+you+mario!') no-repeat center center;
background-size: cover;
will-change: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="viewport">
<div class="land"></div>
</div>
Also on Playground.

This is how you do it in Javascript/HTML5
theGame.js
var getPlatF1POSX = 0;
var getPlatF1POSY = 0;
var addVar = 0;
var addVar2 = 0;
var addVar3 = 0;
var thisThis = 1;
var moveBlock1 = 350;
var stLandT = 0;
var moveRight = false;
var moveLeft = false;
var movePL = 0;
var movePR = 0;
//////////////////////////////////////////////////////////
//
// LOAD PLATFORMS/SET KEY UP AND DOWN/SET PLAYER POS
function loadGame() {
document.getElementsByTagName("DIV")[4].style.visibility = "visible";
addEventListener('mousemove', getData, false);
addEventListener('keydown', movePlayer, false);
addEventListener('keyup', stopPlayer, false);
moveP();
document.getElementById("player").style.left = xPos + "px";
document.getElementById("player").style.top = yPos + "px";
}
function getData(gData) {
}
//////////////////////////////////////////////////////////
//
// KEY DOWN TO MOVE PLAYER
function movePlayer(mPlayer) {
switch (mPlayer.keyCode) {
case 39: // RIGHT
if (stLandT == 0) {
setThis = setTimeout(landT, 500);
thisSet = setTimeout(moveLand, 30);
stLandT = 1;
}
movePL = 0;
movePR = 1;
break;
case 37: // LEFT
if (stLandT == 0) {
setThis = setTimeout(landT, 500);
thisSet = setTimeout(moveLand, 30);
stLandT = 1;
}
movePL = 1;
movePR = 0;
break;
case 38: // UP
break;
case 40: // DOWN
break;
}
}
//////////////////////////////////////////////////////////
//
// KEY UP TO STOP PLAYER/VOID STOP AND GO GLITCH
function stopPlayer(sPlayer) {
if (sPlayer.keyCode == 39) {
clearTimeout(setThis);
clearTimeout(thisSet);
stLandT = 0;
movePR = 0;
}
if (sPlayer.keyCode == 37) {
clearTimeout(setThis);
clearTimeout(thisSet);
stLandT = 0;
movePL = 0;
}
}
landThis.js/ MOVE PLAYER AND PLATFORMS
var cTAdd = 0;
var setThis = 1;
var GAPlayer = 3;
//////////////////////////////////////////////////////////
//
// SHOW PLATFORMS TO MOVE
function landT() {
setThis = setTimeout(landT, 500);
if (xPos >= 500) {
cTAdd = Math.floor(Math.random() * 100 + 1);
var block00 = document.createElement("img");
if (cTAdd > 0 && cTAdd < 25) {
block00.src = "images/sep2.png";
}
if (cTAdd > 25 && cTAdd < 50) {
block00.src = "images/sep1.png";
}
if (cTAdd > 50 && cTAdd < 100) {
block00.src = "images/platform00.png";
}
document.getElementById("land01").appendChild(block00);
var block01 = document.createElement("img");
var getB = block01.getBoundingClientRect();
if (cTAdd > 0 && cTAdd < 25) {
block01.src = "images/platform00.png";
}
if (cTAdd > 25 && cTAdd < 50) {
block01.src = "images/sep2.png";
}
if (cTAdd > 50 && cTAdd < 100) {
block01.src = "images/sep1.png";
}
document.getElementById("land00").appendChild(block01);
GAPlayer = GAPlayer + 2;
}
}
//////////////////////////////////////////////////////////
//
// MOVE PLATFORMS
var thisSet = 1;
var cPlayer = 0;
var moveSpeed = 5;
var xPos = 50;
var yPos = 300;
function moveLand() {
thisSet = setTimeout(moveLand, 30);
if (xPos >= 500) {
moveBlock1 = moveBlock1 - 10;
document.getElementById("land00").style.left = moveBlock1 + "px";
document.getElementById("land01").style.left = moveBlock1 + "px";
}
}
//////////////////////////////////////////////////////////
//
// MOVE PLAYER
var setP = 1;
function moveP() {
setP = setTimeout(moveP, 10);
if (movePR == 1) {
xPos = xPos + moveSpeed;
cPlayer++;
if (cPlayer >= 4)
cPlayer = 0;
document.images[GAPlayer].src = gPlayer[cPlayer].src;
}
if (movePL == 1) {
xPos = xPos - moveSpeed;
cPlayer++;
if (cPlayer >= 4)
cPlayer = 0;
document.images[GAPlayer].src = gPlayer[cPlayer].src;
}
document.getElementById("player").style.left = xPos + "px";
document.getElementById("player").style.top = yPos + "px";
if (xPos >= 500) {
xPos = 500;
}
if (xPos <= 50) {
xPos = 50;
}
}

Related

How to make my game full screen in the browser

I created a little game here that i am still working on (let me know what you think about it so far) and I am trying to make it full size in the browser and put the back button to the top left of the game screen. I have tried numerous times but am not getting anywhere ...Any ideas?
<html>
<head>
<style>
#hero {
/* background: #ff0000; */
background-image: url("man-of-space.png");
width: 40px;
height: 40px;
position: absolute;
}
#background {
background-image: url("space.png");
/* background: #000000; */
width: 500px;
height: 500px;
position: absolute;
left: 0px;
top: 0px;
}
.laser {
background: #00ff00;
width: 2px;
height: 50px;
position: absolute;
}
.enemy {
background-image: url("pic-that-works.png");
/* background: #0000ff; */
width: 40px;
height: 40px;
position: absolute;
}
#score {
color: #ffffff;
font-size: 18pt;
position: absolute;
left: 20px;
top: 20px;
}
#gameover {
color: #ff0000;
font-size: 20px;
position: absolute;
left: 160px;
top: 200px;
visibility: hidden;
}
</style>
</head>
<body>
<div id="background"></div>
<div id="hero"></div>
<div class="laser" id="laser0"></div>
<div class="laser" id="laser1"></div>
<div class="laser" id="laser2"></div>
<div id="score"></div>
<div id="gameover">GAME OVER</div>
<script>
var LEFT_KEY = 37;
var UP_KEY = 38;
var RIGHT_KEY = 39;
var DOWN_KEY = 40;
var SPACE_KEY = 32;
var HERO_MOVEMENT = 3;
var lastLoopRun = 0;
var score = 0;
var iterations = 0;
var controller = new Object();
var enemies = new Array();
function createSprite(element, x, y, w, h) {
var result = new Object();
result.element = element;
result.x = x;
result.y = y;
result.w = w;
result.h = h;
return result;
}
function toggleKey(keyCode, isPressed) {
if (keyCode == LEFT_KEY) {
controller.left = isPressed;
}
if (keyCode == RIGHT_KEY) {
controller.right = isPressed;
}
if (keyCode == UP_KEY) {
controller.up = isPressed;
}
if (keyCode == DOWN_KEY) {
controller.down = isPressed;
}
if (keyCode == SPACE_KEY) {
controller.space = isPressed;
}
}
function intersects(a, b) {
return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
}
function ensureBounds(sprite, ignoreY) {
if (sprite.x < 20) {
sprite.x = 20;
}
if (!ignoreY && sprite.y < 20) {
sprite.y = 20;
}
if (sprite.x + sprite.w > 480) {
sprite.x = 480 - sprite.w;
}
if (!ignoreY && sprite.y + sprite.h > 480) {
sprite.y = 480 - sprite.h;
}
}
function setPosition(sprite) {
var e = document.getElementById(sprite.element);
e.style.left = sprite.x + 'px';
e.style.top = sprite.y + 'px';
}
function handleControls() {
if (controller.up) {
hero.y -= HERO_MOVEMENT;
}
if (controller.down) {
hero.y += HERO_MOVEMENT;
}
if (controller.left) {
hero.x -= HERO_MOVEMENT;
}
if (controller.right) {
hero.x += HERO_MOVEMENT;
}
if (controller.space) {
var laser = getFireableLaser();
if (laser) {
laser.x = hero.x + 9;
laser.y = hero.y - laser.h;
}
}
ensureBounds(hero);
}
function getFireableLaser() {
var result = null;
for (var i = 0; i < lasers.length; i++) {
if (lasers[i].y <= -120) {
result = lasers[i];
}
}
return result;
}
function getIntersectingLaser(enemy) {
var result = null;
for (var i = 0; i < lasers.length; i++) {
if (intersects(lasers[i], enemy)) {
result = lasers[i];
break;
}
}
return result;
}
function checkCollisions() {
for (var i = 0; i < enemies.length; i++) {
var laser = getIntersectingLaser(enemies[i]);
if (laser) {
var element = document.getElementById(enemies[i].element);
element.style.visibility = 'hidden';
element.parentNode.removeChild(element);
enemies.splice(i, 1);
i--;
laser.y = -laser.h;
score += 100;
} else if (intersects(hero, enemies[i])) {
gameOver();
} else if (enemies[i].y + enemies[i].h >= 500) {
var element = document.getElementById(enemies[i].element);
element.style.visibility = 'hidden';
element.parentNode.removeChild(element);
enemies.splice(i, 1);
i--;
}
}
}
function gameOver() {
var element = document.getElementById(hero.element);
element.style.visibility = 'hidden';
element = document.getElementById('gameover');
element.style.visibility = 'visible';
}
function showSprites() {
setPosition(hero);
for (var i = 0; i < lasers.length; i++) {
setPosition(lasers[i]);
}
for (var i = 0; i < enemies.length; i++) {
setPosition(enemies[i]);
}
var scoreElement = document.getElementById('score');
scoreElement.innerHTML = 'SCORE: ' + score;
}
function updatePositions() {
for (var i = 0; i < enemies.length; i++) {
enemies[i].y += 4;
enemies[i].x += getRandom(7) - 3;
ensureBounds(enemies[i], true);
}
for (var i = 0; i < lasers.length; i++) {
lasers[i].y -= 12;
}
}
function addEnemy() {
var interval = 50;
if (iterations > 1500) {
interval = 5;
} else if (iterations > 1000) {
interval = 20;
} else if (iterations > 500) {
interval = 35;
}
if (getRandom(interval) == 0) {
var elementName = 'enemy' + getRandom(10000000);
var enemy = createSprite(elementName, getRandom(450), -40, 35, 35);
var element = document.createElement('div');
element.id = enemy.element;
element.className = 'enemy';
document.children[0].appendChild(element);
enemies[enemies.length] = enemy;
}
}
function getRandom(maxSize) {
return parseInt(Math.random() * maxSize);
}
function loop() {
if (new Date().getTime() - lastLoopRun > 40) {
updatePositions();
handleControls();
checkCollisions();
addEnemy();
showSprites();
lastLoopRun = new Date().getTime();
iterations++;
}
setTimeout('loop();', 2);
}
document.onkeydown = function(evt) {
toggleKey(evt.keyCode, true);
};
document.onkeyup = function(evt) {
toggleKey(evt.keyCode, false);
};
var hero = createSprite('hero', 250, 460, 20, 20);
var lasers = new Array();
for (var i = 0; i < 3; i++) {
lasers[i] = createSprite('laser' + i, 0, -120, 2, 50);
}
loop();
</script>
</body>
</html>

Laser does not shoot after I added a player

I've been trying to make a game where a character shoots a laser, but for some reason when you press Q, which is the firing key, the laser doesn't shoot, which is weird because I have tried this code before and it worked, the only thing I changed is I have added another player to the game, and it doesn't give me any error messages
'''
#hero {
background: #ff0000;
width: 20px;
height: 50px;
position: absolute;
}
#player {
background: #ff0000;
width: 20px;
height: 50px;
position: absolute;
}
#Pic {
width: 150px;
}
#laser {
width: 30;
height: 3;
background: #ff0000 position:absolute;
}
#plaser {
width: 30;
height: 3;
background: #ff0000 position:absolute;
}
</style>
<div id="player"></div>
<div id="hero"></div>
<div id="laser"></div>
<div id="plaser"></div>
<script type="text/javascript">
var LEFT_KEY = 65;
var UP_KEY = 87;
var RIGHT_KEY = 68;
var DOWN_KEY = 83;
var LEFT_ARROW = 37;
var RIGHT_ARROW = 39;
var SPACE_KEY = 32;
var DOWN_ARROW = 40;
var UP_ARROW = 38;
var Q_KEY = 81;
var E_KEY = 69;
var HERO_MOVEMENT = 10;
var ONE_KEY = 97;
var TWO_KEY = 98;
var lastLoopRun = 0;
var controller = new Object();
var player = new Object();
player.element = 'player'
player.x = 1450;
player.y = 460;
var hero = new Object();
hero.element = 'hero';
hero.x = 250;
hero.y = 460;
var laser = new Object();
laser.element = 'laser'
laser.x = 0;
laser.y = -120;
laser.w = 30;
laser.h = 3;
var plaser = new Object();
plaser.element = 'plaser'
plaser.x = 0;
plaser.y = -130;
plaser.w = 30;
plaser.h = 3;
function ensureBounds(sprite, ignoreY) {
if (sprite.x < 20) {
sprite.x = 20;
}
if (!ignoreY && sprite.y < 20) {
sprite.y = 20;
}
if (sprite.x + sprite.w > 1910) {
sprite.x = 1910 - sprite.w;
}
if (!ignoreY && sprite.y + sprite.h > 940) {
sprite.y = 940 - sprite.h;
}
}
function createSprite(element, x, y, w, h) {
var result = new Object();
result.element = element;
result.x = x;
result.y = y;
result.w = w;
result.h = h;
return result;
}
function toggleKey(keyCode, isPressed) {
if (keyCode == DOWN_KEY) {
controller.down = isPressed;
}
if (keyCode == LEFT_KEY) {
controller.left = isPressed;
}
if (keyCode == RIGHT_KEY) {
controller.right = isPressed;
}
if (keyCode == UP_KEY) {
controller.up = isPressed;
}
if (keyCode == SPACE_KEY) {
controller.space = isPressed;
}
if (keyCode == LEFT_ARROW) {
controller.leftarrow = isPressed;
}
if (keyCode == RIGHT_ARROW) {
controller.rightarrow = isPressed;
}
if (keyCode == UP_ARROW) {
controller.uparrow = isPressed
}
if (keyCode == DOWN_ARROW) {
controller.downarrow = isPressed
}
if (keyCode == Q_KEY) {
controller.qkey = isPressed
}
if (keyCode == E_KEY) {
controller.ekey = isPressed
}
if (keyCode == ONE_KEY) {
controller.onekey = isPressed
}
if (keyCode == TWO_KEY) {
controller.twokey = isPressed
}
}
function handleControls() {
if (controller.down) {
hero.y += HERO_MOVEMENT
}
if (controller.up) {
hero.y -= HERO_MOVEMENT
}
if (controller.left) {
hero.x -= HERO_MOVEMENT;
}
if (controller.right) {
hero.x += HERO_MOVEMENT;
}
if (controller.qkey && laser.x <= -120) {
laser.x = hero.x - 20;
laser.y = hero.y + 15;
}
if (controller.space && laser.x <= -120) {
laser.x = hero.x + 20;
laser.y = hero.y + 10;
}
if (controller.onekey && plaser.x <= -120) {
plaser.x = player.x - 20;
plaser.y = player.y + 15;
}
if (controller.twokey) {
}
if (controller.uparrow) {
player.y -= HERO_MOVEMENT
}
if (controller.downarrow) {
player.y += HERO_MOVEMENT
}
if (controller.leftarrow) {
player.x -= HERO_MOVEMENT;
}
if (controller.rightarrow) {
player.x += HERO_MOVEMENT;
}
ensureBounds(hero);
ensureBounds(player)
}
function showSprites() {
setPosition(hero);
setPosition(laser);
setPosition(player)
setPosition(plaser)
}
function updatePositions() {
laser.x -= 90
plaser.x -= 90
}
function loop() {
if (new Date().getTime() - lastLoopRun > 40) {
updatePositions();
handleControls();
showSprites();
lastLoopRun = new Date().getTime();
}
setTimeout('loop();', 2);
}
document.onkeydown = function(evt) {
toggleKey(evt.keyCode, true);
};
document.onkeyup = function(evt) {
toggleKey(evt.keyCode, false);
};
loop();
function setPosition(sprite) {
var e = document.getElementById(sprite.element)
e.style.left = sprite.x + 'px';
e.style.top = sprite.y + 'px';
}
createSprite('laser', 0, -120, 2, 50)
createSprite('plaser', 0, -120, 2, 50)
</script>
</body>
</html>
'''

How do I make lava drops damage the character?

I am building a JavaScript game, based on Mario.
I have already implemented "physics" for lava, so when the character would fall into it, they would lose 1 life. What I am trying to achieve is that lava drops would act the same, so on contact they would hurt the character and make it respawn at the start of the area / level.
The code can be found here and seen below:
//////////////////////////////
// This is only a demo code //
//////////////////////////////
var LEVELS = [
[" ",
" ",
" ",
" ",
" xxx ",
" xx!xx ",
" x!!!x ",
" xx!xx ",
" x xvx ",
" x x",
" x x",
" x x",
" x x",
" x x",
" x # xxxxx o x",
" xxxxxx xxxxxxxxx xxxxxxxxxx",
" x x ",
" x!!!!!x ",
" x!!!!!x ",
" xxxxxxx ",
" "]
];
var life = 3;
document.getElementById("life").innerHTML = ("Lives left: " + life);
function Vector(x, y) {
this.x = x; this.y = y;
}
Vector.prototype.plus = function(other) {
return new Vector(this.x + other.x, this.y + other.y);
};
Vector.prototype.times = function(scale) {
return new Vector(this.x * scale, this.y * scale);
};
// Note: uppercase words are used that means constructor are values
var actorchars = {
"#": Player,
"o": Coin,
"|": Lava,
"v": Lava
};
function Player(pos) {
this.pos = pos.plus(new Vector(0, -.5));
this.size = new Vector(.5, 1);
this.speed = new Vector(0, 0);
}
Player.prototype.type = "player";
function Lava(pos, ch) {
this.pos = pos;
this.size = new Vector(1, 1);
if (ch === "|")
this.speed = new Vector(0, 2);
else if (ch === 'v'){
this.speed = new Vector(0, 3);
this.repeatPos = pos;
}
}
Lava.prototype.type = "Lava";
function Coin(pos) {
this.basePos = this.pos = pos;
this.size = new Vector(.6, .6);
// take a look back
this.wobble = Math.random() * Math.PI * 2;
}
Coin.prototype.type = "coin";
Level.prototype.isFinished = function() {
return this.status !== null && this.finishDelay < 0;
};
function Level(plan) {
this.width = plan[0].length;
this.height = plan.length;
this.grid = [];
this.actors = [];
for (var y = 0; y < this.height; y++) {
var line = plan[y], gridLine = [];
for (var x = 0; x < this.width; x++) {
var ch = line[x], fieldType = null;
var Actor = actorchars[ch];
if (Actor)
this.actors.push(new Actor(new Vector(x, y), ch));
else if (ch === "x")
fieldType = "wall";
else if (ch === "!")
fieldType = "lava";
else if (ch === "|")
fieldType = "lava";
else if (ch === "v"){
fieldType = "lava";
console.log(fieldType);
}
gridLine.push(fieldType);
}
this.grid.push(gridLine);
}
this.player = this.actors.filter(function(actor) {
return actor.type === "player";
})[0];
this.status = this.finishDelay = null;
}
function element(name, className) {
var elem = document.createElement(name);
if(className) elem.className = className;
return elem;
}
function DOMDisplay(parent, level) {
this.wrap = parent.appendChild(element("div", "game"));
this.level = level;
this.wrap.appendChild(this.drawBackground());
this.actorLayer = null;
this.drawFrame();
}
var scale = 15;
DOMDisplay.prototype.drawBackground = function() {
var table = element("table", "background");
table.style.width = this.level.width * scale + "px";
table.style.height = this.level.height * scale + "px";
this.level.grid.forEach(function(row) {
var rowElement = table.appendChild(element("tr"));
rowElement.style.height = scale + "px";
row.forEach(function(type) {
rowElement.appendChild(element("td", type));
});
});
return table;
};
DOMDisplay.prototype.drawActors = function() {
var wrap = element("div");
this.level.actors.forEach(function(actor) {
var rect = wrap.appendChild(element("div", "actor " + actor.type));
rect.style.width = actor.size.x * scale + "px";
rect.style.height = actor.size.y * scale + "px";
rect.style.left = actor.pos.x * scale + "px";
rect.style.top = actor.pos.y * scale + "px";
});
return wrap;
};
DOMDisplay.prototype.drawFrame = function() {
if (this.actorLayer)
this.wrap.removeChild(this.actorLayer);
this.actorLayer = this.wrap.appendChild(this.drawActors());
this.wrap.className = "game " + (this.level.status || "");
this.scrollPlayerIntoView();
};
// clear it later
DOMDisplay.prototype.scrollPlayerIntoView = function() {
var width = this.wrap.clientWidth;
var height = this.wrap.clientHeight;
var margin = width / 3;
// The viewport
var left = this.wrap.scrollLeft, right = left + width;
var top = this.wrap.scrollTop, bottom = top + height;
var player = this.level.player;
var center = player.pos.plus(player.size.times(0.5))
.times(scale);
if (center.x < left + margin)
this.wrap.scrollLeft = center.x - margin;
else if (center.x > right - margin)
this.wrap.scrollLeft = center.x + margin - width;
if (center.y < top + margin)
this.wrap.scrollTop = center.y - margin;
else if (center.y > bottom - margin)
this.wrap.scrollTop = center.y + margin - height;
};
DOMDisplay.prototype.clear = function() {
this.wrap.parentNode.removeChild(this.wrap);
};
Level.prototype.obstacleAt = function(pos, size) {
var xStart = Math.floor(pos.x);
var xEnd = Math.ceil(pos.x + size.x);
var yStart = Math.floor(pos.y);
var yEnd = Math.ceil(pos.y + size.y);
if (xStart < 0 || xEnd > this.width || yStart < 0)
return "wall";
if (yEnd > this.height)
return "lava";
for (var y = yStart; y < yEnd; y++) {
for (var x = xStart; x < xEnd; x++) {
var fieldType = this.grid[y][x];
if (fieldType) return fieldType;
}
}
};
Level.prototype.actorAt = function(actor) {
for (var i = 0; i < this.actors.length; i++) {
var other = this.actors[i];
if (other != actor &&
actor.pos.x + actor.size.x > other.pos.x &&
actor.pos.x < other.pos.x + other.size.x &&
actor.pos.y + actor.size.y > other.pos.y &&
actor.pos.y < other.pos.y + other.size.y)
return other;
}
};
var maxStep = 0.05;
Level.prototype.animate = function(step, keys) {
if (this.status !== null)
this.finishDelay -= step;
while (step > 0) {
var thisStep = Math.min(step, maxStep);
this.actors.forEach(function(actor) {
actor.act(thisStep, this, keys);
}, this);
step -= thisStep;
}
};
Lava.prototype.act = function(step, level) {
var newPos = this.pos.plus(this.speed.times(step));
if (!level.obstacleAt(newPos, this.size))
this.pos = newPos;
else if (this.repeatPos)
this.pos = this.repeatPos;
else
this.speed = this.speed.times(-1);
};
var wobbleSpeed = 8, wobbleDist = 0.07;
Coin.prototype.act = function(step) {
this.wobble += step * wobbleSpeed;
var wobblePos = Math.sin(this.wobble) * wobbleDist;
this.pos = this.basePos.plus(new Vector(0, wobblePos));
};
var playerXSpeed = 10;
Player.prototype.moveX = function(step, level, keys) {
this.speed.x = 0;
if (keys.left) this.speed.x -= playerXSpeed;
if (keys.right) this.speed.x += playerXSpeed;
var motion = new Vector(this.speed.x * step, 0);
var newPos = this.pos.plus(motion);
var obstacle = level.obstacleAt(newPos, this.size);
if (obstacle)
level.playerTouched(obstacle);
else
this.pos = newPos;
};
var gravity = 30;
var jumpSpeed = 17;
Player.prototype.moveY = function(step, level, keys) {
this.speed.y += step * gravity;
var motion = new Vector(0, this.speed.y * step);
var newPos = this.pos.plus(motion);
var obstacle = level.obstacleAt(newPos, this.size);
if (obstacle) {
level.playerTouched(obstacle);
if (keys.up && this.speed.y > 0)
this.speed.y = -jumpSpeed;
else
this.speed.y = 0;
} else {
this.pos = newPos;
}
};
Player.prototype.act = function(step, level, keys) {
this.moveX(step, level, keys);
this.moveY(step, level, keys);
var otherActor = level.actorAt(this);
if (otherActor)
level.playerTouched(otherActor.type, otherActor);
// Losing animation
if (level.status == "lost") {
this.pos.y += step;
this.size.y -= step;
}
};
Level.prototype.playerTouched = function(type, actor) {
if (type == "lava" && this.status === null) {
this.status = "lost";
life -= 1;
console.log(life);
document.getElementById("life").innerHTML = ("Lives left: " + life);
if(life < 0) {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
this.finishDelay = 1;
} else if (type == "coin") {
this.actors = this.actors.filter(function(other) {
return other != actor;
});
if (!this.actors.some(function(actor) {
return actor.type == "coin";
})) {
life += 1;
document.getElementById("life").innerHTML = ("Lives left: " + life);
this.status = "won";
this.finishDelay = 1;
}
}
};
var arrowCodes = {37: "left", 38: "up", 39: "right"};
function trackKeys(codes) {
var pressed = Object.create(null);
function handler(event) {
if (codes.hasOwnProperty(event.keyCode)) {
var down = event.type == "keydown";
pressed[codes[event.keyCode]] = down;
event.preventDefault();
}
}
addEventListener("keydown", handler);
addEventListener("keyup", handler);
return pressed;
}
function runAnimation(frameFunc) {
var lastTime = null;
function frame(time) {
var stop = false;
if (lastTime !== null) {
var timeStep = Math.min(time - lastTime, 100) / 1000;
stop = frameFunc(timeStep) === false;
}
lastTime = time;
if (!stop)
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
var arrows = trackKeys(arrowCodes);
function runLevel(level, Display, andThen) {
var display = new Display(document.body, level);
runAnimation(function(step) {
level.animate(step, arrows);
display.drawFrame(step);
if (level.isFinished()) {
display.clear();
if (andThen)
andThen(level.status);
return false;
}
});
}
var lives = function() {
ctx.font = "20px Courier";
ctx.fontFamily = "monospace";
ctx.fillStyle = "#666";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Lives left: " + life, 10, 10);
};
function runGame(plans, Display) {
function startLevel(n) {
runLevel(new Level(plans[n]), Display, function(status) {
if (status == "lost") {
startLevel(n);
} else if (n < plans.length - 1)
startLevel(n + 1);
else
alert("You win!");
});
}
startLevel(0);
}
runGame(LEVELS, DOMDisplay);
body {
background: #222;
}
h2 {
color: #666;
font-family: monospace;
text-align: center;
}
.background {
table-layout: fixed;
border-spacing: 0;
}
.background td {
padding: 0;
}
.lava, .actor {
background: #e55;
}
.wall {
background: #444;
border: solid 3px #333;
box-sizing: content-box;
}
.actor {
position: absolute;
}
.coin {
background: #e2e838;
border-radius: 50%;
}
.player {
background: #335699;
box-shadow: none;
}
.lost .player {
background: #a04040;
}
.won .player {
background: green;
}
.game {
position: relative;
overflow: hidden;
}
#life {
font = 20px;
font-family: monospace;
color: #666;
text-align: left;
baseline: top;
margin-left: 30px;
font-weight: bold;
}
<h2>Simple JavaScript Game</h2>
<div id="life"></div>
So just a quick explanation, the following elements act as:
"x" represents a wall
"#" acts as a character
"!", "v" act as lava
"o" is a coin, which finishes the level by being collected
Current code:
Level.prototype.playerTouched = function(type, actor) {
if (type == "lava" && this.status === null) {
The problem is that you use different types for the "lava pool" and "lava drops".
The last one type is 'Lava' and not 'lava' as the first. So if you want to keep it that way is as simple as that:
Level.prototype.playerTouched = function(type, actor) {
if ((type == "lava" || type == "Lava") && this.status === null) {
With regards,
Chris Karanikas.

Points are being incorrectly counted

I have another question about game creation, that I already reached out for.
As I continued developing the game and tried to implement point counter I have encountered another issue.
It seems that sometimes the points are being counter instead of +1 to +2 or even +3.
I am suspecting incorrect placement of the code-part expo += 1 as it would (probably) get looped 2 (or multiple) times instead of once, but frankly, I am not sure.
The code can be found here or below:
var LEVELS = [
[" x x",
" xx x",
" xxx x x",
" xx!xx x ox",
" x!!!x x xx",
" xx!xx x x",
" x xvx x x",
" x xx x",
" x x x",
" x x x",
" x x xx",
" x x",
" x # xxxxx o x",
" xxxxxx xxxxxxxxx xxxxxxxxxxxxx",
" x x ",
" x!!!!!x ",
" x!!!!!x ",
" xxxxxxx ",
" "],
];
var life = 3;
var expo = 0;
document.getElementById("life").innerHTML = ("Lives left: " + life);
document.getElementById("expo").innerHTML = ("Points: " + expo);
function Vector(x, y) {
this.x = x; this.y = y;
}
Vector.prototype.plus = function(other) {
return new Vector(this.x + other.x, this.y + other.y);
};
Vector.prototype.times = function(scale) {
return new Vector(this.x * scale, this.y * scale);
};
// Note: uppercase words are used that means constructor are values
var actorchars = {
"#": Player,
"o": Coin,
"=": Lava,
"|": Lava,
"v": Lava,
"#": Lava
};
function Player(pos) {
this.pos = pos.plus(new Vector(0, -.5));
this.size = new Vector(.5, 1);
this.speed = new Vector(0, 0);
}
Player.prototype.type = "player";
function Lava(pos, ch) {
this.pos = pos;
this.size = new Vector(1, 1);
if (ch === "=")
this.speed = new Vector(2, 0);
else if (ch === '|')
this.speed = new Vector(0, 2);
else if (ch === 'v'){
this.speed = new Vector(0, 5); // new Vector(0, 3);
this.repeatPos = pos;
} else if (ch === '#'){
this.speed = new Vector(0, 10);
}
}
Lava.prototype.type = "lava"
//Lava.prototype.type = "Lava";
function Coin(pos) {
this.basePos = this.pos = pos;
this.size = new Vector(.6, .6);
// take a look back
this.wobble = Math.random() * Math.PI * 2;
}
Coin.prototype.type = "coin";
Level.prototype.isFinished = function() {
return this.status !== null && this.finishDelay < 0;
};
function Level(plan) {
this.width = plan[0].length;
this.height = plan.length;
this.grid = [];
this.actors = [];
for (var y = 0; y < this.height; y++) {
var line = plan[y], gridLine = [];
for (var x = 0; x < this.width; x++) {
var ch = line[x], fieldType = null;
var Actor = actorchars[ch];
if (Actor)
this.actors.push(new Actor(new Vector(x, y), ch));
else if (ch === "x")
fieldType = "wall";
else if (ch === "!")
fieldType = "lava";
else if (ch === "|")
fieldType = "lava";
else if (ch === "=")
fieldType = "lava";
else if (ch === "#")
fieldType = "lava";
else if (ch === "v"){
fieldType = "lava";
console.log(fieldType);
}
gridLine.push(fieldType);
}
this.grid.push(gridLine);
}
this.player = this.actors.filter(function(actor) {
return actor.type === "player";
})[0];
this.status = this.finishDelay = null;
}
function element(name, className) {
var elem = document.createElement(name);
if(className) elem.className = className;
return elem;
}
function DOMDisplay(parent, level) {
this.wrap = parent.appendChild(element("div", "game"));
this.level = level;
this.wrap.appendChild(this.drawBackground());
this.actorLayer = null;
this.drawFrame();
}
var scale = 15;
DOMDisplay.prototype.drawBackground = function() {
var table = element("table", "background");
table.style.width = this.level.width * scale + "px";
table.style.height = this.level.height * scale + "px";
this.level.grid.forEach(function(row) {
var rowElement = table.appendChild(element("tr"));
rowElement.style.height = scale + "px";
row.forEach(function(type) {
rowElement.appendChild(element("td", type));
});
});
return table;
};
DOMDisplay.prototype.drawActors = function() {
var wrap = element("div");
this.level.actors.forEach(function(actor) {
var rect = wrap.appendChild(element("div", "actor " + actor.type));
rect.style.width = actor.size.x * scale + "px";
rect.style.height = actor.size.y * scale + "px";
rect.style.left = actor.pos.x * scale + "px";
rect.style.top = actor.pos.y * scale + "px";
});
return wrap;
};
DOMDisplay.prototype.drawFrame = function() {
if (this.actorLayer)
this.wrap.removeChild(this.actorLayer);
this.actorLayer = this.wrap.appendChild(this.drawActors());
this.wrap.className = "game " + (this.level.status || "");
this.scrollPlayerIntoView();
};
// clear it later
DOMDisplay.prototype.scrollPlayerIntoView = function() {
var width = this.wrap.clientWidth;
var height = this.wrap.clientHeight;
var margin = width / 3;
// The viewport
var left = this.wrap.scrollLeft, right = left + width;
var top = this.wrap.scrollTop, bottom = top + height;
var player = this.level.player;
var center = player.pos.plus(player.size.times(0.5))
.times(scale);
if (center.x < left + margin)
this.wrap.scrollLeft = center.x - margin;
else if (center.x > right - margin)
this.wrap.scrollLeft = center.x + margin - width;
if (center.y < top + margin)
this.wrap.scrollTop = center.y - margin;
else if (center.y > bottom - margin)
this.wrap.scrollTop = center.y + margin - height;
};
DOMDisplay.prototype.clear = function() {
this.wrap.parentNode.removeChild(this.wrap);
};
Level.prototype.obstacleAt = function(pos, size) {
var xStart = Math.floor(pos.x);
var xEnd = Math.ceil(pos.x + size.x);
var yStart = Math.floor(pos.y);
var yEnd = Math.ceil(pos.y + size.y);
if (xStart < 0 || xEnd > this.width || yStart < 0)
return "wall";
if (yEnd > this.height)
return "lava";
for (var y = yStart; y < yEnd; y++) {
for (var x = xStart; x < xEnd; x++) {
var fieldType = this.grid[y][x];
if (fieldType) return fieldType;
}
}
};
Level.prototype.actorAt = function(actor) {
for (var i = 0; i < this.actors.length; i++) {
var other = this.actors[i];
if (other != actor &&
actor.pos.x + actor.size.x > other.pos.x &&
actor.pos.x < other.pos.x + other.size.x &&
actor.pos.y + actor.size.y > other.pos.y &&
actor.pos.y < other.pos.y + other.size.y)
return other;
}
};
var maxStep = 0.05;
Level.prototype.animate = function(step, keys) {
if (this.status !== null)
this.finishDelay -= step;
while (step > 0) {
var thisStep = Math.min(step, maxStep);
this.actors.forEach(function(actor) {
actor.act(thisStep, this, keys);
}, this);
step -= thisStep;
}
};
Lava.prototype.act = function(step, level) {
var newPos = this.pos.plus(this.speed.times(step));
if (!level.obstacleAt(newPos, this.size))
this.pos = newPos;
else if (this.repeatPos)
this.pos = this.repeatPos;
else
this.speed = this.speed.times(-1);
};
var wobbleSpeed = 8, wobbleDist = 0.07;
Coin.prototype.act = function(step) {
this.wobble += step * wobbleSpeed;
var wobblePos = Math.sin(this.wobble) * wobbleDist;
this.pos = this.basePos.plus(new Vector(0, wobblePos));
};
var playerXSpeed = 10;
Player.prototype.moveX = function(step, level, keys) {
this.speed.x = 0;
if (keys.left) this.speed.x -= playerXSpeed;
if (keys.right) this.speed.x += playerXSpeed;
var motion = new Vector(this.speed.x * step, 0);
var newPos = this.pos.plus(motion);
var obstacle = level.obstacleAt(newPos, this.size);
if (obstacle)
level.playerTouched(obstacle);
else
this.pos = newPos;
};
var gravity = 30;
var jumpSpeed = 17;
Player.prototype.moveY = function(step, level, keys) {
this.speed.y += step * gravity;
var motion = new Vector(0, this.speed.y * step);
var newPos = this.pos.plus(motion);
var obstacle = level.obstacleAt(newPos, this.size);
if (obstacle) {
level.playerTouched(obstacle);
if (keys.up && this.speed.y > 0)
this.speed.y = -jumpSpeed;
else
this.speed.y = 0;
} else {
this.pos = newPos;
}
};
Player.prototype.act = function(step, level, keys) {
this.moveX(step, level, keys);
this.moveY(step, level, keys);
var otherActor = level.actorAt(this);
if (otherActor)
level.playerTouched(otherActor.type, otherActor);
// Losing animation
if (level.status == "lost") {
this.pos.y += step;
this.size.y -= step;
}
};
Level.prototype.playerTouched = function(type, actor) {
//if (type == "lava" || type == "Lava" && this.status === null) { //DOESN'T SEEM TO WORK, FIND OUT WHY MASS DAMAGE
if (type == "lava" && this.status === null) {
this.status = "lost";
life -= 1;
console.log(life);
expo = 0;
document.getElementById("expo").innerHTML = ("Points: " + expo);
document.getElementById("life").innerHTML = ("Lives left: " + life);
if(life < 0) {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
this.finishDelay = 1;
} else if (type == "coin") {
this.actors = this.actors.filter(function(other) {
return other != actor;
});
if (!this.actors.some(function(actor) {
console.log("coin picked up")
expo += 1;
document.getElementById("expo").innerHTML = ("Points: " + expo);
return actor.type == "coin";
})) {
life += 1;
document.getElementById("life").innerHTML = ("Lives left: " + life);
this.status = "won";
this.finishDelay = 1;
}
}
};
var arrowCodes = {37: "left", 38: "up", 39: "right"};
function trackKeys(codes) {
var pressed = Object.create(null);
function handler(event) {
if (codes.hasOwnProperty(event.keyCode)) {
var down = event.type == "keydown";
pressed[codes[event.keyCode]] = down;
event.preventDefault();
}
}
addEventListener("keydown", handler);
addEventListener("keyup", handler);
return pressed;
}
function runAnimation(frameFunc) {
var lastTime = null;
function frame(time) {
var stop = false;
if (lastTime !== null) {
var timeStep = Math.min(time - lastTime, 100) / 1000;
stop = frameFunc(timeStep) === false;
}
lastTime = time;
if (!stop)
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
var arrows = trackKeys(arrowCodes);
function runLevel(level, Display, andThen) {
var display = new Display(document.body, level);
runAnimation(function(step) {
level.animate(step, arrows);
display.drawFrame(step);
if (level.isFinished()) {
display.clear();
if (andThen)
andThen(level.status);
return false;
}
});
}
var lives = function() {
ctx.font = "20px Courier";
ctx.fontFamily = "monospace";
ctx.fillStyle = "#666";
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillText("Lives left: " + life, 10, 10);
};
function runGame(plans, Display) {
function startLevel(n) {
runLevel(new Level(plans[n]), Display, function(status) {
if (status == "lost") {
startLevel(n);
} else if (n < plans.length - 1)
startLevel(n + 1);
else
alert("You win!");
});
}
startLevel(0);
}
function restart() {
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
runGame(LEVELS, DOMDisplay);
body {
background: #222;
}
h2 {
color: #666;
font-family: monospace;
text-align: center;
}
.background {
table-layout: fixed;
border-spacing: 0;
}
.background td {
padding: 0;
}
.lava, .actor {
background: #e55;
}
.wall {
background: #444;
border: solid 3px #333;
box-sizing: content-box;
}
.actor {
position: absolute;
}
.coin {
background: #e2e838;
border-radius: 50%;
}
.player {
background: #335699;
box-shadow: none;
}
.lost .player {
background: #a04040;
}
.won .player {
background: green;
}
.game {
position: relative;
overflow: hidden;
}
#life, #expo {
font = 20px;
font-family: monospace;
color: #666;
text-align: left;
baseline: top;
margin-left: 30px;
font-weight: bold;
}
input {
margin-left: 30px;
float: right;
position: relative;
top: -30px;
}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>game</title>
</head>
<body>
<h2>Simple JavaScript Game</h2>
<div id="life"></div>
<div id="expo"></div>
<div>
<input type="button" onclick="restart()" value="Restart"/>
</div>
</body>
</html>
I have already tried some options and quite interesting, was that if I removed all "lava sources" as variants or/and all collisions of those, the counter would work as it should.
Another level, that might get some ideas about my findings, found here.
I will really appreciate any help, Thanks
EDIT::
I would like to mess with the existing code as minimal as possible, if not, I will have to scrap the code and redo most of it (at least that's the only option I saw).
OK, so it seems that what fixed my issue was incorrect placement of the following sentences:
expo += 1;
document.getElementById("expo").innerHTML = ("Points: " + expo);
The placement of code before:
else if (type == "coin") {
this.actors = this.actors.filter(function(other) {
return other != actor;
});
if (!this.actors.some(function(actor) {
console.log("coin picked up")
expo += 1;
document.getElementById("expo").innerHTML = ("Points: " + expo);
return actor.type == "coin";
})) {
life += 1;
document.getElementById("life").innerHTML = ("Lives left: " + life);
this.status = "won";
this.finishDelay = 1;
}
The correct placement of the code:
else if (type == "coin") {
expo += 1;
document.getElementById("expo").innerHTML = ("Points: " + expo);
this.actors = this.actors.filter(function(other) {
return other != actor;
});
if (!this.actors.some(function(actor) {
console.log("coin picked up")
return actor.type == "coin";
})) {
life += 1;
document.getElementById("life").innerHTML = ("Lives left: " + life);
this.status = "won";
this.finishDelay = 1;
}

snake game collision with itself

I have made a snake game with processign.js and im trying to make the collision with itself. The problem is that it isnt working as it should.
var screen = 0;
var bg = color(60,150,60);
var snake;
var apple;
var bonus;
var nBonus = 0;
var gameOver = false;
var appleSize = 10;
var applePosX = round(random(10,width-appleSize)/10)*10;
var applePosY = round(random(10,height-appleSize)/10)*10;
var keys = [];
void keyPressed() {
keys[keyCode] = true;
};
void keyReleased() {
keys[keyCode] = false;
};
frameRate(10);
// collision with itself
// -----------------------------------------------------------------------
// ------------------------------- THE SNAKE -----------------------------
var Snake = function(x, y) {
this.x = x;
this.y = y;
this.len = 1;
this.size = 10;
this.snakePosX = 0;
this.snakePosY = 0;
this.points = 0;
this.positions = [];
this.moving = false;
this.apples = 0;
for(var i=0; i<this.len; i++) {
var posX = this.x-i*10;
var posY = this.y;
this.positions[i] = {x:posX, y:posY};
}
};
Snake.prototype.draw = function() {
fill(0);
stroke(255,255,255);
for(var i=0; i<this.positions.length; i++) {
rect(this.positions[i].x, this.positions[i].y, this.size, this.size);
}
};
Snake.prototype.move = function() {
if(gameOver === false) {
if(keys[UP]) {
this.snakePosY = -this.size;
this.snakePosX = 0;
this.moving = true;
}
if(keys[DOWN]) {
this.snakePosY = this.size;
this.snakePosX = 0;
this.moving = true;
}
if(keys[LEFT]) {
this.snakePosX = -this.size;
this.snakePosY = 0;
this.moving = true;
}
if(keys[RIGHT]) {
this.snakePosX = this.size;
this.snakePosY = 0;
this.moving = true;
}
}
if(this.moving == true) {
if(snake.positions.length == 1) {
this.positions[0].x += this.snakePosX;
this.positions[0].y += this.snakePosY;
}
else {
for(var i=1; i<this.positions.length; i++) {
this.positions[i-1].x = this.positions[i].x;
this.positions[i-1].y = this.positions[i].y;
this.positions[i].x += this.snakePosX;
this.positions[i].y += this.snakePosY;
}
}
}
};
Snake.prototype.checkColl = function() {
// collision with itself
if(this.positions.length>1) {
for(var i=0; i<this.positions.length; i++) {
if(this.positions[0].x > 350) {
text('holly crap', 100, 100);
}
}
}
// collision with walls
if(this.positions[0].x > width-this.size || this.positions[0].x < 0 || this.positions[0].y > height-this.size || this.positions[0].y < 0) {
gameOver = true;
gameIsOver();
}
// collision with apples
for(var i=0; i<this.positions.length; i++) {
if(this.positions[i].x >= apple.x && this.positions[i].x+10 <= apple.x+10 && this.positions[i].y >= apple.y && this.positions[i].y+10 <= apple.y+10) {
apple.draw();
this.apples ++;
this.points += 10;
this.positions.unshift({x:apple.x, y:apple.y});
apple.x = round(random(10,width-appleSize)/10)*10;
apple.y = round(random(10,height-appleSize)/10)*10;
if(this.apples > 1 && this.apples % 5 == 0) {
nBonus = 1;
}
}
}
// collision with bonus
if(this.positions[0].x >= bonus.x && this.positions[0].x+10 <= bonus.x+10 && this.positions[0].y >= bonus.y && this.positions[0].y+10 <= bonus.y+10) {
if(this.moving) {
bonus.x = round(random(10,width-appleSize)/10)*10;
bonus.y = round(random(10,height-appleSize)/10)*10;
nBonus = 0;
this.points += 10;
}
}
};
// ------------------------ THE APPLES -----------------------------------
var Apple = function(x, y) {
this.x = x;
this.y = y;
};
Apple.prototype.draw = function() {
fill(255,0,0);
noStroke();
rect(this.x, this.y, appleSize, appleSize);
};
// ------------------------ THE BONUS -----------------------------------
var Bonus = function(x, y) {
this.x = x;
this.y = y;
}
Bonus.prototype.draw = function() {
fill(150,0,0);
stroke(255,255,255)
rect(this.x, this.y, appleSize, appleSize);
};
// -----------------------------------------------------------------------
snake = new Snake(width/2, height/2);
apple = new Apple(applePosX, applePosY);
bonus = new Bonus(width/2, height/2);
// -----------------------------------------------------------------------
void gameIsOver() {
fill(0);
textAlign(CENTER);
text("Game Over\nPress 'S' to play again", width/2, height/2);
textAlign(LEFT);
if(keys[83]) {
screen = 2;
gameOver = false;
}
}
void playGame() {
if(screen === 0) {
if(mouseX >= width/2-50 && mouseY <= width/2+50 && mouseY >= height/2-15 && mouseY <= height/2+15) {
if(mousePressed) {
screen = 1;
}
}
}
}
void makeScreen() {
if(screen === 0) {
textAlign(CENTER);
textSize(30);
text('SNAKE GAME', width/2, 100);
stroke(255,255,255);
noFill();
rectMode(CENTER);
rect(width/2, height/2, 100, 30);
textSize(15);
text('Play', width/2, height/2+5);
textSize(11);
text('By Eskimopest', width/2, height-20);
textAlign(LEFT);
rectMode(LEFT);
playGame();
}
if(screen === 1) {
snake.draw();
snake.move();
snake.checkColl();
apple.draw();
if(nBonus === 1) {
bonus.draw();
}
fill(0);
text('POINTS : '+ snake.points, 10, 20);
text('APPLES : '+ snake.apples, 10, 40);
}
if(screen === 2) {
snake.points = 0;
snake.apples = 0;
snake.x = width/2;
snake.y = height/2;
snake.len = 1;
snake.positions = [{x:snake.x, y:snake.y}];
snake.snakePosX = 0;
snake.snakePosY = 0;
applePosX = round(random(10,width-appleSize)/10)*10;
applePosY = round(random(10,height-appleSize)/10)*10;
screen = 1;
}
}
// -----------------------------------------------------------------------
void draw() {
background(bg);
makeScreen();
for(var i=0; i<snake.positions.length; i++) {
text(i + 'x:'+snake.positions[i].x + ' y:'+snake.positions[i].y, 600, 20+i*10);
}
}
The problem is in snake.prototype.checkColl and I'm trying to make this work but with no results. When I try to make
if(this.positions[0].x = this.positions[i].x)
nothing happens. If anyone could help me I would be very appreciated.
That should be:
if(this.positions[0].x == this.positions[i].x)
Using a single = is doing an assignment. You want to do a comparison, so you need double ==.

Categories

Resources