Jump to content

Need help with .js game on phone


vmars316

Recommended Posts

Hello & Thanks :

The full game is here: 1) http://vmars.us/javascript/BenghaziGame.html 550 statements.

I have stripped it down to 450 statements here: 2) http://vmars.us/javascript/Hillary-Only-Phone.html .

I stripped it down to debug "why it doesn't run properly on a phone" .

Both run fine in PC browser .

 

1) runs on phone , but images get screwed up (on collisions) , often appearing on screen bottom .

Game uses interval code , not requestAnnmation .

2) runs on phone , but stops dead on collisions .

Game uses requestAnnmation code .

 

Any ideas what I am doing wrong ?

Thanks

 

Link to comment
Share on other sites

  • Replies 73
  • Created
  • Last Reply

Top Posters In This Topic


 

<!DOCTYPE html>

<html>

-<head>

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

<meta charset="utf-8" />

<title>Hillary Benghazi</title>

http://liesandcowpies.com/javascript/

-->

<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: 14px;}

</style>

</head>

<body onload="startGame()" onresize="onScrnResize()">

<div>

<table align="center">

<tr>

<td width="12%"> Oops! Hits</td> <td id="Oop######z" width="5%"> </td>

<td width="8%"></td>

<td width="10%"> Good Hits</td> <td id="GoodHitz" width="5%"> </td>

<td width="8%"></td>

</tr>

<tr>

<td width="10%">Screen Size </td> <td id="ScreenSize" 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="800" height="550" style="background-color:#992D2D"></canvas>

<br>

<button onclick="myGameArea.pause()" ontouchstart="myGameArea.pause()" >Pause</button>

<button onclick="myGameArea.play()" ontouchstart="myGameArea.play()" >Play</button>

___

<button onmousedown="touchLeftArrow()" onmouseup="touchEndLeft()" ontouchstart="touchLeftArrow()" ontouchend="touchEndLeft()">MoveLeft</button>

_

<button onclick="touchUpArrow()" ontouchstart="touchUpArrow()">Throw</button>

_

<button onmousedown="touchRightArrow()" onmouseup="touchEndRight()" ontouchstart="touchRightArrow()" ontouchend="touchEndRight()">MoveRight</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="tru02" src="sprites/hillaryThrow-a.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" />

<img id="bgCompound" src="sprites/bgCompound.jpeg" width="320" height="191" />

<img id="manufacturer" src="sprites/manufacturer.png" width="180" height="100" />

</div>

<script type='text/javascript'>

//

var lastTimestamp = 0;

var oneTraceLine = ""; var traceYESorNO = false;

var visible = true;

var interval = 0; var tripsMax=0;

var thisIdTag = ""; var resetSpeedX = 2; var newestPie =0;

var idTag = "lie02"; var idTagTh = "thrower";

var thisPie = 0;

var tripsCnt=0; var directionX=1 ; var addit = 0; var thisCowpieActive = false;

var countUpdateGameArea = 0;

var oop######s = 0; var goodHits = 0; var totalShots = 0; var screenWidth = 0; var screenHeight=0;

var oop######sA; var goodHitsA; var totalShotsA; var screenSizeA; var screenWidthA; var screenHeightA;

var yestru = true ; var yeslie = true ; var playThis = ""; var pausePlayCnt=0;

var allImgsCnt = 0; var totalTrips = 0; var imWinningMsg = false;

var My_audio_Urls = ["sounds/CowMooSplat.mp3",

"sounds/GoodBye-Female.mp3","sounds/cheeringCrowd.mp3","sounds/oops.mp3"];

var cached_Audio_files = [];

 

canvas = document.getElementById("canvas"); // get the canvas

ctx = canvas.getContext('2d'); // create canvas Context;

 

var allImgs = [ document.getElementById("thrower"), // 0

document.getElementById("lie02"), // 1

document.getElementById("tru02"), // 2

document.getElementById("bgCompound"), // 3

document.getElementById("manufacturer") // 4

] ;

//

var cowpies = [];

var cowpieImg = document.getElementById("cowpie");

//

