I made a snake game that works almost completely. I have one snake head, and an array which contains the head and all of the tails. When the snake eats a food, the food moves location, but my tail isn't getting bigger when I eat the food. I don't have an IMMENSE understanding of arrays, perhaps I'm doing it wrong?
Here is the code:
setSize(400, 400);
var background = new Rectangle(getWidth(), getHeight());
background.setPosition(0, 0);
background.setColor(Color.black);
add(background);
// ------------------------------------------------
var gameTime = 0;
var snakeX = (Randomizer.nextInt(0, 19)) * 20;
var snakeY = (Randomizer.nextInt(0, 19)) * 20;
var foodX;
var foodY;
var snakeFood = new Rectangle(20, 20);
snakeFood.setColor(Color.red);
var food_eaten = 0;
var snakeSpeed = 20;
var keyLeft = false;
var keyRight = false;
var keyUp = false;
var keyDown = false;
var snake_size = 10;
var snakeHead = new Rectangle(20, 20);
snakeHead.setColor(Color.green);
var snakes = [snakeHead];
// ------------------------------------------------
function start(){
setup();
keyDownMethod(checkKey);
setTimer(counter, 250);
}
function counter(){
gameTime += 0.25;
updateSnake();
}
function setup(){
foodX = (Randomizer.nextInt(0, 19)) * 20;
foodY = (Randomizer.nextInt(0, 19)) * 20;
snakeHead.setPosition(snakeX, snakeY);
add(snakeHead);
snakeFood.setPosition(foodX, foodY);
add(snakeFood);
}
function checkKey(e){
if(e.keyCode == Keyboard.LEFT){
keyRight = false;
keyUp = false;
keyDown = false;
keyLeft = true;
}else if(e.keyCode == Keyboard.RIGHT){
keyLeft = false;
keyUp = false;
keyDown = false;
keyRight = true;
}else if(e.keyCode == Keyboard.UP){
keyRight = false;
keyLeft = false;
keyDown = false;
keyUp = true;
}else if(e.keyCode == Keyboard.DOWN){
keyRight = false;
keyLeft = false;
keyUp = false;
keyDown = true;
}
}
function updateSnake(){
if(foodX == snakeX && foodY == snakeY){
eat();
}
var dirX = 0;
var dirY = 0;
if(keyLeft == true){
dirX = -(snakeSpeed);
dirY = 0;
}else if(keyRight == true){
dirX = snakeSpeed;
dirY = 0;
}else if(keyUp == true){
dirY = -(snakeSpeed);
dirX = 0;
}else if(keyDown == true){
dirY = snakeSpeed;
dirX = 0;
}
// moving the snake head
snakeHead.setPosition(snakeX + dirX, snakeY + dirY);
snakeX += dirX;
snakeY += dirY;
// moving the snake body
if(snakes.length > 1){
for(var i = 0; i < snakes.length; i++){
var curr_body = snakes[i];
curr_body.setPosition(snakeX + dirX, snakeY + dirY);
}
}
}
function eat(){
foodX = (Randomizer.nextInt(0, 19)) * 20;
foodY = (Randomizer.nextInt(0, 19)) * 20;
var tail = new Snake(snakeX, snakeY);
snakeFood.setPosition(foodX, foodY);
}
function Snake(x, y){
var snakeBody = new Rectangle(20, 20);
if(keyLeft == true){
snakeBody.setPosition(x + snake_size, y);
}if(keyRight == true){
snakeBody.setPosition(x - snake_size, y);
}if(keyUp == true){
snakeBody.setPosition(x, y + snake_size);
}if(keyDown == true){
snakeBody.setPosition(x, y - snake_size);
}
snakeBody.setColor(Color.green);
snakes.push(snakeBody);
add(snakeBody);
}
In your eat() function, you assign a new Snake object to a var tail, but then do nothing with it. I think you need to add it to your snakes array (which I assume represents the entire snake?)
Related
I am creating a Create.js 2D game engine in JavaScript and need a way to center the player (which will be a sprite placed in the center of the screen) when the main container is scaled. It should be an offset to the containers translation every time the world is scaled, but I can't figure out how to do the calculation so I have put a ?? and comments where I need help with the code. How do I figure out how much to translate the container to the center when it is scaled? Code below.
var stage;
var canvas;
var map;
var move = [];
var viewDist = 2;
var chunkSize = 16;
var mapSize = 32;
var view_chunks = [];
var chunks = [];
var posX;
var posY;
var tileSize = 16;
var chunksContainer;
var playerPosX = 0;
var playerPosY = 0;
var chunkPosX = 0;
var chunkPosY = 0;
var scale = 3;
var SPRITESHEET;
var tiles = [];
var speed = 0.2;
var moveForward = false;
var moveBackward = false;
var chunksContainer = new createjs.Container();
var halfW = window.innerWidth/2
var halfH = window.innerHeight/2
var scaleFactor = 0.1;
this.document.onkeydown = keydown;
function keydown(event) {
/** you can access keyCode to determine which key was pressed**/
var keyCode = event.keyCode;
if(keyCode == 87){
move[0] = true;
}
if(keyCode == 83){
move[1] = true;
}
if(keyCode == 65){
move[2] = true;
}
if(keyCode == 68){
move[3] = true;
}
if(keyCode == 187){
if(scale < 4){
scale = scale + 0.1;
}
}
if(keyCode == 189){
if(scale > ((viewDist*2+5)*chunkSize*tileSize)/window.innerWidth){
scale = scale - 0.1;
//chunksContainer.x = chunksContainer.x ??
//chunksContainer.y = chunksContainer.y ??
}
console.log(scale)
}
//console.log(keyCode)
}
this.document.onkeyup = keyup;
function keyup(event) {
/** you can access keyCode to determine which key was pressed**/
var keyCode = event.keyCode;
if(keyCode == 87){
move[0] = false;
}
if(keyCode == 83){
move[1] = false;
}
if(keyCode == 65){
move[2] = false;
}
if(keyCode == 68){
move[3] = false;
}
console.log(event.keyCode)
}
function generateMap() {
map = [];
for(var x = 0; x < mapSize*chunkSize; x++){
map[x] = []
for(var y = 0; y < mapSize*chunkSize; y++){
map[x][y] = 5;
if(Math.floor(Math.random() * 11) == 1){
map[x][y] = 1;
}
}
}
}
function getTile(col,row,x,y){
col = col%mapSize;
row = row%mapSize;
if(col < 0){
col = mapSize + col;
}
if(row < 0){
row = mapSize + row;
}
col = Math.abs(col);
row = Math.abs(row);
return map[col*chunkSize + x][row*chunkSize+y]
}
function init(){
canvas = document.getElementById("canvas");
canvas.width = document.body.clientWidth; //document.width is obsolete
canvas.height = document.body.clientHeight; //document.height is obsolete
// create a new stage and point it at our canvas:
stage = new createjs.Stage("canvas");
// load the spritesheet image:
var image = new Image();
image.onload = handleLoad;
image.src = "../assets/spritesheet/roguelikeSheet_transparent.png";
}
var tiles;
function generateChunks(x,y){
chunksContainer = new createjs.Container();
chunksContainer.scale = scale;
chunksContainer.x = 0
chunksContainer.y = 0
chunksContainer.regX = (viewDist*2)*chunkSize*tileSize/2
chunksContainer.regY = (viewDist*2)*chunkSize*tileSize/2
for(col = 0; col < viewDist*2; col++){
tiles[col] = []
for(row = 0; row < viewDist*2; row++){
tiles[col][row] = []
for (var x=0; x<chunkSize; x++) {
tiles[col][row][x] = []
for (var y=0; y<chunkSize; y++) {
var idx = getTile(chunkPosX + col,chunkPosY + row,x,y);
tiles[col][row][x][y] = new createjs.Sprite(SPRITESHEET)
.set({x: 16*(col * 16 + x), y:16*(row * 16 + y)});
tiles[col][row][x][y].gotoAndStop(idx);
chunksContainer.addChild(tiles[col][row][x][y]);
}
}
}
}
stage.addChild(chunksContainer);
}
function updateChunks(){
for(col = 0; col < viewDist*2; col++){
for(row = 0; row < viewDist*2; row++){
for (var x=0; x<chunkSize; x++) {
for (var y=0; y<chunkSize; y++) {
var idx = getTile(chunkPosX + col,chunkPosY + row,x,y);
tiles[col][row][x][y].gotoAndStop(idx);
}
}
}
}
}
function handleLoad(evt) {
// define the spritesheet:
SPRITESHEET = new createjs.SpriteSheet({
images: [evt.target],
frames: {width:16, height:16, regX:16, regY:16, spacing:1, margin:0, count:1680}
});
generateMap();
generateChunks();
stage.update();
// update the stage to draw to screen:
createjs.Ticker.addEventListener("tick", handleTick);
}
chunkPlayerPosY = 0;
chunkPlayerPosX = 0;
function handleTick(event) {
if(move[0]){
chunksContainer.y = chunksContainer.y + speed * createjs.Ticker.getMeasuredTickTime() * scale;
}
if(move[1]){
chunksContainer.y = chunksContainer.y - speed * createjs.Ticker.getMeasuredTickTime() * scale;
}
if(move[2]){
chunksContainer.x = chunksContainer.x + speed * createjs.Ticker.getMeasuredTickTime() * scale;
}
if(move[3]){
chunksContainer.x = chunksContainer.x - speed * createjs.Ticker.getMeasuredTickTime() * scale;
}
if(chunksContainer.y > halfH + chunkSize*tileSize * scale){
chunksContainer.y = halfH;
chunkPosY = chunkPosY - 1
console.log(chunkPosY)
updateChunks();
}
if(chunksContainer.y < halfH){
chunksContainer.y = halfH + chunkSize*tileSize * scale;
chunkPosY = chunkPosY + 1
console.log(chunkPosY)
updateChunks();
}
if(chunksContainer.x > halfW + chunkSize*tileSize * scale){
chunksContainer.x = halfW;
chunkPosX = chunkPosX - 1
console.log(chunkPosX)
updateChunks();
}
if(chunksContainer.x < halfW){
chunksContainer.x = halfW + chunkSize * tileSize * scale;
chunkPosX = chunkPosX + 1
console.log(chunkPosX)
updateChunks();
}
chunksContainer.scale = scale;
stage.update();
}
I need to remove newCircle.fillColor = "red"; in order to get colors other than red but when i remove it, it says the property of hue is undefined.
var circles = [];
function onKeyDown(event) {
var maxPoint = new Point(view.size.width, view.size.height);
var randomPoint = Point.random();
var point = maxPoint * randomPoint;
var newCircle = new Path.Circle(point,500)
if(event.key === "a"){
bubbles.play();
newCircle.fillColor = "#2c3e50";
}
else if(event.key === "b"){
newCircle.fillColor = "#2c3e50";
clay.play();
}
else if(event.key === "c"){
newCircle.fillColor = "#00ff0f";
confetti.play();
}
newCircle.fillColor = "red";
circles.push(newCircle);
}
function onFrame(event){
for(var i = 0; i < circles.length; i++){
circles[i].fillColor.hue += 1;
circles[i].scale(.9);
}
}
Either set the fillColor before the if statements (like the below code snippet) or have an else statement.
var circles = [];
function onKeyDown(event) {
var maxPoint = new Point(view.size.width, view.size.height);
var randomPoint = Point.random();
var point = maxPoint * randomPoint;
var newCircle = new Path.Circle(point,500)
newCircle.fillColor = "red";
if(event.key === "a"){
bubbles.play();
newCircle.fillColor = "#2c3e50";
}
else if(event.key === "b"){
newCircle.fillColor = "#2c3e50";
clay.play();
}
else if(event.key === "c"){
newCircle.fillColor = "#00ff0f";
confetti.play();
}
circles.push(newCircle);
}
function onFrame(event){
for(var i = 0; i < circles.length; i++){
circles[i].fillColor.hue += 1;
circles[i].scale(.9);
}
}
I would also suggest using a switch statement and moving that if else section to another function.
I have three variables that I need to put in the innerHTML of four spans. The variables I use are seconds, accurateclick, and inaccurateclick. The process I use to get these variables is fine. The problem is I can't figure out how to bring them over to another function. I will make a replica of what I have. This will be a simpler version.
var x;
var y;
var z;
function A(){
x = 1;
y = 2;
z = 3;
B();
}
function B(){
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
}
What would happen is, instead of a being equal to 1, b being equal to 2, and c being equal to 3, they would all equal to undefined. I don't know why that is happening when x, y, and z are global variables. I thought they should change when set to a different value.
Here is my actual code:
var seconds;
var accurateclicks;
var inaccurateclicks;
var windowheight = window.innerHeight;
var windowwidth = window.innerWidth;
var colors = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"];
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
function BeginGameLoad(){
var BottomLabel1 = document.getElementById("bl1");
var BeginGameContainer = document.getElementById("BGC1");
var RightClick = false;
BottomLabel1.addEventListener("mousedown", BL1MD);
BottomLabel1.addEventListener("mouseup", BL1MU);
BottomLabel1.style.cursor = "pointer";
window.addEventListener("resize", BeginGameResize);
window.addEventListener("contextmenu", BeginGameContextMenu);
function BeginGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL1MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
var randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel1.style.color = randomcolor;
RightClick = false;
}
}
function BL1MU(){
if(RightClick == false){
window.location.href = "Game.html";
GameLoad();
}
else{
RightClick = false;
}
}
if(windowheight < 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
BeginGameContainer.style.width = "800px";
}
function BeginGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
BeginGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
BeginGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
BeginGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
BeginGameContainer.style.width = "100%";
}
}
}
function GameLoad(){
var LeftPanel2 = document.getElementById("lp2");
var LeftColorPanel2 = document.getElementById("lcp2");
var TopPanel2 = document.getElementById("tp2");
var TopLabel2 = document.getElementById("tl2");
var RightPanel2 = document.getElementById("rp2")
var RightLabel2 = document.getElementById("rl2");
var GameContainer = document.getElementById("GC2");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var clickedRightName = false;
var clickedRightColor = false;
var clickedRightNameColor = false;
var RightClick = false;
var ClickedLeftColorPanel = false;
var ClickedRightLabel = false;
var ClickedTopLabel = false;
var Timer;
TopPanel2.addEventListener("mouseup", TP2MU);
TopLabel2.addEventListener("mousedown", TL2MD);
TopLabel2.addEventListener("mouseup", TL2MU);
TopLabel2.style.cursor = "pointer";
LeftPanel2.addEventListener("mouseup", LP2MU);
LeftColorPanel2.addEventListener("mouseup", LCP2MU);
LeftColorPanel2.addEventListener("mousedown", LCP2MD);
LeftColorPanel2.style.cursor = "pointer";
RightPanel2.addEventListener("mouseup", RP2MU);
RightLabel2.addEventListener("mouseup", RL2MU);
RightLabel2.addEventListener("mousedown", RL2MD);
RightLabel2.style.cursor = "pointer";
window.addEventListener("resize", GameResize);
window.addEventListener("contextmenu", GameContextMenu);
function AddSeconds(){
seconds++;
}
function GameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function TL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true){
TopLabel2.style.color = randomcolor;
RightClick = false;
}
}
function TP2MU(){
if(ClickedTopLabel == false){
inaccurateclicks++;
}
else{
ClickedTopLabel = false;
}
}
function TL2MU(){
ClickedTopLabel = true;
if(clickedRightName == true && clickedRightColor == true && clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
accurateclicks++;
window.location.href = "EndGame.html";
EndGameLoad();
}
else if (!clickedRightName == true && !clickedRightColor == true && !clickedRightNameColor == true && RightClick == false){
clearInterval(Timer);
Timer = setInterval(AddSeconds, 1000);
seconds = 0;
accurateclicks = 0;
inaccurateclicks = 0;
TopLabel2.innerHTML = randomcolor;
RightClick = false;
}
else{
inaccurateclicks++;
}
RightClick == false
}
function LCP2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function LCP2MU(){
ClickedLeftColorPanel = true;
if(clickedRightColor == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == LeftColorPanel2.style.backgroundColor){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.color){
LeftColorPanel2.style.backgroundColorr = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != LeftColorPanel2.style.backgroundColor){
LeftColorPanel2.style.backgroundColor = randomcolor2;
accurateclicks++;
}
if (LeftColorPanel2.style.backgroundColor == randomcolor.toLowerCase()){
clickedRightColor = true;
LeftColorPanel2.style.cursor = "auto";
}
randomcolor2 = null;
RightClick = false;
}
else if(clickedRightColor == true && RightClick == false){
inaccurateclicks++;
}
}
function LP2MU(){
if(ClickedLeftColorPanel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
function RL2MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true;
}
else{
RightClick = false;
}
}
function RL2MU(){
ClickedRightLabel = true;
if(clickedRightName == false && TopLabel2.innerHTML != "Click Here To Start" && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2 == RightLabel2.innerHTML){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2 != RightLabel2.innerHTML){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2 != RightLabel2.color){
RightLabel2.innerHTML = randomcolor2;
accurateclicks++;
}
if (RightLabel2.innerHTML == randomcolor){
clickedRightName = true;
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == false && RightClick == false){
var randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
while (randomcolor2.toLowerCase() == RightLabel2.style.color){
randomcolor2 = null;
randomcolor2 = colors[Math.floor(Math.random()*colors.length)];
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
break;
}
}
if(randomcolor2.toLowerCase() != RightLabel2.style.color){
RightLabel2.style.color = randomcolor2;
accurateclicks++;
}
if (RightLabel2.style.color == randomcolor.toLowerCase()){
clickedRightNameColor = true;
RightLabel2.style.cursor = "auto";
}
randomcolor2 = null;
}
else if(clickedRightName == true && clickedRightNameColor == true && RightClick == false){
inaccurateclicks++;
}
}
function RP2MU(){
if(ClickedRightLabel == false){
inaccurateclicks++;
}
else{
ClickedLeftColorPanel = false;
}
}
if(windowheight < 600)
{
GameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
GameContainer.style.width = "800px";
}
function GameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
GameContainer.style.height = "600px";
}
if(windowheight > 600)
{
GameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
GameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
GameContainer.style.width = "100%";
}
}
}
function EndGameLoad(){
var BottomLabel3 = document.getElementById("bl3");
var EndGameContainer = document.getElementById("EGC3");
var MiddleLabelTwo = document.getElementById("mltwo3");
var MiddleLabelThree = document.getElementById("mlthree3");
var MiddleLabelFour = document.getElementById("mlfour3");
var MiddleLabelFive = document.getElementById("mlfive3");
var RightClick = false;
BottomLabel3.addEventListener("mousedown", BL3MD);
BottomLabel3.addEventListener("mouseup", BL3MU);
BottomLabel3.style.cursor = "pointer";
window.addEventListener("resize", EndGameResize);
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
window.addEventListener("contextmenu", EndGameContextMenu);
function EndGameContextMenu(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
}
}
function BL3MD(e){
if(e.which == 3 || e.button == 2){
e.preventDefault();
RightClick = true
}
else{
randomcolor = colors[Math.floor(Math.random()*colors.length)];
BottomLabel3.style.color = randomcolor;
RightClick = false;
}
}
function BL3MU(){
if(RightClick == false){
MiddleLabelTwo.innerHTML = "Time (Seconds): "
MiddleLabelThree.innerHTML = "Accurate Clicks: "
MiddleLabelFour.innerHTML = "Inaccurate Clicks: "
MiddleLabelFive.innerHTML = "Score: "
window.location.href = "Game.html";
}
}
if(windowheight < 600)
{
EndGameContainer.style.height = "600px";
}
if(windowwidth < 800)
{
EndGameContainer.style.width = "800px";
}
function EndGameResize(){
windowheight = window.innerHeight;
windowwidth = window.innerWidth;
if(windowheight <= 600)
{
EndGameContainer.style.height = "600px";
}
if(windowheight > 600)
{
EndGameContainer.style.height = "100%";
}
if(windowwidth <= 800)
{
EndGameContainer.style.width = "800px";
}
if(windowwidth > 800)
{
EndGameContainer.style.width = "100%";
}
}
}
Whenever I run it, it works up to this point
MiddleLabelTwo.innerHTML += seconds;
MiddleLabelThree.innerHTML += accurateclicks;
MiddleLabelFour.innerHTML += inaccurateclicks;
MiddleLabelFive.innerHTML += seconds + accurateclicks + inaccurateclicks;
It says seconds, accurateclicks, and inaccurateclicks are all undefined. I don't know why this would happen given that they were defined in the previous function [Game()].
try writing,
x = 1;
y = 2;
z = 3;
function A() {
B();
}
function B() {
var a = "";
var b = "";
var c = "";
var d = "";
a += x;
b += y;
c += z;
d += (x + y + z);
console.log(a, b, c, d);
}
A();
Reason: 'var' defines variables locally!
You did make two html files and this caused the js file to reload. This is why the global variables are declared again and are renewed to undefined.The solution is to work with one html file and to only reload the body.
My syntax was right, but as #Julie mentioned, the variables were being reloaded. How to get JS variable to retain value after page refresh? this helped me solve my problem.
I have a puzzle and piece. Piece 5 x 5 covering all puzzle.
When client on click piece, piece disable, show part puzzle underneath piece. I using canvas draw two layer but not working.
function init( img ){
if( img == undefined ){
img="http://amitysmiletravel.com/sites/a/am/amity/uploads/ckfinder/images/amitysmile-hotel(10).jpg";
}
_img = new Image();
_img.addEventListener('load',onImage,false);
_img.src = img ;
}
function onImage(e){
_pieceWidth = Math.floor(_img.width / PUZZLE_DIFFICULTY)
_pieceHeight = Math.floor(_img.height / PUZZLE_DIFFICULTY)
_puzzleWidth = _pieceWidth * PUZZLE_DIFFICULTY;
_puzzleHeight = _pieceHeight * PUZZLE_DIFFICULTY;
setCanvas();
initPuzzle();
}
function setCanvas(){
_canvas = $('#game-state');
_stage = _canvas[0].getContext('2d');
_canvas[0].width = _puzzleWidth;
_canvas[0].height = _puzzleHeight;
// _canvas[0].style.border = "1px solid #004D3D";
}
function initPuzzle(){
_pieces = [];
_mouse = {x:0,y:0};
_currentPiece = null;
_currentDropPiece = null;
_stage.drawImage(_img, 0, 0, _puzzleWidth, _puzzleHeight, 0, 0, _puzzleWidth, _puzzleHeight);
initPieces();
}
function initPieces(){
/*if( img == undefined ){
img="<?php echo Yii::app()->theme->baseUrl?>/images/piece_bg.png";
}*/
_imgPiece = new Image();
_imgPiece.addEventListener('load',buildPieces,false);
_imgPiece.src = "<?php echo Yii::app()->theme->baseUrl?>/images/piece_bg.png";
}
var buildPieces = function(){
_stage.clearRect(0,0,_puzzleWidth,_puzzleHeight);
var i;
var piece ;
var xPos = 0;
var yPos = 0;
for(i = 0; i < 25; i++){
piece ={};
piece.xPos = xPos;
piece.yPos = yPos;
_pieces.push(piece);
_stage.drawImage(_imgPiece,piece.xPos,piece.yPos,_pieceWidth,_pieceHeight);
_stage.strokeRect(xPos,yPos,_pieceWidth,_pieceHeight);
xPos += _pieceWidth;
if(xPos >= _puzzleWidth){
xPos = 0;
yPos += _pieceHeight;
}
}
if( !touchSupported ){
$('#game-state').on('mousedown', onPuzzleClick);
}else{
// document.ontouchstart = null;
$('#game-state').on('touchstart',function( e ){
var e = e.originalEvent;
e.preventDefault();
onPuzzleClick( e );
});
}
}
function onPuzzleClick(e){
// alert(e);
if( !Modernizr.touch ){
_mouse.x = e.pageX - _canvas.offset().left;
_mouse.y = e.pageY - _canvas.offset().top;
}else{
_mouse.x = e.touches[0].pageX - _canvas.offset().left;
_mouse.y = e.touches[0].pageY - _canvas.offset().top;
}
// alert("x "+_mouse.x+" y: "+_mouse.y);
_currentPiece = checkPieceClicked();
if(_currentPiece != null){
_stage.clearRect(_currentPiece.xPos,_currentPiece.yPos,_pieceWidth,_pieceHeight);
_stage.save();
}
}
function checkPieceClicked(){
var i;
var piece;
for(i = 0;i < _pieces.length;i++){
piece = _pieces[i];
if(_mouse.x < piece.xPos || _mouse.x > (piece.xPos + _pieceWidth) || _mouse.y < piece.yPos || _mouse.y > (piece.yPos + _pieceHeight)){
//PIECE NOT HIT
}
else{
return piece;
}
}
return null;
}
please help me. Thank!
I'm brand new to JavaScript, and have a crashing application. I have no idea what would cause the crash.
Here is the code:
<script>
//constants
var Col = 20, Rows = 20;
var cellHeight = 25;
var cellWidth = 25;
var foodX;
var score;
var foodY;
var Nothing = 0, Snake = 1, Food = 2;
var Left = 37, Up = 38, Right = 39, Down = 40;
var canvas = document.getElementById('snakeCanvas');
var context = canvas.getContext('2d');
var dead = "false";
var snakeDirection = null;
var keystate;
var snake = [];
function start() //this is where we begin the long journey
{
init();
Tick();
}
function init() {
snake = [{ x: 5, y: 5 }];
snakeDirection = null;
score = 0;
document.getElementById("score").innerHTML = "Score: " + score;
setFood();
keystate = null;
}
function Tick() // just liker a timer tick
{
document.addEventListener("keydown", function (evt) {
keystate = evt.keyCode; // checks key presses
});
//document.addEventListener("keyup", function (evt) {
//delete keystate[evt.keyCode];
//});
update(); //after we check for a key press we update alllll the
stuff
setTimeout(Tick, 300);
//}
}
function update()
{
checkKey(); // checks what key has been pressed
for (var i = snake.length-1; i > 0; i--) {
snake[i].y = snake[i-1].y;
snake[i].x = snake[i-1].x
}
switch (snakeDirection) { // keys
case "DOWN":
snake[0].y++;
break;
case "UP":
snake[0].y--;
break;
case "RIGHT":
snake[0].x++;
break;
case "LEFT":
snake[0].x--;
break;
}
draw(); //draws all the stuff like food and snake
checkCollisions(); // self explaintory name
}
function checkKey() //Change the direction of the snake cant go
backwards too
{
if (keystate == Left && snakeDirection != "RIGHT" )
{
snakeDirection = "LEFT";
}
if (keystate == Up && snakeDirection != "DOWN")
{
snakeDirection = "UP";
}
if (keystate == Right && snakeDirection != "LEFT")
{
snakeDirection = "RIGHT";
}
if (keystate == Down && snakeDirection != "UP")
{
snakeDirection = "DOWN";
}
}
function setFood()
{ //WE ARE RUNNING OUT OF FOOD WE NEED NEW PROVISIONS
var next = "true"
do {
foodX = Math.floor((Math.random() * Rows));
foodY = Math.floor((Math.random() * Col));
for (var i = 0; i < snake.length; i++) { // IT SUCKS WHEN I
CANT EAT FOOD BECAUSE ITS ALREADY INSIDE OF ME
if (snake[i].x == foodX && snake[i].y == foodY) {
next = "false"
}
}
}
while (next == "false")
draw(); // Pretty pictures
}
function checkCollisions()
{
for (var i = 1; i < snake.length; i++) { // STOP hitting
yourself
if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) {
init();
}
}
if (snake[0].y < 0 || snake[0].y > Rows || snake[0].x < 0 ||
snake[0].x > Col) // you are forbidon to veture from the canvas
{
init();
}
if (snake[0].x == foodX && snake[0].y == foodY) { //Yummy FOOD EAT
EAT EAT
score++;
document.getElementById("score").innerHTML = "Score: " + score;
setFood();
snake.push({ x: null, y: null }); // I got fatter
}
}
function draw()
{
context.clearRect(0, 0, canvas.width, canvas.height); // clears
canvas
context.fillStyle = "#FF0000"; // pretty colour for the head of
the snake
context.fillRect(snake[0].x * cellWidth, snake[0].y * cellWidth,
cellWidth, cellHeight);
context.fillStyle = "#09F";
for (var i = 1; i < snake.length; i++)
{
context.fillRect(snake[i].x * cellWidth, snake[i].y * cellWidth,
cellWidth, cellHeight);
}
context.fillStyle = "#F90"; // FOOD FOOD FOOD FOOD
context.fillRect(foodX * cellWidth, foodY * cellWidth, cellWidth,
cellHeight);
}
start(); // starts hence the name start
</script>
OK not bad for a beginer if you wrote it all your self.
Your problem is with the keydown event. You are creating a new handler each time you tick. This will lead to a crash. You only need to create the event handler once for the page, it will remain active until you leave the page.
To fix your problem move adding the keyDown listener to just above the function Start, as shown below.
var snake = [];
document.addEventListener("keydown", function (evt) {
keystate = evt.keyCode; // checks key presses
});
function start(){
init();
Tick();
}
Also just a because to me it looks weird. true and false are not strings you dont need to put quotes around them. Though using them as strings still works.
You have
function setFood() { //WE ARE RUNNING OUT OF FOOD WE NEED NEW PROVISIONS
var next = "true"
do {
foodX = Math.floor((Math.random() * Rows));
foodY = Math.floor((Math.random() * Col));
for (var i = 0; i < snake.length; i++) {
if (snake[i].x == foodX && snake[i].y == foodY) {
next = "false"
}
}
} while (next == "false")
draw();
}
would be better written as follows
function setFood() {
var next = true; // removed the qoutes
do {
foodX = Math.floor((Math.random() * Rows));
foodY = Math.floor((Math.random() * Col));
for (var i = 0; i < snake.length; i++) {
if (snake[i].x == foodX && snake[i].y == foodY) {
next = false; // removed the quotes.
// no point continuing the for loop as you know you need to
// reposition the food so use the break token
break; // breaks out of the closest loop
}
}
} while ( !next ) // removed next == "false" and replaced with
// ! next. "!" means "Not". do while next not true
// you have the draw here but you draw every tick so it would be best if
// you removed it as the next draw is less than 1/3 of a second away anyways
// draw(); // removed needless draw
}
Good work. Hope you get a good mark for it.