Jump to content

Need help with .js game on phone


vmars316

Recommended Posts

They're just syntax errors, syntax errors are easy to debug.

 

In my previous post I told you how to fix the hitTest method which had a mistake.

Game.hitTest = function(a,  {
There's also a mistake I made here, it should be using Game.cowpies:
Game.createCowpie = function() {
  cowpies.push(new Cowpie());
}

But you still seem to be missing the bigger picture, have you determined the structure of your game? The code itself does not matter very much, you should have the game designed well enough that it could be programmed in any language. You have to describe all the objects, their properties and methods, and the interactions between the objects.

 

The code I wrote is incomplete, it's just setting up some of the objects. If I write much more code I'll have built the whole game.

 

Pls notice that the code I last presented does include the changes you mentioned .

I had already fixed the errors .

I deliberately removed the "objects, their properties and methods" to make it easier to debug js syntax .

Again , what I am trying to do now , is simply to debug the js syntax ,

I am trying to establish an error free 'starting point . So that any errors that pop up after this 'starting point' are indeed my errors .

The code I wrote is incomplete

 

Yes I realize that . Isn't the diagram that you gave me , though incomplete , program structure ?

Or do you mean something else ?

Thanks

Link to comment
Share on other sites

  • Replies 73
  • Created
  • Last Reply

Top Posters In This Topic

There's also a mistake I made here, it should be using Game.cowpies:

Game.createCowpie = function() {
cowpies.push(new Cowpie());
}

 

Oops , I misunderstood what you were saying . I fixed code & no error here .

But I am still getting these errors:
: Uncaught SyntaxError: Unexpected token {
// Create or destroy cowpies
Game.createCowpie = function() {
cowpies.push(new Cowpie());
//}
Last js statement"
: Uncaught SyntaxError: Unexpected end of input
// Draw the sprite
this.draw = function() {
Game.context.drawImage(this.sprite, this.x, this.y, this.width, this.height);
}

 

 

Link to comment
Share on other sites

<!DOCTYPE html>

<html>

-<head>

<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

<meta charset="utf-8" />

<title>goBegin</title>



-->

</head>

<!--

<body onload="Game.start()" >

-->

<body>

<canvas id="canvas" width="600" height="450" style="background-color:#992D2D"></canvas>

<script type='text/javascript'>

/*****************/

/** Game object **/

/*****************/

/*****************/

/** Game object **/

/*****************/


var Game = {}


/* Properties */

// For drawing

Game.canvas = document.getElementById("canvas");

Game.graphics = Game.canvas.getContext("2d");


// Sounds

Game.sounds = {

splat : new Audio("sounds/CowMooSplat.mp3"),

goodbye : new Audio("sounds/GoodBye-Female.mp3"),

cheering : new Audio("sounds/cheeringCrowd.mp3"),

oops : new Audio("sounds/oops.mp3")

};


// Movable objects

Game.cowpies = [];

Game.thrower = new Thrower(document.getElementById("thrower"), 0, 0);

Game.target = new Target(document.getElementById("lie02"), 128, 24)


/* Methods */


// Play a sound

Game.playSound = function(sound) {

sound.play();

}


// Detect a rectangular collision between two objects

/*Game.hitTest(a, B) {

return a.x <= b.x + b.width &&

a.x + a.width >= b.x &&

a.y <= b.y + b.height &&

a.y + a.height >= b.y;

} */


// Create or detroy cowpies

Game.createCowpie = function() {

Game.cowpies.push(new Cowpie());

}


Game.destroyCowpie = function(cowpie) {

// Play sound

Game.playSound(Game.sounds.splat);


// Remove from cowpies

var count = Game.cowpies.length;

var destroyed = false;

for(var i = 0; i < count && !destroyed; i++) {

if(Game.cowpies == cowpie) {

destroyed = true;

Game.cowpies.splice(i, 1);

}

}


}


// Starts up the game

Game.start = function() {

// Start by playing the cheering sound

playSound(Game.sounds.cheering);


// Then begin the game loop, this code depends on what kind of loop you're using

}


// Ends the game

/*Game.end() {

// Stop the game loop, this code depends on what kind of loop you're using.

} */


// This is the game loop

Game.gameLoop = function() {


// Loop through objects and update them

var amount = Game.cowpies.length;

var cowpie;

for(var i = 0; i < amount; i++) {

cowpie = Game.cowpies;

cowpie.update();

}

thrower.update();

target.update();


// Detect collisions and do something

//

//


// Draw everything

context.clearRect(0, 0, Game.canvas.width, Game.canvas.height);

for(var i = 0; i < amount; i++) {

cowpie = Game.cowpies;

cowpie.draw();

}

thrower.draw();

target.draw();

}



/*********************/

/** Movable objects **/

/*********************/


/* Cowpie */

function Cowpie(sprite, x, y) {

this.sprite = sprite;

this.x = x;

this.y = y;

this.width = sprite.width;

this.height = sprite.height;


// Update position based on requirements

this.update = function() {


}


// Draw the sprite

this.draw = function() {

Game.context.drawImage(this.sprite, this.x, this.y, this.width, this.height);

}

}


/* Thrower */

function Thrower(sprite, x, y) {

this.sprite = sprite;

this.x = x;

this.y = y;

/* this.width = sprite.width;

this.height = sprite.height;

*/

// Update position based on requirements

this.update = function() {


}


// Draw the sprite

this.draw = function() {

Game.context.drawImage(this.sprite, this.x, this.y, this.width, this.height);

}

}


/* Target */

function Target(x, y) {

this.x = x;

this.y = y;

/* this.width = sprite.width;

this.height = sprite.height;

*/

// Update position based on requirements

this.update = function() {


}


// Draw the sprite

this.draw = function() {

Game.context.drawImage(this.sprite, this.x, this.y, this.width, this.height);

}

}


</script>

</body>

</html>

Link to comment
Share on other sites

I didn't provide a diagram, I just wrote some code with some incomplete object templates.

 

Why have you commented out the closing curly brace "}" in this code? That would be what's causing a syntax error.

// Create or destroy cowpies
Game.createCowpie = function() {
  cowpies.push(new Cowpie());
//}

The other errors likely just cascade down from there.

 

You seem to have completely commented out the hitTest() method, so it's not throwing errors, but doesn't do anything else either which isn't very useful.

 

Instead of pressing the <> button for code in your posts, just put your code between [ c o d e ] and [ / c o d e] tags.

Link to comment
Share on other sites

Thanks ;

Why have you commented out the closing curly brace "}" in this code?

 

Yes , I fixed that .

 

I still couldn't find all the errors , so I stripped out everything (js) except

var Game = {} and Game.start = function() {}

(then added Game.hitTest(a, B) {)

 

However when I pruned code down to this:

<script type='text/javascript'>
 
/** Game object **/
var Game = {}
 
// Movable objects
Game.cowpies = []; 
 
/* Properties */
// For drawing
Game.canvas = document.getElementById("canvas");
Game.context = Game.canvas.getContext("2d");
 
// Starts up the game 
Game.start = function() {
 
    }
 
// Detect a rectangular collision between two objects
Game.hitTest(a,  {
  return a.x <= b.x + b.width &&
         a.x + a.width >= b.x &&
         a.y <= b.y + b.height &&
         a.y + a.height >= b.y;
} //
</script>
I am still getting the
Uncaught SyntaxError: Unexpected token {

on this:

[code]
Game.hitTest(a, B) {
return a.x <= b.x + b.width &&
a.x + a.width >= b.x &&
a.y <= b.y + b.height &&
a.y + a.height >= b.y;
} //

[/code]

Can you see the error ?
By the way this:
Instead of pressing the <> button for code in your posts, just put your code between code tags .

 

Works great !

Thanks
Link to comment
Share on other sites

 


 

<!DOCTYPE html>
<html>
-<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta charset="utf-8" />
<title>GameObject.html</title>
-->
<style>
#assets { height: 0px; overflow: hidden; visibility: hidden; width: 0px; }
body { background-color: Black; margin: 0; overflow: hidden; padding: 0; }
canvas { cursor: none; }
table { color: #E1E1E1; background-color: #732222; height: 24px; width: 800px; border: none; }
button {font-size: 16px;}
#buttonsArea { color: #E1E1E1; background-color: #732222; width: 600px; border: none; }</style>
</head>
<body onload="Game.start()" >
<!--
-->
//<body>
<div>
<table align="center">
<tr>
<td width="10%">Screen Size </td> <td id="ScreenSize" width="10%"> </td>
<td width="5%"></td>
<td width="10%"> Good Hits</td> <td id="GoodHitz" width="5%"> </td>
<td width="8%"></td>
<td width="8%"> Total Shots </td> <td id="TotalShotz" width="5%"> </td>
</tr>
</table>
</div>
<div id="canvasDiv" align="center" >
<canvas id="canvas" width="600" height="450" style="background-color:#992D2D"></canvas>
<!-- <br><br> -->
<div id="buttonsArea">
<button onclick="touchUpArrow()" ontouchstart="touchUpArrow()">----Throw----</button>
<br><br>
<button onclick="catchButtons.pause()" ontouchstart="catchButtons.pause()" >Pause</button>
__ <button onclick="catchButtons.play()" ontouchstart="catchButtons.play()" >Play</button>
__ <button onclick="clearIt()" ontouchstart="clearIt()">Clear</button>
__ <button onclick="quitIt()" ontouchstart="quitIt()">Quit</button>
</div>
</div>
<div id="assets">
<img id="lie02" src="sprites/lies02.png" width="64" height="64" />
<img id="cowpie" src="sprites/cowpie.png" width="32" height="32" />
<img id="thrower" src="sprites/thrower.png" width="64" height="64" />
</div>
<script type='text/javascript'>
/* Globals */
var oops = 0; var goodHits = 0; var totalShots = 0; var ScreenSize = 0 ;
/*****************/
/** Game objects **/
var Game = {}
var My_audio_Urls = ["sounds/CowMooSplat.mp3",
"sounds/GoodBye-Female.mp3","sounds/cheeringCrowd.mp3","sounds/oops.mp3"];
// Sounds
Game.sounds = {
splat : new Audio("sounds/CowMooSplat.mp3"),
goodbye : new Audio("sounds/GoodBye-Female.mp3"),
cheering : new Audio("sounds/cheeringCrowdLow.mp3"),
oops : new Audio("sounds/oops.mp3")
};
var cached_Audio_files = [];
var allImgs = [ document.getElementById("thrower"), // 0
document.getElementById("lie02"), // 1
] ; // future version will have 9 images to load
// Movable objects
Game.cowpies = [];
var cowpie = Game.cowpies ;
var cowpieImg = document.getElementById("cowpie");
/* Properties For drawing */
Game.canvas = document.getElementById("canvas");
Game.context = Game.canvas.getContext("2d");
/* requestAnimationFrame */
var gid = 0;
var lastTimestamp = 0;
var timestamp = 0;
var Thrower = function () { // in future version Thrower will be able to move left and right
var self = this;
this.idTag = 'thrower';
this.x = (Game.canvas.width / 2) -30;
this.y = Game.canvas.height - 64;
this.width= 64;
this.height = 64;
this.visible = true;
this.speedX = 4;
this.speedY = 0;
this.directionX = 1;
this.moveMe = false ;
this.draw = function() { Game.drawSprite(0, thrower.x, thrower.y, thrower.width, thrower.height); } // Thrower
this.update = function() {
// self.speedX = resetSpeedX;
if (self.x > Game.canvas.width -50 ) { self.x = Game.canvas.width -51; self.moveMe = false ; }
if (self.x < 3) { self.x = 4; self.moveMe = false ; }
self.x = self.x + (self.speedX * self.directionX); // always either +1 or -1 }
}
}
//
thrower = new Thrower();
thrower.idTag = 'thrower';
//
var Cowpie = function () { // there can be several cowpies active at same time
var self = this;
this.idTag = 'cowpie';
this.idActive = true ;
this.index = 0;
this.x = thrower.x; // cowpie will always launch from the same coordinates as Thrower
this.y = thrower.y; // to simulate that Cowpie is being thrown by Thrower
this.width= 32;
this.height = 32;
this.speedX = 0;
this.speedY = 4;
this.visible = true;
this.directionY = -1;
this.draw = function() { Game.context.drawImage(cowpieImg, this.x, this.y, this.width, this.height); } // draw cowpie
} // var cowpie
//
var TargetImages = function () {
var self = this ;
this.idTag = "";
this.imageIndex = 1 ;
this.x = 0;
this.y = 4;
this.width= 64;
this.height = 64;
this.speedX = 4;
this.tripsCnt = 0 ;
this.tripMax = 2 ;
this.visible = true ;
this.directionX = 1;
this.update = function() { // Manage Target back and forth movement & manage Cowpie collisions
// alert(" self.idTag = " + this.idTag )
Game.drawSprite(this.imageIndex,this.x,this.y,this.width,this.height);
this.x = this.x + (this.speedX * this.directionX); // direction always = +1 or -1
// Check for collisions Cowpie/Target
// When collision occurs , destroy Cowpie , update scores , and play collision sound
if(this.x > Game.canvas.width - 2) {this.directionX = -1; // If sprite out of bounds occurs change direction
this.x = Game.canvas.width - 2;
this.tripsCnt++; // totalTrips++;
}
if(this.x < -64 ) {this.directionX = 1; // If sprite out of bounds occurs change direction
this.x = 0;
this.tripsCnt++; // totalTrips++;
}
for (var i = Game.cowpies.length - 1; i >= 0; i--) {
thisPie = i;
if (Game.cowpies[thisPie].idActive) {
if(self.visible) { // IF this Target is visible , do collision CK
if (Game.hitTest(lie02, Game.cowpies[thisPie]) ) { // alert("YES , a collision has occurred" )
yeslie = this.idTag.startsWith("lie");
yestru = this.idTag.startsWith("tru");
if (yeslie){ switch(this.idTag) {
case "lie02": lie02.visible=true ; goodHits += 1; // alert("case 'lie02': lie02.visible=true ;");
// lie02.tripsCnt =0 ; lie02.x = -60; this.speedX = 0;
// tru02.visible=true ; tru02.tripsCnt =0 ; tru02.x = 0; tru02.speedX = 1;
break ;
}
Game.playSound(Game.sounds.splat); // playsound for any liexx hit
}
if (yestru){
Game.playSound(Game.sounds.oops);
}
Game.cowpies.splice(thisPie,1);
}
}
}
}
} // endof or (var i = Game.cowpies.length - 1
} // this.update = function()
} // TargetImages
//
lie02 = new TargetImages();
lie02.idTag = "lie02";
lie02.imageIndex = 1 ;
lie02.x = 128;
lie02.y = 24;
lie02.speedX = 4 ;
lie02.tripsCnt = 0 ;
lie02.tripMax = 2 ;
lie02.visible = true ;
lie02.directionX = 1 ;
//
// Detect a rectangular collision between two objects
Game.hitTest = function(a, B) {
return a.x <= b.x + b.width &&
a.x + a.width >= b.x &&
a.y <= b.y + b.height &&
a.y + a.height >= b.y;
} // endof Game.hitTest = function
// Starts up the game
Game.start = function() {
// Start by playing the cheering sound
Game.playSound(Game.sounds.cheering);
Game.drawSprite(0,thrower.x,thrower.y,thrower.width,thrower.height);
Game.drawSprite(1,lie02.x,lie02.y,lie02.width,lie02.height);
catchButtons.start();
} // Game.start = function()
//
Game.gameLoop = function() { // This is the GAME LOOP
if (lastTimestamp == 0) {
lastTimestamp = timestamp;
}
Game.context.clearRect(0, 0, Game.canvas.width, Game.canvas.height);
thrower.draw();
updateScores ();
// Loop through cowpie objects and update them
var amount = Game.cowpies.length;
var cowpie;
for(var i = 0; i < amount; i++) {
cowpie = Game.cowpies;
cowpie.y = cowpie.y - cowpie.speedY ;
cowpie.draw();
}
// Draw everything else Game.hitTest done in TargetImages.update
if (lie02.visible) { lie02.update(); }
if(thrower.moveMe) { thrower.update(); thrower.draw(); }
lastTimestamp = timestamp;
gid = requestAnimationFrame(Game.gameLoop);
} // Game.gameLoop = function()
//
/* Methods */
// Play a sound
Game.playSound = function(sound) {
sound.play();
} // endof Game.playSound = function
// create cowpies
Game.createCowpie = function() {
Game.cowpies.push(new Cowpie());
index = (Game.cowpies.length - 1);
Game.cowpies[index].index = (Game.cowpies.length - 1);
// alert("Game.cowpies.[index].index = " + Game.cowpies[index].index )
} // Game.createCowpie = function()
// endof destroy cowpies
Game.destroyCowpie = function(cowpie) {
// Play sound
Game.playSound(Game.sounds.splat);
// Remove from cowpies
var count = Game.cowpies.length;
var destroyed = false;
for(var i = 0; i < count && !destroyed; i++) {
if(Game.cowpies == cowpie) {
destroyed = true;
Game.cowpies.splice(i, 1);
}
}
} // Game.destroyCowpie = function
//
Game.drawSprite = function (imgIndex,xPos,yPos,imgWidth,imgHeight) {
this.imgIndex = imgIndex ;
this.x = xPos ;
this.y = yPos ;
this.width = imgWidth ;
this.height = imgHeight ;
Game.context.drawImage(allImgs[this.imgIndex], this.x, this.y, this.width, this.height);
} // Game.drawSprite = function
//
var catchButtons = { //
start : function() {
gid = requestAnimationFrame(Game.gameLoop);
},
clear : function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
},
stop : function() {
cancelAnimationFrame(gid);
},
pause : function() {
cancelAnimationFrame(gid);
pausePlayCnt = 0;
},
play : function() {
pausePlayCnt ++ ;
if(pausePlayCnt < 2) {
gid = requestAnimationFrame(Game.gameLoop);
}
}
} // endof var catchButtons = {}
//
function onScrnResize(){
var w = window.innerWidth; var h = window.innerHeight;
// alert("function onScrnResize()"); window.innerWidth canvas.width
document.getElementById("ScreenSize").innerHTML =
window.innerWidth + " x " + window.innerHeight ;
} // function onScrnResize()
//
function clearIt() {
oops = 0; goodHits = 0; totalShots = 0;
updateScores ();
// var num = 15; var n = num.toString();
} // endof function clearIt()
//
function updateScores () {
var goodHitsA = goodHits.toString();
document.getElementById('GoodHitz').innerHTML = goodHitsA;
var totalShotsA = totalShots.toString();
document.getElementById('TotalShotz').innerHTML = totalShotsA;
}
//
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
//
function keyDownHandler(e) {
if(e.keyCode == 39 || event.keyCode == 68) { // move right D or --->
thrower.directionX = 1;
thrower.moveMe = true ;
thrower.x = thrower.x + 4;
// thrower.draw();
if (thrower.x > canvas.width -40) { thrower.moveMe = false ; }
}
if(e.keyCode == 37 || event.keyCode == 65) { // move left A or <---
thrower.directionX = -1;
thrower.moveMe = true ;
thrower.x = thrower.x - 4;
// thrower.draw();
if (thrower.x < 3) { thrower.moveMe = false ; }
}
if(e.keyCode == 87 || event.keyCode == 38 ) { // shoot = W or upArrow
Game.createCowpie();
totalShots ++;
} // Endof shoot = W or upArrow
} // endof function keyDownHandler
//
function keyUpHandler(e) {
if(e.keyCode == 39 || event.keyCode == 68) { // move = rightArrow or D
rightPressed = false ;
thrower.moveMe = false ;
// thrower.x = thrower.x + 4;
// thrower.draw();
}
else if(e.keyCode == 37 || event.keyCode == 65) { // move = leftArrow or A
leftPressed = false;
thrower.moveMe = false ;
// thrower.x = thrower.x -4;
// thrower.draw();
} // endof else if(e.keyCode == 37
} // endof function keyUpHandler(e)
//
function touchUpArrow() {
Game.createCowpie();
totalShots ++;
} // endof function touchUpArrow
//
function quitIt() {
Game.playSound(Game.sounds.goodbye);
clearIt();
catchButtons.pause();
}
//
function updateScores () {
goodHitsA = goodHits.toString();
document.getElementById('GoodHitz').innerHTML = goodHitsA;
totalShotsA = totalShots.toString();
document.getElementById('TotalShotz').innerHTML = totalShotsA;
}
//
</script>
</body>
</html>
Link to comment
Share on other sites

It seems I can't properly teach you software development on a forum, there are so many principles you can't grasp without prior experience.

 

I've attached a working game that runs smoothly on my phone, it will work provided you put it in the same location on your server and you use the same image and audio file names. Hopefully reading the code you can learn about structuring your software.

 

You seem to have missed out a whole lot of requirements when describing your game to me, here are some things I had to figure out by digging through your original code:

  • When a target gets hit by a cowpie it toggles its state between "tru" and "lies"
  • When a target bounces off the boundaries three times it also toggles a state change
  • Each state has a different image to represent it
  • There can be more than one target on the screen
  • Hitting a target in its "tru" state adds 1 to the "oops!" counter
  • Hitting a target in its "lies" state adds 1 to the "goodHits" counter
  • The total score is calculated with the following formula: goodHits * 4 - oops * 2

All these details and more are necessary in your requirements document. If you can't describe your game to somebody, how are you going to be able to build it?

index.html

Link to comment
Share on other sites

Wow , Thank you very much for all your help , works great !

Understanding/learning from  Your version will keep me busy for a long time .

Now I see what you meant by using as few Globals as possible :

function Game(c) {  //  from statement 173  to  366

  var self = this;  

 

 

You seem to have missed out a whole lot of requirements when describing your game to me, here are some things I had to figure out by digging through your original code:

  •  
  • When a target gets hit by a cowpie it toggles its state between "tru" and "lies"
  •  
  • When a target bounces off the boundaries three times it also toggles a state change
  •  
  • Each state has a different image to represent it
  •  
  • There can be more than one target on the screen
  •  
  • Hitting a target in its "tru" state adds 1 to the "oops!" counter
  •  
  • Hitting a target in its "lies" state adds 1 to the "goodHits" counter
  •  
  • The total score is calculated with the following formula: goodHits * 4 - oops * 2 

     

.

I understand what you are saying 
and I will review all my requirements above & add to as needed .
Side note: none of the requirements you mentioned above
are part of the original code I presented .
 

I had stripped down the code to use only 1 target ,

and react only by playing a sound on each hit . 

And thrower doesn't move .

Leaving all that other stuff for a future version .

 

However , you went far above and beyond what I had hoped for .

And I am  VERY THANKFUL  for what you have done , because now

I have 'examples of' for 'my future versions' .

 

 

I have Posted your code here: 

http://vmars.us/javascript/GameObject/Foxy.Mod-w3schools.invisionzone-ORIG.html

It runs great ! 

WindowsPhone, Chrome, Edge, InternetExplorer: 

And I notice that when I Restart/reLoad the game by hitting the Browser Reload-button 

or pressing cntrl+F5 , the game runs fine ,

except

that now the only visible images are bgcompound , manufacturer and cowpie .  

The target images are there , because they react to a 'cowpie hit' .

But they are invisible . 

I can solve this by a new button , maybe called "Play again!" ,

That sends me to:   window.location = "http://........

Pls , why is this happining , and is there a coding solution ? 

 

Thanks 

Edited by vmars316
Link to comment
Share on other sites

My guess is that upon creating the sprites the images haven't been loaded yet, so they have a width and height of 0.

 

That can be solved by wrapping the entire logic section in a function and set a window load event to call it. Remember to remove the window load event that's currently being used for game.start.

/***********//** Logic **//***********/window.addEventListener("load", setup, false);function setup() {  /** All logic here **/}/*************//** Objects **//*************/// The rest of the code
Link to comment
Share on other sites

Probably :)

 

But when I do it exactly like you said , no images and no sound .

/***********/
/** Logic **/
/***********/
window.addEventListener("load", setup, false);  //  Listen for Browser ReFresh-Button
function setup() {  // Wrap the entire logic section in a function and set a window load event to call 
 
/* Initialize the game object */
var canvas = document.getElementById("canvas");
var game = new Game(canvas);
 
// Sounds
game.sounds.splat = new Audio("sounds/CowMooSplat.mp3");
game.sounds.goodbye = new Audio("sounds/GoodBye-Female.mp3");
game.sounds.cheering = new Audio("sounds/cheeringCrowd.mp3");
game.sounds.oops = new Audio("sounds/oops.mp3");
 
// Sprites
game.sprites.background = document.getElementById("bgCompound");
game.sprites.manufacturer = document.getElementById("manufacturer");
game.sprites.cowpie = document.getElementById("cowpie");
 
 // Scores
game.scores.totalScore = document.getElementById("totalScore");
game.scores.oops = document.getElementById("oopsScore");
game.scores.hits = document.getElementById("goodHits");
game.scores.totalShots = document.getElementById("totalShots");
 
// Create thrower
var throwerSprite = document.getElementById("thrower");
var throwerX = canvas.width / 2; // Center of the canvas
var throwerY = canvas.height - throwerSprite.height; // Bottom of the canvas
var thrower = new Thrower(throwerSprite, throwerX, throwerY);
thrower.speed = 120 / 1000; // 120 pixels per second
thrower.cowpieSpeed = 180 / 1000; // 180 pixels per second
game.setThrower(thrower);
 
// Create targets
var hillarytrue = document.getElementById("tru02");
var hillarylies = document.getElementById("lie02");
 
var target1 = new Target(hillarylies, hillarytrue, 128, 24);
target1.speed = 120 / 1000; // 120 pixels per second
 
var target2 = new Target(hillarylies, hillarytrue, 0, 68);
target2.speed = 120 / 1000; // 120 pixels per second
 
game.addTarget(target1);
game.addTarget(target2);
 
/* Set event handlers */
// Pause/Resume
document.getElementById("pause").addEventListener("click", game.pause, false);
document.getElementById("play").addEventListener("click", game.resume, false);
 
// Actions
document.getElementById("left").addEventListener("mousedown", thrower.pressLeft, false);
document.getElementById("left").addEventListener("mouseup", thrower.releaseLeft, false);
document.getElementById("right").addEventListener("mousedown", thrower.pressRight, false);
document.getElementById("right").addEventListener("mouseup", thrower.releaseRight, false);
document.getElementById("throw").addEventListener("click", thrower.throwCowpie, false);
document.addEventListener("keydown", keyPressed, false);
document.addEventListener("keyup", keyReleased, false);
 
var canFire = true;
function keyPressed(e) {
  switch(e.keyCode) {
    case 39: case 68: // Right arrow and D
      thrower.pressRight();
    break;
    case 37: case 65: // Left arrow and A
      thrower.pressLeft();
    break;
    case 38: case 87: // Up arrow and W
      if(canFire) {
        canFire = false;
        thrower.throwCowpie();
      }
    break;
  }
}
 
function keyReleased(e) {
  switch(e.keyCode) {
    case 39: case 68: // Right arrow and D
      thrower.releaseRight();
    break;
    case 37: case 65: // Left arrow and A
      thrower.releaseLeft();
    break;
    case 38: case 87: // Up arrow and W
      canFire = true;
    break;
  }
}
 
/* Begin the game */
// window.addEventListener("load", game.start, false);  // Use  function setup()  instead .
 
} // function setup()  Wrap the entire logic section in a function and set a window load event to call 
 
/*************/
/** Objects **/
/*************/
 

There seems to be no way for script to get to game.start() .

So what I did was to insert "game.start()"

Here:

}
/* Begin the game */
// window.addEventListener("load", game.start, false); // Use function setup() instead .
game.start() ;
} // function setup() Wrap the entire logic section in a function and set a window load event to call
/*************/
/** Objects **/
/*************/
Then it runs for all sounds and all images EXCEPT cowpies .
Thanks
Edited by vmars316
Link to comment
Share on other sites

I know your are , Thank you !

 

(Although , from some of your comments ,

I was thinking that you thought I was unteachable .)

 

Yes , please do 'hang in there' because I have some questions about your code .

 

Originally Ready to start at "onload" .

 

With changes , at the end of 'setup function' .

 

But when I put game.start there ,

images disappear .

Edited by vmars316
Link to comment
Share on other sites

This whole POST is just a side note :

I do want to understand your code , and I want you to know that I am not just sitting back and waiting for answers . But I am working at solutions .

Ans I did come up with a work around , its ugly , but it works with your original code .

 

I was unable to get working

window.location.href

and

window.open()

triggered by a Button .

 

But I did notice that for Browser 'Back and Forward' Buttons game restarts fine .

 

So on a "Play Again !" Button click :

code opens up a new webpage called "RestartGame.html" .

which runs this code:

<script type='text/javascript'>
function goBack() {
  setTimeout(function() {
    window.history.back();
//    window.location.href = "http://vmars.us/javascript/GameObject/Foxy.Mod-w3schools.invisionzone-vmFIX-Web.html";
  }, 1000);
  }
</script>
 

Here: http://vmars.us/javascript/GameObject/Restart-FoxyModGame.html

and here: http://vmars.us/javascript/GameObject/Foxy.Mod-w3schools.invisionzone-vmFIX-Web.html

 

Thanks

Edited by vmars316
Link to comment
Share on other sites

You don't need to load the page again to start the game over.

 

Just give the game a reset() method which sets all the relevant values to their initial state. The method should:

  • Set scores to zero
  • Empty the cowpies array
  • Set all the target isGood properties to false

 

There's an easy way to reload the page if that's really the route you want to take to solve this problem. Use the location.reload() method: http://www.w3schools.com/jsref/met_loc_reload.asp

Link to comment
Share on other sites

Thanks

Yes , I'd rather learn

 


Just give the game a reset() method which sets all the relevant values to their initial state. The method should:
Set scores to zero
Empty the cowpies array
Set all the target isGood properties to false

 

Ok , I'll work on this . Thanks

 

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...