var Thrower = function () {

var self = this;

this.idTag = 'thrower';

this.x = (canvas.width / 2) -30;

this.y = canvas.height - 64;

this.width= 64;

this.height = 64;

this.speedX = 4 ;

this.speedY = 0;

this.visible = true;

this.directionX = 9;

this.moveMe ;

this.update = function() {

self.speedX = resetSpeedX;

if (self.x > canvas.width -50 ) { self.x = 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';

thrower.x ; // = 0;

thrower.y ; // = canvas.height - 64;

thrower.width ; // = 64;

thrower.height ; // = 64;

thrower.speedX ; // = 1;

thrower.speedY ; // = 0;

thrower.visible ; // = true ;

thrower.directionX ; // = 1;

thrower.moveMe = false ;

//

var Cowpie = function () {

var self = this;

this.idTag = 'cowpie';

this.idActive = true ;

this.x = thrower.x;

this.y = thrower.y;

// this.y = 69; // for testing only

this.width= 32;

this.height = 32;

this.speedX = 0;

this.speedY = -3;

this.visible = true;

this.directionY = -1;

// this.moveMe = false;

} // var cowpie

//

// workSpace:

 

 

// Endof workSpace

//

function startGame() {

preload_audio_files(My_audio_Urls);

playsIt = My_audio_Urls.indexOf("sounds/cheeringCrowd.mp3");

playAudio(cached_Audio_files[playsIt]);

alert( '<--- Arrow = move Left .\n' + '---> Arrow = move Right .\n' + ' Up Arrow = Throw Cowpie \n ' + '\n Best Screen size: Width = >840 , Height = > 640 .\n' +

'\n Click anywhere on screen to ACTIVATE BUTTONS .\n (Buttons coming soon...)');

myGameArea.start();

}

//

function TargetImages() {

var self = this ;

this.idTag = "";

this.x = 0;

this.y = 4;

this.width= 64;

this.height = 64;

this.speedX = 4;

this.speedY = 0;

this.tripsCnt =0;

this.tripsMax=0;

this.visible = true ;

this.directionX = 1;

this.update = function() {

 

ctx.drawImage(allImgs[allImgsCnt], this.x, this.y, this.width, this.height);

this.x = this.x + (this.speedX * this.directionX); // always = +1 or -1

//

idTag = this.idTag;

//

if(this.x > canvas.width - 2) {this.directionX = -1; // change direction

this.x = canvas.width - 2;

this.tripsCnt++; totalTrips++;

}

//

if(this.x < -64 ) {this.directionX = 1; // change direction

this.x = 0;

this.tripsCnt++; totalTrips++;

}

//

if(this.tripsCnt > this.tripsMax) { // time to change sprites

if(this.idTag == "lie02") {this.speedX = resetSpeedX; lie02.tripsCnt =0; this.visible=false ;

tru02.speedX=resetSpeedX ; tru02.visible=true ; // idTag = "lie02";

}

if(this.idTag == "tru02") {this.speedX = resetSpeedX; tru02.tripsCnt =0; this.visible=false ;

lie02.speedX=resetSpeedX ; lie02.visible=true ; // idTag = "lie01";

}

}

for (var i = cowpies.length - 1; i >= 0; i--) {

thisPie = i;

if (cowpies[thisPie].idActive) {

if(self.visible) { // yes , do collision CK

if (cowpies[thisPie].y < this.y + this.height && cowpies[thisPie].y + cowpies[thisPie].height > this.y)

{ if (cowpies[thisPie].x < this.x + this.width && cowpies[thisPie].x + cowpies[thisPie].width > this.x )

{ // alert("YES , a collision has occurred");

thisIdTag = this.idTag ; var findsIt = 0 ; var playsIt = 0 ;

var yestru = thisIdTag.startsWith("tru"); // if thisIdTag starts with "tru" then set yestru to "true"

var yeslie = thisIdTag.startsWith("lie");

if(yestru) { switch(this.idTag) {

case "tru02": tru02.visible = false ; tru02.tripsCnt =0 ; tru02.x = -60; this.speedX = 0; oop######s += 1;

lie02.visible=true ; lie02.tripsCnt =0 ; lie02.x = 0 ; lie02.speedX = resetSpeedX; break;

}

} // if(yestru) { switch(this.idTag)

if(yeslie){ switch(this.idTag) {

case "lie02": lie02.visible=false ; lie02.tripsCnt =0 ; lie02.x = -60; this.speedX = 0; goodHits += 1;

tru02.visible=true ; tru02.tripsCnt =0 ; tru02.x = 0; tru02.speedX = 1; break ;

}

}

if (thisIdTag == "lie02") {playsIt = My_audio_Urls.indexOf("sounds/CowMooSplat.mp3"); }

if (thisIdTag == "tru02") {playsIt = My_audio_Urls.indexOf("sounds/oops.mp3"); }

playAudio(cached_Audio_files[playsIt]);

 

cowpies.splice(thisPie,1); //alert("cowpies.length= "+ cowpies.length);

}

}

}

}

} // endof or (var i = cowpies.length - 1

} // endof TargetImages this.update ;

} // endof function TargetImages()

//

lie02 = new TargetImages();

lie02.idTag = "lie02";

lie02.x = 128;

lie02.y = 24;

lie02.visible = false ;

lie02.tripsCnt =0;

lie02.tripsMax=2;

//

tru02 = new TargetImages()

tru02.idTag = "tru02";

tru02.x = 0;

tru02.y = 86;

tru02.visible = true ;

tru02.tripsCnt =0;

tru02.tripsMax=2;

//

function updateGameArea(timestamp) {

if (lastTimestamp == 0) {

lastTimestamp = timestamp;

}

 

myGameArea.clear();

updateScores ();

imWinningMsg = false;

ctx.drawImage(allImgs[3], 0, canvas.height - 195, 320, 191); // show bgCompound

ctx.drawImage(allImgs[4], canvas.width -180, canvas.height - 104, 180, 100); // show manufacturer

allImgsCnt = 0; drawThrower();

allImgsCnt = 1; if(lie02.visible) { lie02.speedX = resetSpeedX; lie02.update(); }

allImgsCnt = 2; if(tru02.visible) { tru02.speedX = resetSpeedX; tru02.update(); }

allImgsCnt = 0; if(thrower.moveMe) { thrower.update(); drawThrower(); }

if(cowpies.length > 0){

for (var i = cowpies.length - 1; i >= 0; i--) {

thisPie = i;

cowpies[thisPie].y = cowpies[thisPie].y -3 ;

ctx.drawImage(cowpieImg, cowpies[thisPie].x, cowpies[thisPie].y, cowpies[thisPie].width, cowpies[thisPie].height);

if(cowpies[thisPie].y < 1) { cowpies[thisPie].idActive = false ; cowpies.splice(thisPie,1); } // out of bounds

}

}

 

lastTimestamp = timestamp;

gid = requestAnimationFrame(updateGameArea);

} // End OF function updateGameArea()

//

function drawThrower() {

ctx.drawImage(allImgs[allImgsCnt], thrower.x, thrower.y, thrower.width, thrower.height);

}

//

var myGameArea = {

start : function() {

gid = requestAnimationFrame(updateGameArea);

},

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(updateGameArea);

}

}

} // endof var myGameArea = {}

//

function clearIt() {

oop######s = 0; goodHits = 0; totalShots = 0;

// var num = 15; var n = num.toString();

}

//

function updateScores () {

oop######sA = oop######s.toString();

document.getElementById('Oop######z').innerHTML = oop######sA;

goodHitsA = goodHits.toString();

document.getElementById('GoodHitz').innerHTML = goodHitsA;

totalShotsA = totalShots.toString();

document.getElementById('TotalShotz').innerHTML = totalShotsA;

}

//

document.addEventListener("keydown", keyDownHandler, false);

document.addEventListener("keyup", keyUpHandler, false);

/* document.addEventListener( 'keyup', function( e ) {

console.log( 'Keyup event' );

console.log( e.keyCode );

} );

*/

function keyDownHandler(e) {

// alert(" 1 cowpies.length - 1 " + newestPie);

if(e.keyCode == 39 || event.keyCode == 68) { // move right D or --->

// alert("RIGHT.thrower.directionX = 9;");

thrower.directionX = 1;

thrower.moveMe = true ;

if (thrower.x > canvas.width -40) { thrower.moveMe = false ; }

}

if(e.keyCode == 37 || event.keyCode == 65) { // move left A or <---

// alert("LEFT.thrower.directionX = -9;");

thrower.directionX = -1;

thrower.moveMe = true ;

if (thrower.x < 3) { thrower.moveMe = false ; }

}

if(e.keyCode == 87 || event.keyCode == 38 ) { // shoot = W or upArrow

cowpies.push(cowpie = new Cowpie); // add cowpie in last position

newestPie = 0;

newestPie = cowpies.length - 1; // put last pie created position into newestPie

ctx.drawImage(cowpieImg, cowpies[newestPie].x, cowpies[newestPie].y, cowpies[newestPie].width, cowpies[newestPie].height);

totalShots ++;

} // Endof shoot = W or upArrow

} // endof unction keyDownHandler

//

function keyUpHandler(e) {

if(e.keyCode == 39 || event.keyCode == 68) {

rightPressed = false ;

thrower.moveMe = false ;

drawThrower();

}

else if(e.keyCode == 37 || event.keyCode == 65) {

leftPressed = false;

thrower.moveMe = false ;

drawThrower();

}

}

function mouseMoveHandler(e) {

// var relativeX = e.clientX - canvas.offsetLeft;

// if(relativeX > 0 && relativeX < canvas.width) {

// paddleX = relativeX - paddleWidth/2;

// }

}

//

function touchUpArrow() {

cowpies.push(cowpie = new Cowpie); // add cowpie in last position

newestPie = 0;

newestPie = cowpies.length - 1; // put last pie created position into newestPie

ctx.drawImage(cowpieImg, cowpies[newestPie].x, cowpies[newestPie].y, cowpies[newestPie].width, cowpies[newestPie].height);

totalShots ++;

}

//

function touchLeftArrow() {

//alert("function touchLeftArrow() {");

thrower.directionX = -1;

thrower.moveMe = true ;

if (thrower.x < 3) { thrower.moveMe = false ; }

}

//

function touchEndLeft() {

//alert("function touchEndLeft() {");

leftPressed = false;

thrower.moveMe = false ;

drawThrower();

}

//

function touchRightArrow() {

//alert("function touchRightArrow() {");

thrower.directionX = 1;

thrower.moveMe = true ;

if (thrower.x > canvas.width -40) { thrower.moveMe = false ; }

}

//

function touchEndRight() {

//alert("function touchEndRight() {");

rightPressed = false ;

thrower.moveMe = false ;

drawThrower();

}

//

function quitIt() {

playsIt = My_audio_Urls.indexOf("sounds/GoodBye-Female.mp3");

playAudio(cached_Audio_files[playsIt]);

setTimeout(function() {

window.location = "http://liesandcowpie...e-Tutorial.html"; }, 1000);

}

//

function preload_audio_files(arr_files)

{

for (var i = 0; i < arr_files.length; i++)

{

cached_Audio_files = new Audio();

cached_Audio_files.src = My_audio_Urls;

cached_Audio_files.preload = "auto";

}

}

// preload_audio_files(My_audio_Urls);

 

function playAudio(playThis) {

playThis.play();

}

function showWinningMsg() {

imWinningMsg = true;

// alert('showWinningMsg()');

ctx.drawImage(allImgs[6], 250, 325, 129, 60);

}

function onScrnResize(){

var w = window.innerWidth; var h = window.innerHeight;

// alert("function onScrnResize()"); window.innerWidth canvas.width

document.getElementById("ScreenSize").innerHTML =

// screen.width + " x " + screen.height ;

// w + " x " + h ;

canvas.width + " x " + canvas.height ;

}

 

function ForceUpArrow(){

// if( countUpdateGameArea == 10){

newestPie= 0 ;

cowpies.push(cowpie = new Cowpie); // add cowpie in last position

cowpies.speedY = 12;

newestPie = cowpies.length - 1; // put last pie created position into newestPie

ctx.drawImage(cowpieImg, cowpies[newestPie].x, cowpies[newestPie].y, cowpies[newestPie].width, cowpies[newestPie].height);

// alert("ForcedUpArrow: Should see a cowpie now newestPie= " + newestPie);

// }

}

//

</script>

</body>

</html>

 

Link to comment
Share on other sites

Hello & Thanks :

I was able to strip it down even more:

The full game is here: 1) http://vmars.us/javascript/BenghaziGame.html 550 statements.

