vmars316
-
Posts
480 -
Joined
-
Last visited
Content Type
Profiles
Forums
Events
Posts posted by vmars316
-
-
Thanks ,I would like to understand why the self.sprites = {is there . And what is the name of this type of "self.sprites = {" structure .<img id="cowpie" src="sprites/cowpie.png">//game.sprites.cowpie = document.getElementById("cowpie");//// HTML elementsself.sprites = {background : null,manufacturer : null,cowpie : null};//// Create a cowpieself.createCowpie = function(x, y) {var cowpie = new Cowpie(self.sprites.cowpie, x, y);cowpie.game = this;cowpies.push(cowpie);};Thanks
-
That's the HTML element in which the score is displayed.
Do you know what getElementById() is?
Yes I do .
But why does 'document.getElementById("totalScore")' return
'<td style="width: 18%"> totalScore </td>'instead of the value of 'document.getElementById("totalScore")' ?
And in general what is the purpose of , what is it actually doing:
game.scores.totalScore = document.getElementById("totalScore"); ?
-
on the way to: reset()
I don't understand the purpose of
// Scoresgame.scores.totalScore = document.getElementById("totalScore");console.log(document.getElementById("totalScore"));console.log(game.scores.totalScore);It looks like document.getElementById("totalScore") returns:<td style="width: 18%"> totalScore </td>?What is the purpose of that?Thanks -
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 zeroEmpty the cowpies arraySet all the target isGood properties to falseOk , I'll work on this . Thanks
-
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
-
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 .
-
Where is game.start() called? If you don't call that method the game will not work.
Where should I put game.start() ?
Thanks
-
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 -
-
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 sayingand I will review all my requirements above & add to as needed .Side note: none of the requirements you mentioned aboveare 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
-
<!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"];// SoundsGame.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"), // 0document.getElementById("lie02"), // 1] ; // future version will have 9 images to load// Movable objectsGame.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 rightvar 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); } // Throwerthis.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 timevar self = this;this.idTag = 'cowpie';this.idActive = true ;this.index = 0;this.x = thrower.x; // cowpie will always launch from the same coordinates as Throwerthis.y = thrower.y; // to simulate that Cowpie is being thrown by Throwerthis.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 soundif(this.x > Game.canvas.width - 2) {this.directionX = -1; // If sprite out of bounds occurs change directionthis.x = Game.canvas.width - 2;this.tripsCnt++; // totalTrips++;}if(this.x < -64 ) {this.directionX = 1; // If sprite out of bounds occurs change directionthis.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 CKif (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 objectsGame.hitTest = function(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;} // endof Game.hitTest = function// Starts up the gameGame.start = function() {// Start by playing the cheering soundGame.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 LOOPif (lastTimestamp == 0) {lastTimestamp = timestamp;}Game.context.clearRect(0, 0, Game.canvas.width, Game.canvas.height);thrower.draw();updateScores ();// Loop through cowpie objects and update themvar 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.updateif (lie02.visible) { lie02.update(); }if(thrower.moveMe) { thrower.update(); thrower.draw(); }lastTimestamp = timestamp;gid = requestAnimationFrame(Game.gameLoop);} // Game.gameLoop = function()///* Methods */// Play a soundGame.playSound = function(sound) {sound.play();} // endof Game.playSound = function// create cowpiesGame.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 cowpiesGame.destroyCowpie = function(cowpie) {// Play soundGame.playSound(Game.sounds.splat);// Remove from cowpiesvar 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.widthdocument.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 upArrowGame.createCowpie();totalShots ++;} // Endof shoot = W or upArrow} // endof function keyDownHandler//function keyUpHandler(e) {if(e.keyCode == 39 || event.keyCode == 68) { // move = rightArrow or DrightPressed = false ;thrower.moveMe = false ;// thrower.x = thrower.x + 4;// thrower.draw();}else if(e.keyCode == 37 || event.keyCode == 65) { // move = leftArrow or AleftPressed = 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>
-
-
Oops , try again:
-
Ah , back at it ;
Reminder.. Code works fine on desktop browser , but hangs on phone .
Here is my more readable code :
Thanks
-
Got it , Thanks
-
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, {)
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 theUncaught SyntaxError: Unexpected token {on this:
[code]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;} //[/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 -
<!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 drawingGame.canvas = document.getElementById("canvas");Game.graphics = Game.canvas.getContext("2d");// SoundsGame.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 objectsGame.cowpies = [];Game.thrower = new Thrower(document.getElementById("thrower"), 0, 0);Game.target = new Target(document.getElementById("lie02"), 128, 24)/* Methods */// Play a soundGame.playSound = function(sound) {sound.play();}// 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;} */// Create or detroy cowpiesGame.createCowpie = function() {Game.cowpies.push(new Cowpie());}Game.destroyCowpie = function(cowpie) {// Play soundGame.playSound(Game.sounds.splat);// Remove from cowpiesvar 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 gameGame.start = function() {// Start by playing the cheering soundplaySound(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 loopGame.gameLoop = function() {// Loop through objects and update themvar 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 everythingcontext.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 requirementsthis.update = function() {}// Draw the spritethis.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 requirementsthis.update = function() {}// Draw the spritethis.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 requirementsthis.update = function() {}// Draw the spritethis.draw = function() {Game.context.drawImage(this.sprite, this.x, this.y, this.width, this.height);}}</script></body></html>
-
Ok, I have got it stripped down , and no errors:
-
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 cowpiesGame.createCowpie = function() {cowpies.push(new Cowpie());//}Last js statement": Uncaught SyntaxError: Unexpected end of input// Draw the spritethis.draw = function() {Game.context.drawImage(this.sprite, this.x, this.y, this.width, this.height);} -
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 incompleteYes I realize that . Isn't the diagram that you gave me , though incomplete , program structure ?
Or do you mean something else ?
Thanks
-
you might want to try reposting and using the formatting tags correctly so it's easier to read the code. The syntax highlighting will probably make a huge difference in seeing where the issue are. Are you using any sort of editor for this work? Most editors / IDEs will have syntax highlighting and often highlight inline when there is an obvious syntax error.
Yes , I try it every time . Most often it doesn't work . I use Notepad++ .
1) copy the code i want to paste.
2) then click on the <> lable .3) select html
4) paste in code
5) click save
Code shows up as colored .
Then I click 'save'.
Code doesn't show up , just a small empty colored box .
What am I doing wrong ?
Thanks
-
Hello & Thanks ;I am trying to get a clean compile on the Diagram ,I am getting the following errorsand I can't figure out what the prob is ,Pls help . The Diagram code is at bottom .: Uncaught SyntaxError: Unexpected token {// Detect a rectangular collision between two objectsGame.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;}: Uncaught SyntaxError: Unexpected token {// Create or destroy cowpiesGame.createCowpie = function() {cowpies.push(new Cowpie());//}: Uncaught SyntaxError: Unexpected token {Game.end() {// Stop the Game loop, this code depends on what kind of loop you're using.}Last js statement": Uncaught SyntaxError: Unexpected end of input// Draw the spritethis.draw = function() {Game.context.drawImage(this.sprite, this.x, this.y, this.width, this.height);}
<!DOCTYPE html><html>-<head><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta charset="utf-8" /><title>Debug Hillary Only</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: #992D2D; height: 24px; width: 800px; border: none; }button {font-size: 16px;}</style></head><body onload="Game.start()" ><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><button onclick="touchUpArrow()" ontouchstart="touchUpArrow()">----Throw----</button><br><br><button onclick="myGameArea.pause()" ontouchstart="myGameArea.pause()" >Pause</button>__ <button onclick="myGameArea.play()" ontouchstart="myGameArea.play()" >Play</button>__ <button onclick="clearIt()" ontouchstart="clearIt()">Clear</button>__ <button onclick="quitIt()" ontouchstart="quitIt()">Quit</button></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'>/*****************//** Game object **//*****************//*****************//** Game object **//*****************/var Game = {}/* Properties */// For drawingGame.canvas = document.getElementById("canvas");Game.graphics = Game.canvas.getContext("2d");// SoundsGame.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 objectsGame.cowpies = [];Game.thrower = new Thrower(document.getElementById("thrower"), 0, 0);Game.target = new Target(document.getElementById("lie02"), 128, 24)/* Methods */// Play a soundGame.playSound = function(sound) {sound.play();}// Detect a rectangular collision between two objectsGame.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;}// Create or detroy cowpiesGame.createCowpie = function() {cowpies.push(new Cowpie());}Game.destroyCowpie = function(cowpie) {// Play soundGame.playSound(Game.sounds.splat);// Remove from cowpiesvar 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 gameGame.start = function() {// Start by playing the cheering soundplaySound(Game.sounds.cheering);// Then begin the game loop, this code depends on what kind of loop you're using}// Ends the gameGame.end() {// Stop the game loop, this code depends on what kind of loop you're using.}// This is the game loopGame.gameLoop = function() {// Loop through objects and update themvar 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 everythingcontext.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 requirementsthis.update = function() {}// Draw the spritethis.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 requirementsthis.update = function() {}// Draw the spritethis.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 requirementsthis.update = function() {}// Draw the spritethis.draw = function() {Game.context.drawImage(this.sprite, this.x, this.y, this.width, this.height);}}</script></body></html> -
Thanks ,
I am getting an "GameObject-Copy.html:163 Uncaught SyntaxError: Unexpected token {"
on this:
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;}This syntax is new to me , is return supposed to return 'true or false' ?
Thanks
-
<!DOCTYPE html><html>-<head><meta name="viewport" content="width=device-width, initial-scale=1.0"/><meta charset="utf-8" /><title>Debug Hillary Only</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: 600px; border: none; }#buttonsArea { color: #E1E1E1; background-color: #732222; width: 600px; border: none; }button {font-size: 16px;}</style></head><body onload="Game.start()" onresize="onScrnResize()"><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="myGameArea.pause()" ontouchstart="myGameArea.pause()" >Pause</button>__ <button onclick="myGameArea.play()" ontouchstart="myGameArea.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></body></html>
Need help with .js game on phone
in JavaScript
Posted