I have stripped it down to 330 statements here: 2) http://vmars.us/javascript/_StripHillary-Only.html .

I stripped it down to debug "why it doesn't run properly on a phone" .

Both run fine in PC browser .

 

1) runs on phone , but images get screwed up (on collisions) , often appearing on screen bottom .

Game uses interval code , not requestAnnmation .

2) runs on phone , but stops dead on collisions .

Game uses requestAnnmation code .

 

Any ideas what I am doing wrong ?

Thanks

 


Having probs with Code tag (see below for new code).

Thanks

Edited by vmars316
Link to comment
Share on other sites

Still no go for Code tag , so i'll just paste code below:

<!DOCTYPE html>
<html>
-<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta charset="utf-8" />
<title>Hillary Benghazi</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: 14px;}
</style>
</head>
<body onload="startGame()" 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>
<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'>
//
var lastTimestamp = 0;
var oneTraceLine = ""; var traceYESorNO = false;
var visible = true;
var interval = 0; var tripsMax=0;
var thisIdTag = ""; var resetSpeedX = 2; var newestPie =0;
var idTag = "lie02"; var idTagTh = "thrower";
var thisPie = 0;
var tripsCnt=0; var directionX=1 ; var addit = 0; var thisCowpieActive = false;
var countUpdateGameArea = 0;
var oops = 0; var goodHits = 0; var totalShots = 0; var screenWidth = 0; var screenHeight=0;
var oopsA; var goodHitsA; var totalShotsA; var screenSizeA; var screenWidthA; var screenHeightA;
var yestru = true ; var yeslie = true ; var playThis = ""; var pausePlayCnt=0;
var allImgsCnt = 0; var totalTrips = 0; var imWinningMsg = false;
var My_audio_Urls = ["sounds/CowMooSplat.mp3",
"sounds/GoodBye-Female.mp3","sounds/cheeringCrowd.mp3","sounds/oops.mp3"];
var cached_Audio_files = [];
canvas = document.getElementById("canvas"); // get the canvas
ctx = canvas.getContext('2d'); // create canvas Context;
var allImgs = [ document.getElementById("thrower"), // 0
document.getElementById("lie02"), // 1
] ;
//
var cowpies = [];
var cowpieImg = document.getElementById("cowpie");
//
var Thrower = function () {
var self = this;
this.idTag = 'thrower';
this.x = (canvas.width / 2) -30;
this.y = canvas.height - 64;
this.width= 64;
this.height = 64;
this.speedX = 4 ;
this.speedY = 0;
this.visible = true;
this.directionX = 9;
this.moveMe ;
this.update = function() {
self.speedX = resetSpeedX;
if (self.x > canvas.width -50 ) { self.x = 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';
thrower.x ; // = 0;
thrower.y ; // = canvas.height - 64;
thrower.width ; // = 64;
thrower.height ; // = 64;
thrower.speedX ; // = 1;
thrower.speedY ; // = 0;
thrower.visible ; // = true ;
thrower.directionX ; // = 1;
thrower.moveMe = false ;
//
var Cowpie = function () {
var self = this;
this.idTag = 'cowpie';
this.idActive = true ;
this.x = thrower.x;
this.y = thrower.y;
this.width= 32;
this.height = 32;
this.speedX = 0;
this.speedY = -3;
this.visible = true;
this.directionY = -1;
// this.moveMe = false;
} // var cowpie
//
function startGame() {
preload_audio_files(My_audio_Urls);
playsIt = My_audio_Urls.indexOf("sounds/cheeringCrowd.mp3");
playAudio(cached_Audio_files[playsIt]);
myGameArea.start();
}
//
function TargetImages() {
var self = this ;
this.idTag = "";
this.x = 0;
this.y = 4;
this.width= 64;
this.height = 64;
this.speedX = 4;
this.speedY = 0;
this.tripsCnt =0;
this.tripsMax=0;
this.visible = true ;
this.directionX = 1;
this.update = function() {
ctx.drawImage(allImgs[allImgsCnt], this.x, this.y, this.width, this.height);
this.x = this.x + (this.speedX * this.directionX); // always = +1 or -1
//
idTag = this.idTag;
//
if(this.x > canvas.width - 2) {this.directionX = -1; // change direction
this.x = canvas.width - 2;
this.tripsCnt++; totalTrips++;
}
//
if(this.x < -64 ) {this.directionX = 1; // change direction
this.x = 0;
this.tripsCnt++; totalTrips++;
}
//
for (var i = cowpies.length - 1; i >= 0; i--) {
thisPie = i;
if (cowpies[thisPie].idActive) {
if(self.visible) { // yes , do collision CK
if (cowpies[thisPie].y < this.y + this.height && cowpies[thisPie].y + cowpies[thisPie].height > this.y)
{ if (cowpies[thisPie].x < this.x + this.width && cowpies[thisPie].x + cowpies[thisPie].width > this.x )
{ // alert("YES , a collision has occurred");
thisIdTag = this.idTag ; var findsIt = 0 ; var playsIt = 0 ;
var yeslie = thisIdTag.startsWith("lie");
if(yeslie){ switch(this.idTag) {
case "lie02": lie02.visible=true ; goodHits += 1;
// lie02.tripsCnt =0 ; lie02.x = -60; this.speedX = 0;
// tru02.visible=true ; tru02.tripsCnt =0 ; tru02.x = 0; tru02.speedX = 1; break ;
}
}
if (thisIdTag == "lie02") {playsIt = My_audio_Urls.indexOf("sounds/CowMooSplat.mp3"); }
playAudio(cached_Audio_files[playsIt]);
cowpies.splice(thisPie,1); //alert("cowpies.length= "+ cowpies.length);
}
}
}
}
} // endof or (var i = cowpies.length - 1
} // endof TargetImages this.update ;
} // endof function TargetImages()
//
lie02 = new TargetImages();
lie02.idTag = "lie02";
lie02.x = 128;
lie02.y = 24;
lie02.visible = true ;
lie02.tripsCnt =0;
lie02.tripsMax=2;
function updateGameArea(timestamp) {
if (lastTimestamp == 0) {
lastTimestamp = timestamp;
}
myGameArea.clear();
updateScores ();
imWinningMsg = false;
allImgsCnt = 0; drawThrower();
allImgsCnt = 1; if(lie02.visible) { lie02.speedX = resetSpeedX; lie02.update(); }
allImgsCnt = 0; if(thrower.moveMe) { thrower.update(); drawThrower(); }
if(cowpies.length > 0){
for (var i = cowpies.length - 1; i >= 0; i--) {
thisPie = i;
cowpies[thisPie].y = cowpies[thisPie].y -3 ;
ctx.drawImage(cowpieImg, cowpies[thisPie].x, cowpies[thisPie].y, cowpies[thisPie].width, cowpies[thisPie].height);
if(cowpies[thisPie].y < 1) { cowpies[thisPie].idActive = false ; cowpies.splice(thisPie,1); } // out of bounds
}
}
lastTimestamp = timestamp;
gid = requestAnimationFrame(updateGameArea);
} // End OF function updateGameArea()
//
function drawThrower() {
ctx.drawImage(allImgs[allImgsCnt], thrower.x, thrower.y, thrower.width, thrower.height);
}
//
var myGameArea = {
start : function() {
gid = requestAnimationFrame(updateGameArea);
},
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(updateGameArea);
}
}
} // endof var myGameArea = {}
//
function clearIt() {
oops = 0; goodHits = 0; totalShots = 0;
// var num = 15; var n = num.toString();
}
//
function updateScores () {
goodHitsA = goodHits.toString();
document.getElementById('GoodHitz').innerHTML = goodHitsA;
totalShotsA = totalShots.toString();
document.getElementById('TotalShotz').innerHTML = totalShotsA;
}
//
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
// alert(" 1 cowpies.length - 1 " + newestPie);
if(e.keyCode == 87 || event.keyCode == 38 ) { // shoot = W or upArrow
cowpies.push(cowpie = new Cowpie); // add cowpie in last position
newestPie = 0;
newestPie = cowpies.length - 1; // put last pie created position into newestPie
ctx.drawImage(cowpieImg, cowpies[newestPie].x, cowpies[newestPie].y, cowpies[newestPie].width, cowpies[newestPie].height);
totalShots ++;
} // Endof shoot = W or upArrow
} // endof unction keyDownHandler
//
function keyUpHandler(e) {
if(e.keyCode == 39 || event.keyCode == 68) {
rightPressed = false ;
thrower.moveMe = false ;
drawThrower();
}
else if(e.keyCode == 37 || event.keyCode == 65) {
leftPressed = false;
thrower.moveMe = false ;
drawThrower();
}
}
//
function touchUpArrow() {
cowpies.push(cowpie = new Cowpie); // add cowpie in last position
newestPie = 0;
newestPie = cowpies.length - 1; // put last pie created position into newestPie
ctx.drawImage(cowpieImg, cowpies[newestPie].x, cowpies[newestPie].y, cowpies[newestPie].width, cowpies[newestPie].height);
totalShots ++;
}
//
function quitIt() {
playsIt = My_audio_Urls.indexOf("sounds/GoodBye-Female.mp3");
playAudio(cached_Audio_files[playsIt]);
}
//
function preload_audio_files(arr_files)
{
for (var i = 0; i < arr_files.length; i++)
{
cached_Audio_files = new Audio();
cached_Audio_files.src = My_audio_Urls;
cached_Audio_files.preload = "auto";
}
}
// preload_audio_files(My_audio_Urls);
function playAudio(playThis) {
playThis.play();
}
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 ;
}
</script>
</body>
</html>
Link to comment
Share on other sites

Did you spend any time designing this software before beginning the implementation phase?

 

I'd like to see the structure of your program, because it's really hard to tell what it's supposed to be from just the source code.

Link to comment
Share on other sites

Did you spend any time designing this software before beginning the implementation phase?

 

I'd like to see the structure of your program, because it's really hard to tell what it's supposed to be from just the source code.

Sorry to say "no" .

I am learning .js as I go .

Is there a predefined structure for a .js game ?

I am happy to put it into a more readable format .

Thanks

Link to comment
Share on other sites

There are two things you need to start off:

1. The requirements

2. The software design

 

The requirements would be a description of exactly how the game is supposed to look from a user's perspective, with all the details.

For the software design, it would be good enough to make a diagram of all the objects in the game, their properties and how they interact with each other.

Link to comment
Share on other sites

Hello & Thanks;

 

I usually do all this in my head , but I do see the benefits of writing it all down .
1. The requirements
The requirements would be a description of exactly how the game is supposed to look
from a user's perspective, with all the details :
Game canvas stage:
<canvas id="canvas" width="600" height="450" style="background-color:#992D2D"></canvas>
Top of page shows game info: screenSize , Good Hits , Total Shots .
Screen will show 3 visible sprites:
<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> ,
sprite lies02.png (the target) will be located at : lie02.x = 128; lie02.y = 24;
and will move back and forth on screen
sprite thrower.png will be stationary at location: this.x = (canvas.width / 2) -30; this.y = canvas.height - 64;
sprite cowpie.png (the projectile) will be located initially at same coordinates as thrower.png sprite
but will move vertically toward the target .
At bottom of screen will be 5 Buttons: line 1: "Throw", "Pause", line 2: "Play", "Clear Score" and "Quit" .
2. The software design
For the software design, it would be good enough to make a diagram of all the objects in the game,
their properties and how they interact with each other. (Sorry, I don't have any diagramming tools.)
The object of game is :
To hit Target with a cowpie , racking up as high a score as possible .
Game starts with playing "cheeringCrowd.mp3" .
and "lies02.png" starts its moving back and forth, across screen, behavior .
thrower.png , when user 'clicks or touches' the "Throw button", a new cowpie is created (cowpie.png)
and shoots toward target (lie02) , attempting to collide with Target .
Also, each time the Throw button is depressed, The "Total Shots" score is incremented by 1 .
If cowpie.png collides with lies02.png , "Good Hits" score is incremented by 1 ,
and sound file "CowMooSplat.mp3" is played . Game converts "lies02.png" for use as "lie02" .
Soundfiles are loaded into an array here:
var My_audio_Urls = ["sounds/CowMooSplat.mp3",
"sounds/GoodBye-Female.mp3","sounds/cheeringCrowd.mp3","sounds/oops.mp3"];
And souds are played here:
function playAudio(playThis) { playThis.play(); }
Sprites are loaded into an array here:
var allImgs = [ document.getElementById("thrower"), // 0
document.getElementById("lie02"), ]; // 1
cowpies.png are updated in an array here:
var cowpies = [];
Cowpies are created here:
function keyDownHandler(e) {
if(e.keyCode == 87 || event.keyCode == 38 ) { // shoot = W or upArrow
cowpies.push(cowpie = new Cowpie); // (pop) add cowpie in last position
Cowpies are removed here:
if (thisIdTag == "lie02") {playsIt = My_audio_Urls.indexOf("sounds/CowMooSplat.mp3"); }
playAudio(cached_Audio_files[playsIt]);
cowpies.splice(thisPie,1); //alert("cowpies.length= "+ cowpies.length);
and removed here:
if(cowpies.length > 0){
for (var i = cowpies.length - 1; i >= 0; i--) {
thisPie = i;
cowpies[thisPie].y = cowpies[thisPie].y -3 ;
ctx.drawImage(cowpieImg, cowpies[thisPie].x, cowpies[thisPie].y, cowpies[thisPie].width, cowpies[thisPie].height);
if(cowpies[thisPie].y < 1) { cowpies[thisPie].idActive = false ; cowpies.splice(thisPie,1); } // out of bounds
}
}
Collision detection occurs here:
for (var i = cowpies.length - 1; i >= 0; i--) {
thisPie = i;
if (cowpies[thisPie].idActive) {
if(self.visible) { // yes , do collision CK
if (cowpies[thisPie].y < this.y + this.height && cowpies[thisPie].y + cowpies[thisPie].height > this.y)
{ if (cowpies[thisPie].x < this.x + this.width && cowpies[thisPie].x + cowpies[thisPie].width > this.x )
{ // alert("YES , a collision has occurred");
thisIdTag = this.idTag ; var findsIt = 0 ; var playsIt = 0 ;
var yeslie = thisIdTag.startsWith("lie");
Hope this helps!
Edited by vmars316
Link to comment
Share on other sites

It seems you've put most of your requirements under the software design section, while you put part of the description of your current implementation in the requirements section. The requirements should be what somebody who knows nothing about programming would ask you to make.

 

This is going to take a lot of work. You need to reprogram the game with a proper structure. I'm going to go through your descriptions and help you with the design.

 

> Game starts with playing "cheeringCrowd.mp3" .
This sounds like you need an object called "Game" with a start() method. That start() method would play a sound.

 

> Soundfiles are loaded into an array here:

This could be an array belonging to the Game object

 

> And souds are played here:

You haven't described where the playThis parameter comes from, in your sounds array all you have are strings. You can either change the playAudio() method to accept strings a parameter or you can make the sounds array contain Audio objects.

 

> Sprites are loaded into an array here:

> cowpies.png are updated in an array here:

These arrays can also be a property of the Game object.

 

> Cowpies are created here:

> Cowpies are removed here:

createCowpie() can and destroyCowpie() can be methods of the Game object

 

> Collision detection occurs here:

A collision method could be made here.

 

 

There are still a lot of requirements missing:

  • You haven't described what the thrower and target are and what they do, I will need you to describe that.
  • You forgot to mention that some objects in the game are moving and haven't described how they move. For this current iteration I will give all objects that can move an update() method.

The game needs a game loop, there are two ways to do that: Fixed time loops are done with setInterval() and variable time loops are with requestAnimationFrame. With fixed time loops, you calculate physics based on frames, in variable-time loops you have to calculate the physics based on the time that has passed since the previous loop. You're going to have to decide which one you want to use, until then I can't show you the code for the game loop. In the game loop you should call the update() method of all the objects in the game, so we should add an array of movable objects to the game.

 

From my understanding you have a Cowpie object, a Thrower object and a Target. I will assume these have a position and a size, so at minimum they need x, y, width and height properties. Since they all can move I'll give them an update() method.

 

With your description so far I have created this structure. We can add more once you have refined the requirements:

/*****************/
/** 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() {
  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[i] == 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[i];
    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[i];
    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);
  }
}
Link to comment
Share on other sites

Here is an updated specs docs :

1. The [requirements]
The requirements would be a description of exactly how the game is supposed to look
from a user's perspective, with all the details .
The requirements should be what somebody who knows nothing about programming would ask you to make.
[Game canvas]
<canvas id="canvas" width="600" height="450" style="background-color:#992D2D"></canvas>
[Top of page] shows game scores: screenSize , Good Hits , Total Shots .
[sprite Movement] Game will have 2 moving sprites , and 1 stationary sprite , 3 sprites in total]
<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" />
[sprite lies02.png] (the target) will be located at : lie02.x = 128; lie02.y = 24;
and will move back and forth on screen
[sprite cowpie.png] (the projectile) will be located initially at same coordinates as thrower.png sprite ,
but when the Throw-Button is clicked (or the Up-Arrow is depressed) ,
cowpie.png will move vertically toward the target , lies02.png .
[sprite thrower.png] will be stationary , at location: this.x = (canvas.width / 2) -30; this.y = canvas.height - 64;
thrower doesn't do anything , he's just a launchpad for cowpie.png .
At [bottom of screen] will be two rows of buttons , 5 Buttons in all :
row 1: "Throw" , row 2: , "Pause" , "Play", "Clear Score" and "Quit" .
2. [The software design]
For the software design, it would be good enough to make a diagram of all the objects in the game,
their properties and how they interact with each other.
[The object of the game is]
To hit Target(lies02.png) with a cowpie.png , racking up as high a score as possible .
[Game starts] with the playing of "cheeringCrowd.mp3" , with two sprites visible , lies02.png and thrower .
[sprite movement]
[sprite "lies02.png"] moves continually back and forth across screen horizontaly .
[sprite "cowpie.png"] moves vertically , when user 'clicks or touches' the "Throw" button,
a new cowpie is created (cowpie.png) , and shoots vertically toward target (lies02.png) , attempting to collide with target .
If cowpie.png collides with lies02.png , "Good Hits" score is incremented by 1 ,
and sound file "CowMooSplat.mp3" is played .
cowpies disappear on two occasions , when cowpie reaches top of page ( if(cowpies[thisPie].y < 1) ) ,
and disappears when cowpie collides with lies02.png .
[thrower.png]
Each time the "Throw" button is depressed, a new cowpie is created , and "Total Shots" score is incremented by 1 .
[soundfiles are loaded into an array here]
var My_audio_Urls = ["sounds/CowMooSplat.mp3",
"sounds/GoodBye-Female.mp3","sounds/cheeringCrowd.mp3","sounds/oops.mp3"];
And are played here:
function playAudio(playThis) { playThis.play(); } // playThis = [object HTMAudioElement]
var playThis is the name of the sound file to play , actually (cached_Audio_files[soundArrayIndex])
Like this: {soundArrayIndex = My_audio_Urls.indexOf("sounds/CowMooSplat.mp3"); }
playAudio(cached_Audio_files[soundArrayIndex]);
[sprites are loaded into an array here]
var allImgs = [ document.getElementById("thrower"), // 0
document.getElementById("lie02"), ]; // 1
[cowpies are updated in an array here]
var cowpies = [];
Cowpies are created here:
function keyDownHandler(e) {
if(e.keyCode == 87 || event.keyCode == 38 ) { // shoot = W or upArrow
cowpies.push(cowpie = new Cowpie); // (pop) add cowpie in last position
[Cowpies are removed here]
if (thisIdTag == "lie02") {playsIt = My_audio_Urls.indexOf("sounds/CowMooSplat.mp3"); }
playAudio(cached_Audio_files[playsIt]);
cowpies.splice(thisPie,1); //alert("cowpies.length= "+ cowpies.length);
and also removed here:
if(cowpies.length > 0){
for (var i = cowpies.length - 1; i >= 0; i--) {
thisPie = i;
cowpies[thisPie].y = cowpies[thisPie].y -3 ;
ctx.drawImage(cowpieImg, cowpies[thisPie].x, cowpies[thisPie].y, cowpies[thisPie].width, cowpies[thisPie].height);
if(cowpies[thisPie].y < 1) { cowpies[thisPie].idActive = false ; cowpies.splice(thisPie,1); } // out of bounds
}
}
[Collision detection] occurs here and cowpie disappears :
for (var i = cowpies.length - 1; i >= 0; i--) {
thisPie = i;
if (cowpies[thisPie].idActive) {
if(self.visible) { // yes , do collision CK
if (cowpies[thisPie].y < this.y + this.height && cowpies[thisPie].y + cowpies[thisPie].height > this.y)
{ if (cowpies[thisPie].x < this.x + this.width && cowpies[thisPie].x + cowpies[thisPie].width > this.x )
{ // alert("YES , a collision has occurred");
thisIdTag = this.idTag ; var findsIt = 0 ; var playsIt = 0 ;
var yeslie = thisIdTag.startsWith("lie");
Edited by vmars316
Link to comment
Share on other sites

You're still using implementation terms in your requirements. It doesn't really matter if your game uses a <canvas> or not from a user perspective. That's just how it's implemented, it could be done in other ways. How would you describe your game to somebody who knows nothing about programming? That's requirements. Here's an example:

 

 

There is a rectangular area on the screen where the game plays. In that area is a thrower at the bottom in the center and a target at the top moving left and right [... these could be described in more detail...].

There are score counters on the corner of the screen [... more description of these counters]

 

Below the game area are the following buttons:

  • Throw: When clicked, this button makes a cowpie appear and start moving upwards
  • ...
  • ...

When a cowpie hits the target a sound is played and the score counter increases.

[... more descriptions here ...]

 

I think you misinterpreted the word "object" to mean "objective". By "object" I'm referring to elements of the game, like cowpie and thrower.

 

Your game has four objects: Game, Thrower, Cowpie and Target.

We need to define what properties and methods these objects should have and how they interact with each other.

 

I've already started you off with a template of how your game should be designed, I'd like you to start filling in the blanks.

Link to comment
Share on other sites

[The requirements]
The requirements would be a description of exactly how the game is supposed to look
from a user's perspective, with all the details .
The requirements should be what somebody who knows nothing about programming would ask you to make.
[There are three rectangle areas on the screen .]
[Top of screen] shows game scores: screenSize , Good Hits , Total Shots .
[Game area] Below that is a rectangular area where the game plays (game area)
[bottom of screen] At bottom of screen there are two rows of buttons , 5 Buttons in all :
row 1: "Throw" , row 2: "Pause" , "Play", "Clear Score" and "Quit" .
[Game objects] There are three game objects (sprites): Target , Cowpie and Thrower .
There are 2 moving sprites , and 1 stationary sprite , 3 sprites in total .
Game objects movement:
The Target moves back and forth across the screen .
The Cowpie is a projectile which moves vertically aimed at the Target .
Cowpie appears/shoots each time the Throw button is touched/pressed or clicked on ,
and disappears when it hits the Target , or when it goes out of game area boundaries .
When a cowpie hits the Target a sound is played and the score counter increases .
The Thrower is stationary at bottom/center of screen . It is a launchpad for Cowpie .
[Game sounds] There are three different sounds that play: 1) at game start ,
2) when Cowpie hits Target , 3) when the Quit button is pressed .
[The game objective]
To hit Target with a Cowpie , racking up as high a score as possible .

We need to define what properties and methods these objects should have and how they interact with each other.

I've already started you off with a template of how your game should be designed, I'd like you to start filling in the blanks.

 

Ok , I'll work on these .

Link to comment
Share on other sites

[Game objects properties and methods]

 

var Thrower = function () {  //  in future version  Thrower will be able to move left and right  
         var self = this;
         this.idTag = 'thrower';
         this.x = (canvas.width / 2) -30;
         this.y = canvas.height - 64;
         this.width= 64;
         this.height = 64;
this.visible = true;
    }


var Cowpie = function () {  // there can be several cowpies active at same time 
         var self = this;
         this.idTag = 'cowpie';
this.idActive = true ;
         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 = -3;
this.visible = true;
         this.directionY = -1;
    } // var cowpie


function TargetImages() {
         var self = this ;
         this.idTag = "";
         this.x = 0;
         this.y = 4;
this.width= 64;
    this.height = 64;
this.speedX = 4;
this.visible = true ; 
this.directionX = 1;
         this.update = function() {   
                 // Manage Target back and forth movement 
                 // If out of bounds occurs , switch movement direction  
    // Check for collisions  Cowpie/Target  
// When collision occurs , destroy Cowpie , update scores , and play collision sound  
             }

lie02 = new TargetImages();  // in future version this game will have 8 TargetImages 
         var self = this ;
         this.idTag = "lie02";
         this.x = 128;
         this.y = 24;
         this.width= 64;
         this.height = 64;
         this.speedX = 4;
this.visible = true ; 
this.directionX = 1;




 

Link to comment
Share on other sites

You should properly indent your code, it's already starting to get messy.

 

What is the purpose of the idTag, directionX and directionY properties?

 

If I were you I would not put the collision detection in the target's update function. Instead I would put it in the main game loop.

 

Do not create any global variables, global variables make code messy. Please read and analyze the code I provided previously and try to learn how to structure your code.

Link to comment
Share on other sites

What is the purpose of the idTag, directionX and directionY properties?

 

id.tag : to identify which Target has focus .

 

directionX & Y : to identify which direction Target is moving .

If I were you I would not put the collision detection in the target's update function. Instead I would put it in the main game loop.

 

Pls, what is your rational for this ?

Link to comment
Share on other sites

id.tag : to identify which Target has focus .

What's does "focus" mean in this context? You shouldn't need a string reference when you can reference the object itself.

 

Pls, what is your rational for this ?

Each object should be self contained and should not reference global variables or objects. Everything that it interacts with should either be a property of that object or a value passed in through one of its methods. The Game object is the only object that's has both the Cowpie and the Target as properties, so it should be the one to take care of checking for collisions between the two.

 

If you actually want the Target to detect its own collisions then you will have to make the array of cowpies a property of the target. Semantically that means that the target owns the cowpies, which I don't believe is correct.

Link to comment
Share on other sites

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

Edited by vmars316
Link to comment
Share on other sites

Actually, that's supposed to be a function declaration. It's a mistake in the code I gave, but you seemed to have a removed a parenthesis anyway.

 

It should be this:

Game.hitTest = function(a, B) {
Link to comment
Share on other sites

Hello & Thanks ;


I am trying to get a clean compile on the Diagram ,

I am getting the following errors

and 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 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;

}


: Uncaught SyntaxError: Unexpected token {

// Create or destroy cowpies

Game.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 sprite

this.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 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() {

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>

Edited by vmars316
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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, B) {
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.

Link to comment
Share on other sites

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

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...