AllSeoHelp.com
Search the Entire Site
  • PHP
  • JavaScript
  • CSS
  • HTML

JavaScript - Dice Game






Topic

Dice Game

View Content

Similar Tutorials

Dice Game
Dice Game
Javascript Dice Game Help
Dice Game Type Error
Making Dice Game 2 Player
Help Creating A Javascript Dice Game.
*resolved* Dice Roller For Classroom: Reading Double-digits Error
Javascript Game (game 2)
Javascript Game (game 1)
1 Pay 1 Game
Game Clock
Javascript Game Help
Javascript Game Help.
Need Help On Quiz Game
Guessing Game Help.
Need Help On Quiz Game
Javascript Game?
The Guessing Game
Game Problem
Help With Javascript Simon Says Game
Js Numeric Guessing Game
Game Making With Javascript?
Forms In Javascript Game
Game Engine Question..
How To Creat Puzzle Game






Dice Game

Similar Tutorials View Content

Dice Game

Similar Tutorials View Content
Hi!
I am studying webdesign and we also go through a chapter of javascript-programming. Our first assignment is to create a dice game. I have written a code and in the beginning it worked, except that all the dices showed the same random number. I tried to fix that and now I do not know what I have done! In the game, you shall click on a link and the three dices will show random numbers.
Here is my code:

Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>T&auml;rningsspel</title>
<script type="text/javascript" language="javascript">


function showDice(imgNr) {
    
    if (imgNr == 1) var imgUrl = "1.gif";
    else if (imgNr == 2) var imgUrl = "2.gif";
    else if (imgNr == 3) var imgUrl = "3.gif";
    else if (imgNr == 4) var imgUrl = "4.gif";
    else if (imgNr == 5) var imgUrl = "5.gif";
    else if (imgNr == 6) var imgUrl = "6.gif";
    document.tarning1.src = imgUrl;
    document.tarning2.src = imgUrl;
    document.tarning3.src = imgUrl;
    
 
}

function randomInteger() {
    var randNumber = Math.random();
    var randNumber = Math.floor(5*randNumber)+2;
    return randNumber; 
}
    
function showRandomPict() {
    var imgNr = randomInteger(6); 
    showDice(imgNr);
    var imgName = "tarning1" + imgNr;
    var imgName = "tarning2" + imgNr;
    var imgName = "tarning3" + imgNr;
}


function PlayAll(){    
diceSwitch('tarning1', 'text1');
diceSwitch('tarning2', 'text2');
diceSwitch('tarning3', 'text3');
}

function diceSwitch(randNumber,textRuta){    
var randNumber = randomInteger();        
}


 </script>

</head>
<body>
    <p><b>T&auml;rning 1:</b><br /><span id="text1">1</span></p>
    <p><b>T&auml;rning 2:</b><br /><span id="text2">2</span></p>
    <p><b>T&auml;rning 3:</b><br /><span id="text3">3</span></p>
        
    
    <img src="1.gif" name="tarning1" onclick="javascript:diceSwitch('tarning1', 'text1')" />
    <img src="2.gif" name="tarning2" onclick="javascript:diceSwitch('tarning2', 'text2')" />
    <img src="3.gif" name="tarning3"  onclick="javascript:diceSwitch('tarning3', 'text3')" />
    
 
    

<p><a href="javascript:PlayAll()">Spela alla!</a></p>    



</body>
</html>

Thank you!

Javascript Dice Game Help

Similar Tutorials View Content
guys im trying to make a dice game and i don't know nothing so can you guys help me with the code? This is what i am trying to do. i need help how to get started n stuff

Something that will create a random number b/w 1 n 6 and decide if the user is a winner. He will win only if the #s are equal

so i want a text box for the first number and text box for the second. a button to click to play the game(roll the dice) button to start over and reset all values
textbox to display the # of tries(rolls) textbox 2 display the # of wins. Also i want toKeep track of the number of times the user rolls the dice and display this in the appropriate textbox and the number of times the user wins the game and display this in the appropriate textbox.

Well my friend helped me with this but he made 2 player i only want one player and i want the number of tries and win the user wins if the #s are equal and i want a start over button that resets everything. Also the max number i want is 6 and only one roll the dice button but 2 textboxes so if you get same # you win it should appear in alert and text box for tries and wins. Also, i am gonna have 2 pics one for the first textbox the other for the second both of the pics are gonna be dice and i am gonna have 12 pics but only 2 appear at a time so if a guy gets 5 the dice with the #5 appears and the other text gets 4 the dice with the # 4 appears
Code:
<html>
<HEAD>

<SCRIPT LANGUAGE="JavaScript">
var die = 6;
var dice = 2;
var ary=[];

function dice_roll(die, dice,nu) {
 var txt=document.form.text;
 for (var roll=0,loop=0; loop < dice; loop++) {
  roll = roll + Math.round(Math.random() * die) % die + 1;
 }
 if (ary.length==0&&nu==0){
  txt[0].value =ary[0]= roll;
  txt[1].value = 0;
 }
 if (ary.length==1&&nu==1){
  txt[1].value = ary[1]= roll;
  if (ary[0]==ary[1]){
   alert('Draw');
  }
  else if (ary[0]>ary[1]){
   alert('Player 1 Wins');
  }
  else {
   alert('Player 2 Wins');
  }
  ary=[];

 }
}
// End -->


</script>

<body>
<form name=form>
<table border=2 cellpadding=5>
<tr>
 <td colspan=2 align=middle>No. of sides/dice</td>

</tr>
<tr>
<td valign=top align=middle>
<p><input type=radio checked name=sides onClick="die = 6">6 Sided
</td>
<td valign=top align=middle>
<p><input name=number type=radio onClick="dice = 2" checked>
2
</td>
</tr>
<tr>
<td colspan=2 >
Player 1
</td>
</tr>
<tr>
<td align=middle colspan=4>
<input type=button value="Roll Dice" name=button onClick="dice_roll(die, dice,0)">
<input type=text size=10 name=text value="0" disabled="disabled" >
</td>
</tr>
<tr>
<td colspan=2 >
Player 2
</td>
</tr>
<tr>
<td align=middle colspan=4>
<input type=button value="Roll Dice" name=button onClick="dice_roll(die, dice,1)">
<input type=text size=10 name=text value="0" disabled="disabled" >
</td>
</tr>
</table>
</form>

</center>
</body>
</html


Dice Game Type Error

Similar Tutorials View Content
everything in this dice rolling game is fine until line 69 where i get TypeError:actuals[i] undefined. Any help would be appreciated.

http://pastebin.com/bVmgMcbB

Making Dice Game 2 Player

Similar Tutorials View Content
Hi,

I'm trying to make a dice game, as well as making it two player. I need to be able to have a scoreboard displayed (eg. player 1 has won 7 times and player 2 has won 4) and I need to be able to prompt the user on if they want to play the game again.

So far I have the following:
Code:
<html>
<HEAD>

<SCRIPT LANGUAGE="JavaScript">
<!-- Dice Game -->


<!-- player 1
var die = 6;
var dice = 2;
var player1 = 0;
var player2 = 0;

function dice_roll(die, dice) {
var roll = 0;
for (loop=0; loop < dice; loop++) {
roll = roll + Math.round(Math.random() * die) % die + 1;
}
document.form.text.value = roll;
}
player1 = roll;
// End -->

<!-- player 2
function dice_roll2(die, dice) {
var roll = 0;
for (loop=0; loop < dice; loop++) {
roll = roll + Math.round(Math.random() * die) % die + 1;
}
document.form.text.value = roll;
}
player2 = roll;
// End -->

if player_1 = player_2 
alert("DRAW!")

else if player_1 > player_2
alert("Player 1 is the winner!")

else if player_1 < player_2
alert("Player 2 is the winner!")

</script>

<body>
<form name=form>
<table border=2 cellpadding=5>
<tr>
<td colspan=2 align=middle>No. of sides/dice</td>

</tr>
<tr>
<td valign=top align=middle>
<p><input type=radio checked name=sides onClick="die = 6">6 Sided
</td>
<td valign=top align=middle>
<p><input name=number type=radio onClick="dice = 2" checked>
2
</td>
</tr>
<tr>
<td align=middle colspan=4>
<input type=button value="Roll Dice" name=button onClick="dice_roll(die, dice)">
<input type=text size=10 name=text>
</td>
</tr>
</table>
</form>

</center>
</body>
</html

^^ I basically just tried duplicating the original function that adds up the 'dice'. But it doesn't work, I've tried playing around with if/else statements etc to get it to display messages and so fourth, but I have failed.

Any help would be appreciated. I only started javascript last week and my teacher isn't really helping explain lots of it.

Thanks in advance.

Help Creating A Javascript Dice Game.

Similar Tutorials View Content
Create a game where 6 dice are 'rolled' by you and 6 dice are 'rolled' by the player (simulated by the click of a button). Add up both rolls. The goal is to come as close to a score of 100 as possible, without passing 100. Have a STOP button to signify when you are ready to stop rolling and compute the winner. The highest score under 100 wins. Display the number of times you win and the number of times the computer wins using javascript. So far I have the following code, however, my dice images are not working(they display as little broken symbols when I run the game). The game itself is running just fine but I can't figure out how to get the game to do the "Add up both rolls" step and beyond. If anyone can help it would be much appreciated. Thanks.


Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
  <head>
    <title>Dice Game</title>
    <link href="Dicegame.css" type="text/css" rel="stylesheet" /> 
  </head>
  <body>
  
    <div id='human' class='playerArea'>
      <h3>Human</h3>
      <div id='humanDice'>
      </div>
      <p id='humanTotal' class='total'></p>
    </div>
    
    <div id='computer' class='playerArea'>
      <h3>Computer</h3>
      <div id='computerDice'>
      </div>
      <p id='computerTotal' class='total'></p>
    </div>
    
    <div id='roll'>
      <a href='#' onclick='play(); return false;'>Roll</a>
    </div>
    
    <script type='text/javascript' src='lib.js'></script>
    <script type='text/javascript' src='dicegame.js'></script>
    
  </body>
</html>

*the external links are as follows*
*Dicegame.css*
body
{
background-color: #004400;
}

div.playerArea
{
position: absolute;
top: 100px;
bottom: 200px;
width: 300px;

background-color: #0996FF;
border: 3px solid #0027C6;
padding: 0 1em;
}

div#human
{
left: 100px;
}

div#computer
{
right: 100px;
}

div#roll
{
position: absolute;
bottom: 50px;
left: 100px;
right: 100px;
height: 100px;
background-color: #FFFF00;
border: 3px solid #FFBE00;

}

div#roll:hover
{
background-color: #FFFF99;
}

div#roll a
{
display: block;
position: absolute;
top: 0px;
bottom: 0px;
width: 100%;
color: #004400;
text-align: center;
font-size: 90px;
text-decoration: none;
}

div#roll a:hover
{
color: #FF0000;
}

p.total
{
margin: 10px;
font-weight: bold;
font-size: 8em;
text-align: center;
}

p.winner
{
color: #00CC00;
}

p.loser
{
color: #CC0000;
}[/CODE]

*dicegame.js*
Code:
window.onload=function(){
Nifty("div.playerArea", "big");
}

function roll()
{
  var result = 0;
  result = Math.floor((Math.random() * 6) + 1);
  return result;
}


function play()
{
  // create dice array
  var humanDice = new Array();
  var computerDice = new Array();
  
  // totals
  var humanTotal = 0;
  var computerTotal = 0;
  
  // output
  var out = "";
  
  // roll the dice
  for (var i = 0; i < 6; i++)
  {
    humanDice[i] = roll();
    humanTotal += humanDice[i];
    
    computerDice[i] = roll();
    computerTotal += computerDice[i];
  }
  
  // display human dice
  out = displayDice(humanDice);
  document.getElementById('humanDice').innerHTML = out;
  
  // display computer dice
  out = displayDice(computerDice);
  document.getElementById('computerDice').innerHTML = out;
  
  document.getElementById('humanTotal').innerHTML = humanTotal;
  document.getElementById('computerTotal').innerHTML =  computerTotal;  
  
  if (humanTotal > computerTotal)
  {
    document.getElementById('humanTotal').className = 'total winner';
    document.getElementById('computerTotal').className = 'total loser';
  }
  else if (computerTotal > humanTotal)
  {
    document.getElementById('humanTotal').className = 'total loser';
    document.getElementById('computerTotal').className = 'total winner';
  }
  else
  {
    document.getElementById('humanTotal').className = 'total';
    document.getElementById('computerTotal').className = 'total';
  }

}

function displayDice(dice)
{
  var out = "";
  for (var i = 0; i < dice.length; i++)
  {
    out += "<img src='die" + dice[i] + ".png'/>";
  }
  
  return out;
}

*lib.js*

Code:
function output(text, tag)
{
  document.write("<" + tag + ">" + text + "</" + tag + ">");
}


*resolved* Dice Roller For Classroom: Reading Double-digits Error

Similar Tutorials View Content
So far I've logged forty hours in total trying to locate and fix the major problems in this code. I've worked with two other forums and a pay-by-minute guru to no avail. I am hopeful that the good folks here at CodingForums will be able to take this code the final distance. I'll try to be verbose without boring anyone.

Summary: This code was written in 2005/2007 by "Wonder" at ProBoards. I teach a fourth grade game design and applied mathematics class to home-schoolers on a ProBoards forum. It is placed in the global footer of the forum to allow forum members to roll dice in their posts. The code was incomplete. I worked with "Jordan" at ProBoards to fix the parts that were incomplete. A problem with the code resulted.

Primary resolution I'm seeking: Right now the code does everything I could possibly want. However, it is mistakenly reading double-digit numbers (XY) as X = sides of die and Y = a negative modifier. Once this issue is fixed, I can take the roller back to my students and they can game together.

Secondary resolutions I'm seeking: (1) I've been told twice that the code should be "tabbed out." Not sure what that means but I guess it makes it less messy. (2) When clicking the "Add Tag" button the code generates, it automatically inserts [dice=6] into a forum post. Would love this to simply be [dice=X]

The original code from "Wonder":

Code:
<style type="text/css">
.dicebg {background-color: FFFFFF;border:solid 2px #000000;}
.dicefont {background-color: FFFFFF;color: 000000; font-weight:bold;}
</style>
<script>
//Dice Rolls In Posts v1.1 updated 31 October 2008

//Copyright 4-23-2007 ~Wonder
//May be reposted anywhere as long as this header remains in tact

//Do you want the dice to line of horizontally(true) or vertically(false)
diceAlignment=true;

//Enter URL of the image you want to appear as the dice ubbc button
UBBCdiceImage="http://img100.imageshack.us/img100/6118/diceicon9rx.gif";

//Enter the default # of sides
defaultSides=6;

//Enable dice in preview? true or false
enablePreview=true;

rs="";mainForm="";
if(document.postForm)
{
mainForm=document.postForm;
if(location.href.match(/action\=modifypost/)){enablePreview=true;}
mainForm.color.parentNode.innerHTML+="<a href=javascript:add(\"[dice="+defaultSides+"]\",\"\")><img src=\""+UBBCdiceImage+"\" alt=\"Insert Dice Roll\" border=\"0\"></a>";
mainForm.onsubmit=addRand;
mainForm.message.value=mainForm.message.value.replace(/(\[rand\=\d+\])/ig,"");
rs=RegExp.$1; rs=(/\[rand\=/.test(rs))?rs:"";
if(location.href.match(/quote\=\d+/))
{
mainForm.message.value=mainForm.message.value.replace(/(\[dice\=\d+\])/ig,"");
rs="";
}
}
else if(location.href.match(/action\=display/))
{
ta=document.getElementsByTagName("textarea");
if(ta.length>0 && ta[0].name=="message")
{
mainForm=ta[0].parentNode;
mainForm.onsubmit=addRand;
}
}

///////////////////////
if(location.href.match(/action\=(display|pmview|recent|userrecentposts|gotopost|search|calendarview)/) || (!location.href.match(/action\=/) && document.postForm && enablePreview))
{
hr=document.getElementsByTagName("hr");
for(i=0;i<hr.length;i++)
{
if(typeof(hr[i].parentNode)!="undefined" && hr[i].parentNode.tagName=="TD" && typeof(hr[i].parentNode.lastChild)!="undefined" && typeof(hr[i].parentNode.lastChild.lastChild)!="undefined" && hr[i].parentNode.lastChild.lastChild.nodeType!=1)
{
n=hr[i].parentNode.lastChild;
rand=n.innerHTML.match(/\[rand\=\d+\]/);
if(rand!=null)
{
n.innerHTML=n.innerHTML.replace(rand[0],"");
rand=rand[0].replace(/[^\d]/g,"");
dice=n.innerHTML.match(/\[dice\=\d+(\+\d+)?\]/ig);
if(dice!=null)
{
for(k=0;k<dice.length;k++)
{
numb=dice[k].match(/\d+(\+\d+)?/);
numb=numb[0].split("+");
addon=numb.length>1?parseInt(numb[1],10):0;
numb=parseInt(numb[0],10);
roll=Math.round((parseFloat(rand.substring(k,k+2)+"."+rand.substring(k+2,rand.length))/100)*(numb-1))+1+addon;
n.innerHTML=n.innerHTML.replace(dice[k],"<table "+(diceAlignment?"style=\"display:inline\"":"")+" border=0 cellpadding=0 cellspacing=0><tr><td><table class=dicebg cellpadding=1 cellspacing=0><tr><td><center><font class=dicefont size=\"+1\"><b>"+roll+"</b><br><font size=\"1\">"+numb+" sides"+(addon>0?"+"+addon:"")+"</font></font></center></td></tr></table></td></tr></table>&nbsp; ");
}
}
}
}
}
}
function addRand()
{
mainForm.message.value=mainForm.message.value.replace(/(\[rand\=\d+\])/ig,"");
if((rs.length==0 && mainForm.message.value.match(/(\[dice\=\d+(\+\d+)?\])/)) && (enablePreview==true || (enablePreview==false && mainForm.nextaction.value=="post")))
{
mainForm.message.value+="[rand="+(Math.random()+"").replace(/0\./,"")+(Math.random()+"").replace(/0\./,"")+(Math.random()+"").replace(/0\./,"")+( Math.random()+"").replace(/0\./,"")+"]";
}
else
{
mainForm.message.value+=rs;
}
disable(mainForm);
}
</script>

The altered code from "Jordan":

Code:
<style type="text/css">
.dicebg {background-color: FFFFFF;border:solid 2px #000000;}
.dicefont {background-color: FFFFFF;color: 000000; font-weight:bold;}
</style>
<script>
//Dice Rolls In Posts v1.1 updated by Jordan October 2009

//Copyright 4-23-2007 ~Wonder
//May be reposted anywhere as long as this header remains in tact

//Do you want the dice to line of horizontally(true) or vertically(false)
diceAlignment=true;

//Enter URL of the image you want to appear as the dice ubbc button
UBBCdiceImage="http://img100.imageshack.us/img100/6118/diceicon9rx.gif";

//Enter the default # of sides
defaultSides=6;

//Enable dice in preview? true or false
enablePreview=true;



rs="";mainForm="";
if(document.postForm)
{
mainForm=document.postForm;
if(location.href.match(/action\=modifypost/)){enablePreview=true;}
mainForm.color.parentNode.innerHTML+="<a href=javascript:add(\"[dice="+defaultSides+"]\",\"\")><img src=\""+UBBCdiceImage+"\" alt=\"Insert Dice Roll\" border=\"0\"></a>";
mainForm.onsubmit=addRand;
mainForm.message.value=mainForm.message.value.replace(/(\[rand\=\d+\])/ig,"");
rs=RegExp.$1; rs=(/\[rand\=/.test(rs))?rs:"";
if(location.href.match(/quote\=\d+/))
{
mainForm.message.value=mainForm.message.value.replace(/(\[dice\=\d+\])/ig,"");
rs="";
}
}
else if(location.href.match(/action\=display/))
{
ta=document.getElementsByTagName("textarea");
if(ta.length>0 && ta[0].name=="message")
{
mainForm=ta[0].parentNode;
mainForm.onsubmit=addRand;
}
}



///////////////////////
if(location.href.match(/action\=(display|pmview|recent|userrecentposts|gotopost|search|calendarview)/) || (!location.href.match(/action\=/) && document.postForm && enablePreview))
{
hr=document.getElementsByTagName("hr");
for(i=0;i<hr.length;i++)
{
if(typeof(hr[i].parentNode)!="undefined" && hr[i].parentNode.tagName=="TD" && typeof(hr[i].parentNode.lastChild)!="undefined" && typeof(hr[i].parentNode.lastChild.lastChild)!="undefined" && hr[i].parentNode.lastChild.lastChild.nodeType!=1)
{
n=hr[i].parentNode.lastChild;
rand=n.innerHTML.match(/\[rand\=\d+\]/);
if(rand!=null)
{
n.innerHTML=n.innerHTML.replace(rand[0],"");
rand=rand[0].replace(/[^\d]/g,"");
dice=n.innerHTML.match(/\[dice\=\d+((\+|\-)\d+)?\]/ig);
if(dice!=null)
{
for(k=0;k<dice.length;k++)
{
numb=dice[k].match(/\d+((\+|\-)\d+)?/);
numb=numb[0].split(RegExp.$2);
unsigned = (RegExp.$2 == "+") ? true : false;
addon=numb.length>1?parseInt(numb[1],10):0;
if(!unsigned)addon = addon - addon * 2;
numb=parseInt(numb[0],10);
roll=Math.round((parseFloat(rand.substring(k,k+2)+"."+rand.substring(k+2,rand.length))/100)*(numb-1))+1+addon;
n.innerHTML=n.innerHTML.replace(dice[k],"<table "+(diceAlignment?"style=\"display:inline\"":"")+" border=0 cellpadding=0 cellspacing=0><tr><td><table class=dicebg cellpadding=1 cellspacing=0><tr><td><center><font class=dicefont size=\"+1\"><b>"+roll+"</b><br><font size=\"1\">"+numb+" sides"+(addon>0?"+"+addon:addon)+"</font></font></center></td></tr></table></td></tr></table> ");
}
}
}
}
}
}
function addRand()
{
mainForm.message.value=mainForm.message.value.replace(/(\[rand\=\d+\])/ig,"");
if((rs.length==0 && mainForm.message.value.match(/(\[dice\=\d+((\+|\-)\d+)?\])/)) && (enablePreview==true || (enablePreview==false && mainForm.nextaction.value=="post")))
{
mainForm.message.value+="[rand="+(Math.random()+"").replace(/0\./,"")+(Math.random()+"").replace(/0\./,"")+(Math.random()+"").replace(/0\./,"")+( Math.random()+"").replace(/0\./,"")+"]";
}
else
{
mainForm.message.value+=rs;
}
disable(mainForm);
}
</script>

My incredibly detailed account of my last few weeks with this code:

Back in 2005, a user named "Wonder" wrote a nifty piece of code that fits into any ole ProBoard's global footer. Once installed on a forum, it allows users to type the command [dice=X] where X is the number of sides for the single die they want to roll and it gives them a random result that's very attractive (a small white box with a black border and a bold, large result with smaller text below that reads: Xsides) and not "easy" to change/alter/cheat. To roll more than one die, you simply string the command like [dice=X][dice=X][dice=X][dice=X]. The code also allows for positive modifiers (bonuses) such as [dice=X+Y] where the result has the same compact, attractive format and the small text reads: Xsides+Y

Wonder posted that his code would also allow negative modifiers (penalties) but, actually, no one seems to have ever tested that part... until September 2009 when along came pesky me.

I went over to the ProBoards support forum because Wonder's code is included in their official database. I posted the problem and a user named Jordan tweaked the code several times, each time getting it closer to providing the correct result. The correct result being that when a user types the command [dice=X-Y] the result is the attractive box, the larger number above and the smaller text below that reads Xsides-Y (in addition to continuing to accept [dice=X] and [dice=X+Y] and offer the same format of results).

Jordan's version of the code now does all this. But when I started testing it I realized that whenever a user types a command that gives the die double-digit sides (10, 12, 20, etc), the code now reads it like this: [dice=10] results in 1sides-0 or [dice=12] results in 1sides-2. So double-digit numbers are being read as the number of sides and a negative modifier *sigh* Very bad news.

Jordan needed to pass on further work on the code because (understandably) it was taking too much time and it was "messy." Since I am not a coder myself, most JavaScript looks messy to me but I believe Jordan.

I then took the code to a pay-by-minute help website but was gently told that the code was so messy that it would take too long to debug and it wouldn't be worth the charge since the roller is being used for a non-profit classroom project for my fourth graders. I thought that was very thoughtful... but I'm back at square one, really.

I have attached everything I have: The very original code from Wonder (the one that doesn't read negative modifiers at all) and the latest from Jordan (that reads double-digits incorrectly).

The only other cute/attractive thing about the code that I'll point out (so you don't see it in the code and wonder, "What the heck is that?" is: When you install the code into a forum, it adds a tiny die-shaped button to the Add Tags menu. Users can click the little thing and the code automatically inserts [dice=6] for them. Personally, this doesn't help my students and I would love it if the button just inserted [dice=X] but that's fine.

*deep breath*

Whew! That's about it. Thank you for putting up with my blather. I sincerely appreciate any help you can offer. I know your time is valuable and I've taken quite a bit just posting my full report... I just wanted to try to be verbose :)

Jennifer

Javascript Game (game 2)

Similar Tutorials View Content
This is a simple basic game i want to make.

Its a "What Am I" Riddle...

The questions is (In HTML which i already know):
I'm as light as a feather but no man can hold me for long. What am I?

the answer is: Your Breath.


(This is where the JAVASCRIPT comes in)
Lets say they guess a rock, have a pop up say:
Wrong Answer. Please try again.

Lets say they guess Your breath -OR- Breath, have a pop up say:
Correct!

I want a text field where you can enter your answer, and if they choose ANYTHING but the 2 correct answers above, it will display please try again.

Can anyone code this please?
Thanks for reading.

Javascript Game (game 1)

Similar Tutorials View Content
Ok so i want to work on an EASY basic game. As simple as Guess what number... But there are some twist...

Ok So here is my example...

(HTML, i know this.)I'm Guessing a number 1-99. What is it?

(java) Lets say its 66 and they guess 53, have the text rusult be in a pop up window be: Too low!

(java) Lets say they guess 78, have the text rusult be in a pop up window be: Too high!

(java) Lets say they guess 100+, have the text rusult be in a pop up window be: Out of range!

(java)But lets say they guess 66, have a text result be in a pop up window be: You've won!

(java) I want a text field where you can enter your answer, and it will do the actions above.

Can anyone code this?
Thanks for reading!

1 Pay 1 Game

Similar Tutorials View Content
I have a game page on my site and I am trying to protect direct access to it by .htaccess .htpasswd but is not accepting user name and password?

.htaccess:

AuthUserFile /home/vhosts/kandcoentertainment.freetzi.com/.htpasswd
AuthType Basic
AuthName "game1"

<Files "cookietest.html">
Require valid-user
</Files>

.htpasswd

test:8888

Any suggestions on why it is not working?


What I would like to do is have apay and play once setup but as I am a novice and dont have a clue HELP PLEASE!!!

What I have been told is - protect the files, add a client side cookie to game page then upon url payment return validate cookie giving single access and when played the user cannot replay by refresh or just typing in url because cookie expired ? I have tried to write the scripts up with no success.

Game Clock

Similar Tutorials View Content
Hello, I am trying to create a clock for my video game. I need to begin the clock at zero and count while the game is going. I need to have the clock count in standard minutes and seconds but not be based on the actual time of day. I am coding in javascript for an applet.

Javascript Game Help

Similar Tutorials View Content
I am creating a guessing word game and when the user types in a guess a pop-up tells the user how many letters the user got right to the actual answer.

My problem is I can't seem to display the number of letters the user guessed right.

This is what the function looks like:

Code:
function guessing()
{
	words = "album";
	guess = document.getElementById("txt1").value;
	answer = document.getElementById("result").value = parseInt();
		alert("You have " + answer + " matches");
		
	used = false;
	for(i = 0; i<=guess.length; i++)
	{
		for(j = 0; j<=answer.length; j++)
		if(!used[j] && guess[i] == words)
		{
			alert("Congradulations! You got it!");
			used[j] = true;
			count++;
			break;
		}
		
		else
		{
				count = 5;
				while(count > 5)
				{
					alert("Sorry, that's game over!");
					count++;
				}
		}
		
	}
}


Javascript Game Help.

Similar Tutorials View Content
A newbie here can you please help me with my javascript game. I cant seem to make it work.



Quote:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Language" content="en-us" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Play</title>

<script type='text/javascript'>
function win(x, z){

if(x == z)
return "It's a draw";
draw.value++;
{
if(x == "Fire")&&(z == "Air")
return "You Lose, Fire beats Air!";
loss.value++;
else if(x == "Fire")&&(z == "Earth")
return "It's a draw!";
draw.value++;
else if(x == "Fire")&&(z == "Water")
return "You Win, Fire is beaten by Water!";
win.value++;
}
{
if(x == "Air")&&(z == "Earth")
return "You win, Air beats Earth";
win.value++;
else if(x == "Air")&&(z == "Water")
return "It's a draw!";
draw.value++;
else if(x == "Air")&&(z == "Fire")
return "You lose, Air is beaten by Fire!")
loss.value++
}
{
if(x == "Earth")&&(z == "Air")
return "You Lose, Earth is beaten by Air"
loss.value++;
else if(x == "Earth")&&(z == "Water")
return "You Win, Earth beats Water";
win.value++;
else if(x == "Earth")&&(z == "Fire")
return "It's a draw!";
draw.value++;
}
{
if(x == "Water")&&(z == "Fire")
return "You win, Water beats Fire";
win.value++;
else if(x == "Water")&&(z == "Air")
return "It's a draw!";
draw.value++;
else if(x == "Water")&&(z == "Earth")
return "You lose, Water is beaten by Earth"
loss.value++;
}
}

function ran(){
var gen = Math.random();
if(gen <= 0.25)
var com = "Fire";
if((gen > 0.25)&&(gen<= 0.50))
var com = "Earth";
if(gen > 0.50)&&(gen<= 0.75))
var com = "Water";
if(gen > 0.75)
var com = "Air";
if(document.c.game[0].checked)
var use = "Fire";
if(document.c.game[1].checked)
var use = "Earth";
if(document.c.game[2].checked)
var use = "Water";
if(document.c.game[3].checked)
var use = "Air";

alert ("The computer played: " + com +". You played: " + use + ". " + win(com,use));
}

</script>

<style type="text/css">
body {background-color:#7f9527;}
.style1 {
color: #FFFFFF;
}
.style2 {
font-family: "After Disaster";
}
.style3 {
font-family: "After Disaster";
font-size: 30pt;
color: #FFFFFF;
margin-left: 160px;
}
.style4 {
font-size: xx-large;
}
.style5 {
color: #FFFFFF;
font-size: large;
}
.style6 {
color: #FFFFFF;
font-family: "After Disaster";
font-size: large;
}
.style7 {
margin-top: 0px;
}
.style8 {
color: #FFFFFF;
font-family: "After Disaster";
font-size: xx-large;
margin-left: 280px;
}
.style9 {
font-size: large;
}
.style10 {
margin-top: 12px;
}
</style>

</head>

<body>

<p class="style3" style="width: 581px">Avatar The Last Air bender: Element Fight</p>

<p class="style8" style="width: 340px">
<img alt="" src="Avatar_Aang_by_Shira_chan.jpg" width="339" height="244" class="style7" /></p>
<p class="style6">Select Your Attack</p>
<form name="c" method="post" class="style2">
<span class="style4"><span class="style9">
<input name="game" type="radio" value="Fire" /></span></span><span class="style5">Fire</span><span class="style9"><br />
</span><span class="style4"><span class="style9">
<input name="game" type="radio" value="Earth" /></span></span><span class="style5">Earth</span><span class="style9"><br />
</span><span class="style4"><span class="style9">
<input name="game" type="radio" value="Water" /></span></span><span class="style1"><span class="style9">Water<br />
<span class="style4">
<input name="game" type="radio" value="Air" /></span>Air</span><br /></span>
<tr>
<td colspan="4" align=center>
<span class="style2">
<input type="text" name= "win" readonly="readonly" value="0" size="2"> Wins </input>
<input type="text" name= "loss" readonly="readonly" value="0" size="2"> Losses</input>
<input type="text" name= "draw" readonly="readonly" value="0" size="2"> Draws</input>
</span>
</td>
</tr>
</form>

<form method="post">
<br />
<input name="Play" type="button" value="Play" onClick="ran()" style="width: 189px; height: 39px" />
<a href="Instructions.htm">
<input name="Button1" type="button" value="Instructions" style="width: 189px; height: 39px" class="style10" /></a></form>

</body>

</html>

Need Help On Quiz Game

Similar Tutorials View Content
sorry this post is duplicated, the original post:http://www.codingforums.com/showthread.php?t=261488

Guessing Game Help.

Similar Tutorials View Content
What I'm trying to achieve is it initialises a number between 1-2000 randomly.
When the submit button is clicked it simply returns if the number that is in putted is higher or lower than the randomly initialised number.
External JavaScript:

Html
Code:
<html>
<head>
<script type="text/javascript" src="jsscri.js"></script>
</head>
<body onload="initialisation ()">

<form name="exampleform">
 <h3>
Number: <input name="number" type="text" 
            onchange='checkNumber( this.value );'>
</h3>
 <p>
	<input name="submit" type="button" value="Guess"
	onclick= 'checkValue()';/>  
 </p>
 

</body>
</html>

If you load this onto a webpage you'll see what i'm trying to do. I tried deleting the rest of the code to keep the size of the code down.

Need Help On Quiz Game

Similar Tutorials View Content
Hello all,

* I'm very new to javascript and working on a quiz game. Theres a set of code im working on but i need help, and greatly appreciate any help.

* After every questions, there is a tick or wrong animation/image that should pop over the answer card.
I created the gif file one for a tick and one for a wrong:
http://www.freeimagehosting.net/cqn91
http://www.freeimagehosting.net/v74v6

*By right the user should not be able to click on the answer cards anymore after finishing the quiz. For now the score keeps going up although the quiz is done. And after the quiz is done, a button should direct the user to the DetailedResult page, instead of the popup.

*How to change the popup into a Html(DetailedResult) page, and instead of a text eg.(resent.jpg), how can I make the real image show, and if the qn is correct, how can I place a tick and if the qn is wrong how can I place a wrong image.
Ive created both images.
tick image==>http://i1069.photobucket.com/albums/...ttica/tick.jpg
wrong image==>http://i1069.photobucket.com/albums/...ca/wrong-1.jpg

*Suppose at the bottom of the html page, should have a button for the user to retry only wrong answers.
*And how do i keep updating the user score for each attempt he tries on the table.

Below are a set of code i'm working on, and another set of Html layout(DetailedResult) which i intend to achieve.

Code:
<!DOCTYPE HTML>
<html>
<head>
<title> Card Test </title>
<style>
img { margin:7px; }
#Question {
text-align:left;
font-family:"Vladimir Script";
font-size:40px;
}
</style>

<script type="text/javascript">
// For: http://www.codingforums.com/private....pm&pmid=124136

var baseURL = 'http://s1069.photobucket.com/albums/u475/felettica/';
var questions = [
// format [pic,[image1,imag2,image3]],
['happy.jpg', ['*|delight.jpg','|sad.jpg','|confuse.jpg']], // 0
['angry.jpg', ['|sad.jpg','*|resent.jpg','|joyful.jpg']], // 1
['father.jpg',['|sister.jpg','|mum.jpg','*|dad.jpg']], // 2
['sports.jpg',['|crying.jpg','*|soccer.jpg','|sleep.jpg']], // 1
['fruit.jpg', ['*|apple.jpg','|meat.jpg','|bacon.jpg']], // 0
];

var qNo = 0;
var correct = [];
function $_(IDS) { return document.getElementById(IDS); }

function NextQuestion(IDS) {
var response;
switch (IDS) {
case 'image1' : response = 0; break;
case 'image2' : response = 1; break;
case 'image3' : response = 2; break;
}
if (response == currentQuestion[4]) {
correct[0]++; 
alert('Well Done');
} else {
alert('Wrong Answer');
}
correct.push(currentQuestion.join('|')+'|'+response); // alert(correct.join('\n'));
qNo++;

if (qNo < questions.length) {
$_('score').innerHTML = 'Sco  '+correct[0];
showImages(qNo);
$_('Question').innerHTML = 'Question: '+(qNo+1);
} else {
$_('score').innerHTML = 'You had '+correct[0]+' correct answers for '+questions.length+' questions';
DisplayQuizResults();
// alert('End of quizi\n\n'+correct.join('\n'));
return;
}
// I created a two .gif animation of a tick and a wrong 
// but unsure how to place it so that it appears on the
// correct answer image instead of the alertbox.
// Tick animation Url==> http://www.freeimagehosting.net/cqn91
// Wrong animation Url==>http://www.freeimagehosting.net/v74v6
// I tried to add a button to direct to the DetailedResult page
// which shows the correct and wrong questions but it didnt appear.
// It should appear after the alert('End of quiz'); pops up.
}

var currentQuestion = [];
function showImages(ptr) { 
var tarr = []; var tmp = '';
currentQuestion = [];
currentQuestion.push(questions[ptr][0]); // 0 
temp_questions = questions[ptr][1].slice();
temp_questions.sort(randOrd);
for (var i=0; i<3; i++) {
tarr = temp_questions[i].split('|')
if (tarr[0] != '') { tmp = i; } // save correct answer
currentQuestion.push(tarr[1]); // 1,2,3 // save response order
}
currentQuestion.push(tmp); // 4 

$_("Pic").src=baseURL+currentQuestion[0];
$_("image1").src=baseURL+currentQuestion[1];
$_("image2").src=baseURL+currentQuestion[2];
$_("image3").src=baseURL+currentQuestion[3];
}

function randOrd() { return (Math.round(Math.random())-0.5); }
window.onload = function() {
correct = []; correct.push(0);
questions = questions.sort(randOrd);
showImages(0);
}

// Following from: http://www.yourhtmlsource.com/javascript/popupwindows.html
function DisplayQuizResults() {
var generator=window.open('','name','height=400,width=500');
generator.document.write('<html><head><title>Popup</title>');
generator.document.write('<link rel="stylesheet" href="style.css">');
generator.document.write('</head><body>');
var str = '';
var tarr = [];
// correct array format: item +|+ question +|+ answer +|+ response 

var str = '<h1> Your Results</h1>';
for (var i=1; i<correct.length; i++) {
tarr = correct[i].split('|'); // item|img1|img2|img3|ans|resp
str += 'Question #'+i;
str += ' was: '+tarr[0];
str += '<br>Correct answer was: '+tarr[4] +'('+tarr[tarr[4]*1+1]+')';
if (tarr[4] != tarr[5]) {
str += ' but your answer was: '+tarr[5] +'('+tarr[tarr[5]*1+1]+')';
}
str += '<p>';
}
generator.document.write('<p>'+str+'<p>');
generator.document.write('<p><a href="java_script:self.close()">Close</a> the popup.</p>');
generator.document.write('</body></html>');
generator.document.close();
}
</script>

</head>
<body>
<div id="Question">Question: 1</div>
<div align="center">
<img id="Pic" src="" height="220" width="321"> <p>
<img id="image1" src="" width="269" height="171" onclick="NextQuestion(this.id)">
<img id="image2" src="" width="269" height="171" onclick="NextQuestion(this.id)">
<img id="image3" src="" width="269" height="171" onclick="NextQuestion(this.id)">
<p> <span id="score">Sco  </span> <p></div>
</body>
</html>

================================================
Instead of the popup, instead i thought having it on a Html page (DetailedResult), the layout below
================================================
Code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>


<style type="text/css">
Table{
	position:absolute;
	left:632px;
	top:97px;
	width: 408px;
	border:1px solid black;
}
table, td, th
{
border:1px solid green;
}
th
{
background-color:green;
color:white;
}
</style>

</head>

<body>

<table width="472" border="0" cellspacing="0" cellpadding="0"> <!--In the table,the scores of the user should appear for the the current attempt and previous attempts so that the user can track his scores-->
  <tr>
    <th width="227" scope="row"><strong>My Attempts</strong></th>
    <td width="181"> <div align="center">My sco </div></td>
  </tr>
  <tr>
    <th height="19" scope="row">1st Attempt</th>
    <td><div align="center">4/5</div></td>
  </tr>
  <tr>
    <th scope="row">2nd Attempt</th>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <th scope="row">3rd Attempt</th>
    <td>&nbsp;</td>
  </tr>
</table>
<h1> My Current Attempt </h1>
<p>&nbsp;</p>
<p>Question 1: "code to get Qn 1 image"  "either tick image or wrong image" </p> <!-- For each qn, its picture will appear and either a tick or wrong image next to it. If the user answer it correctly, then a tick will appear or other wise. The image of the question would be smaller. -->
<p>Question 2: "code to get Qn 1 image"  "either tick image or wrong image"</p>
<p>Question 3: "code to get Qn 1 image"  "either tick image or wrong image"</p>
<p>Question 4: "code to get Qn 1 image"  "either tick image or wrong image"</p>
<p>Question 5: "code to get Qn 1 image"  "either tick image or wrong image"</p>

<p><button type="button">Retry Wrong Question</button><p> <!-- direct page to retry wrong qns once more -->

<!-- tick image URL:http://i1069.photobucket.com/albums/...ttica/tick.jpg 
 wrong image URL http://i1069.photobucket.com/albums/...ca/wrong-1.jpg 
 baseURL:http://s1069.photobucket.com/albums/u475/felettica/   -->

</body>
</html>


Javascript Game?

Similar Tutorials View Content
How hard would it be to make a 2d game similar to super smash bros?

Basically I want to have a scrolling position (instead of a static image, where the background is always the same) where when the user moves his character object, the area of vision moves with him.

Also, will it work with using keyboard keys?

I have to integrate it into a database and I know quite a bit of javascript so I am hoping it is possible.

Thanks!
Max

The Guessing Game

Similar Tutorials View Content
Can someone guide me to what I am doing wrong. My book does not show how to do this. This is what I have to far.I am just getting more and more confused. I am suppose to have a button there asking write a timeout that asks users if they want to stop the game if they do not press the Guess button within 10 seconds. They are suppose to pick a number between 1-100.
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Guessing Game</title>
<script type="text/javascript">
while (runAgain == 'y' || runAgain == 'Y')
{
guessedNumber = reader.readDouble("Please pick a number between 1 and 100: ");

while (guessedNumber != randomNumber)
{
if (guessedNumber < randomNumber)
System.out.println("Too low!\nGuess again!");

else if (guessedNumber > randomNumber)
System.out.println("Too high\nGuess again!");

else if (guessedNumber == randomNumber)
System.out.println("You got it!");
}
runAgain = reader.readChar("Play again (y/n)? ");
}
</script>
</head>
<body>
<div id="content">


<h2>JavaScript Guessing Game</h2>
<p>Enter a number between 1 and 100, then press the Guess button.</p>
<form action="myForm" method="post">
<p><input type="text" name="guessgame" />
<input type="hidden" name="eGame" value="1"/>
<input type="submit" value=" Guess" name="submit"/></p>
</form>
</body>
</html>

Game Problem

Similar Tutorials View Content
Hi,
i made a game,where you controll a paddle to bounce back a ball and it hits the bricks on top.
The problem is that my eventhandlers don't work after i've added delay function,to make a counter(counting from 3 to 1 before game starts).
Any tips?Is it scope problem?

Code:
var ballx = 100;
var bally = 100;    //coord x and y,radius of a ball
var ballr = 10;
var recx;
var recy;           //coord x and y,width and height of a paddle
var recw = 100;
var rech = 15;
var dx = 2;        //x coord step for animated movement of ball
var dy = 2;        //y coord step for animated movement of ball
var rx = 5;        //x coord step for animated movement of paddle
var WIDTH;        //width of main canvas
var HEIGHT;       //height of main canvas
var ctx;               //drawn shape
var leftDown = false;   
var rightDown = false;        //keyboard arrow buttons
var upDown = false;
var downDown = false;
var mouseXmin;
var mouseXmax;
var intervalId;
var bricks;
var NROWS;
var NCOLS;
var BRICKWIDTH;
var BRICKHEIGHT;
var PADDING;
var y=4;

window.addEventListener("load",init,false);               //event for loading main func
window.addEventListener("keydown",buttonpressed,false);   //event for checking if button is pressed
window.addEventListener("keyup",buttonreleased,false);    //event to check if button is released
window.addEventListener("mousemove",mousemoved,false);    //event for controlling paddle with mouse movement

function init_mouse(){    //initialize coord for mouse movement

mouseXmin = document.getElementById('can').offsetLeft;
mouseXmax = mouseXmin + (WIDTH-recw);             //doesn't work that pretty...check?

}

function init_bricks(){ //initialize bricks

   NROWS = 5;
   NCOLS = 3;
   BRICKWIDTH = (WIDTH/NCOLS) - 1;
   BRICKHEIGHT = 15;
   PADDING = 1;
   
   bricks = new Array(NROWS);
   for(i=0; i<NROWS; i++){
      bricks[i] = new Array(NCOLS);
	  for(j=0; j<NCOLS; j++){
	     bricks[i][j] = 1;
      }
   } 
}

function mousemoved(e){    //function that enables movement of paddle with mouse

if(e.pageX > mouseXmin && e.pageX < mouseXmax) recx = e.pageX ;//- mouseXmin; <---why would you need that?Movement is bugyy! FIX:)

}

function buttonpressed(e){                 //to check if any of keyboard arrow buttons are pressed
                                           
if(e.which==37) { leftDown = true; }
if(e.which==39) { rightDown = true; }
if(e.which==40) { upDown = true; }
if(e.which==38) { downDown = true; }

}

function buttonreleased(e){             //function to check if button up,down,left or right is released
                                         
if(e.which==37) { leftDown = false; }
if(e.which==39) { rightDown = false; }
if(e.which==40) { upDown = false; }
if(e.which==38) { downDown = false; }

}

function clear(){                     //function to clear the stage

ctx.clearRect(0,0,800,600);

}

function circle(x,y,r){               //function to draw circle shape

ctx.beginPath();
ctx.arc(x,y,r,0,Math.PI*2,true);
ctx.closePath();
ctx.fill();

}

function rect(x,y,w,h){     //function to draw rectangle shape

ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();

}

function checkforCoallision(){  //checks for borders of main canvas and if ball hits the paddle

if(ballx + dx > WIDTH-ballr || ballx + dx < ballr) dx = -dx;           
if(bally + dy < ballr ) dy = -dy;
else if (bally + dy > HEIGHT - ballr){
        if(ballx +  ballr > recx && ballx + ballr < recx + recw)
		   dy = -dy;
		else {clearInterval(intervalId); alert('Game Over,Baby!');} bounce();}

}

function draw(){           //function that draws the desired shapes and animates them

clear();                  //clears the main canvas,so the animation would look smooth

checkforCoallision();    //checks for borders of main canvas and if ball hits the paddle
		
if(leftDown) recx -= rx;                                //enables movement of paddle right and left
if(rightDown) recx += rx;

for(i=0; i<NROWS; i++){              //drawing bricks
   for(j=0; j<NCOLS; j++){
      if(bricks[i][j] == 1) {         //checking if brick exists
         rect(j * (BRICKWIDTH+PADDING)+PADDING,i * (BRICKHEIGHT+PADDING) + PADDING, BRICKWIDTH, BRICKHEIGHT)
	  }  
   }
}

//have we hit a brick?
  rowheight = BRICKHEIGHT + PADDING;
  colwidth = BRICKWIDTH + PADDING;
  row = Math.floor(bally/rowheight);
  col = Math.floor(ballx/colwidth);
  //if so, reverse the ball and mark the brick as broken
  if (bally < NROWS * rowheight && row >= 0 && col >= 0 && bricks[row][col] == 1) {
    dy = -dy;
    bricks[row][col] = 0;
  }

circle(ballx,bally,ballr);
rect(recx,recy,recw,rech);

ballx += dx;
bally += dy;

}



/* function init(){
ctx = document.getElementById('can').getContext('2d');
WIDTH = document.getElementById('can').offsetWidth ;       //gets the width of main canvas
HEIGHT = document.getElementById('can').offsetHeight ;     //gets the height of main canvastto
recx = WIDTH / 2;                                            //setting the coord x of a paddle
recy = HEIGHT - rech;                                      //setting the coord y of a paddle
init_mouse();
init_bricks();
intervalId = setInterval(draw,10);                          //calls draw func on desired interval,which is represented by number next to it
return intervalId;

}  */

function delay() {

if(y<=0) { 
document.getElementById('content2').innerHTML = "<canvas id='can' width='300' height='300'>This text is displayed if your browser does not support HTML5 Canvas.</canvas>";
ctx = document.getElementById('can').getContext('2d');
WIDTH = document.getElementById('can').offsetWidth ;       //gets the width of main canvas
HEIGHT = document.getElementById('can').offsetHeight ;     //gets the height of main canvastto
recx = WIDTH / 2;                                            //setting the coord x of a paddle
recy = HEIGHT - rech;                                      //setting the coord y of a paddle
init_mouse();
init_bricks();
intervalId = setInterval(draw,10);                          //calls draw func on desired interval,which is represented by number next to it
return intervalId;
 }
else { 
        Object = document.getElementById('content2');
		y = y - 1;
		Object.innerHTML = "<div style='text-align:center;width:25em;margin: 0px auto;height:100px;position:absolute;top:50%;margin-top:-50px;'>"+y+"</div>";
			setTimeout("delay()", 1000);}
}


Help With Javascript Simon Says Game

Similar Tutorials View Content
Hey all, I'm trying to code a javascript game for my final project as a mini game within an interactive website, but I'm having some problems since I don't know javascript. It's supposed to be a piano game with a specific pattern to one song (so the game has the same pattern everytime) and I can't get it to work. This is my code right now (I started working with a code I found online). I'm really struggling, if anyone has any ideas on what I'm doing wrong it would be greatly appreciated!

Code:

<SCRIPT LANGUAGE="JavaScript">
<!-- Original:  Brian Gosselin (bgaudiodr@aol.com) -->
<!-- Web Site:  http://www.bgaudiodr.iwarp.com -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://www.javascriptsource.com -->


<!-- Begin
var image_directory = "http://www.your-web-site-address-here.com/simon-says-pics/";
var ok = false; 
var pcbusy = false; 
var userturn = true;
var butdown = false;
var stage = 1;
var cnt = 1;
var pcclicks = new Array();
var userclicks = new Array();
var pos;
var tst = true;
var msg = "Click Go!";
btn1 = new Image();
btn1.src = image_directory + "purple.gif";
btn2 = new Image();
btn2.src = image_directory + "yellow.gif";
function updown(isdn) {
if (isdn) {
document.f[('pl'+pos)].src = image_directory + 'yellow.gif';
}
else {
document.f[('pl'+pos)].src= image_directory + 'purple.gif';
   }
}
function getPattern() {
  if(stage=1)
    return new Array(1);
  if(stage=2)
   return new Array(1,2);
  if(stage=3)
   return new Array(1,2,3);
  if(stage=4)
   return new Array(1,2,3,4);
  if(stage=5)
   return new Array(1,2,3,4,5);
  if(stage=6)
   return new Array(1,2,3,4,5,6);
  else
    return new Array(1,2,3,4,5,6,7);
}
function dopc() {
document.f.st.value = stage;
if (cnt <= stage) {
pcbusy = true;
userturn = false;
document.f.s.value = getPattern()[0];
pos=getPattern()[cnt - 1];
setTimeout("updown(true)",500);
setTimeout("updown(false) ; pcclicks[cnt]=pos; cnt++; dopc()",1200);
}
else {
userclicks = new Array();
cnt = 1;
document.f.s.value = "Player's  Turn";
pcbusy = false;
userturn = true;
document.f.b.focus();
   }
}
function testclicks() {
tst = true;
for(i = 1;cnt > i; i++) {
if (pcclicks[i] == userclicks[i]) {
tst = true && tst;
}
else {
tst = false && tst;
   }
}
if(tst) {
setTimeout("stage++ ; document.f.st.value=stage ; alert('That is correct!  Advancing to the next level....'); document.f.s.value=msg ; document.f.b.focus()",300);
}
else {
setTimeout("stage=1 ; cnt=1 ; pcclicks=new Array() ; document.f.st.value=stage ; alert('Sorry, that is not correct.  Start a new game if you would like to play again.') ; document.f.s.value=msg",300);
}
cnt = 1;
}
function testclk(downflag, pos) {
if (userturn&&(!pcbusy)) {
if (downflag) {
document.f[('pl'+pos)].src = image_directory + 'yellow.gif';
}else{
document.f[('pl'+pos)].src = image_directory + 'purple.gif';
}
if (ok && !downflag) {
userclicks[cnt] = pos;
cnt++;
if (pcclicks.length == userclicks.length) {
testclicks();
         }
      }
   }
}
//  End -->
</script>
</HEAD>

<!-- STEP TWO: Copy this code into the BODY of your HTML document  -->


<BODY>

<embed src="G#.wav" autostart="false" hidden="true" name="sound1" enablejavascript="true">	

<!-- <a href="#" onclick="playSound('G#.wav');"></a> !-->

<img src="piano.png" />

<center>
<form name="f">
<table cellspacing="20" cols="8" width="600">
<tr height="60">
<td align="center" width="20%"><img src="purple.gif" onclick="playsound('G#.wav')"; name="1" onMousedown="testclk(true,1)" onMouseup="testclk(false,1)"></td>
<td align="center" width="20%"><img src="purple.gif" name="2" onMousedown="testclk(true,2)" onMouseup="testclk(false,2)"></td>
<td align="center" width="20%"><img src="purple.gif" name="3" onMousedown="testclk(true,3)" onMouseup="testclk(false,3)"></td>
<td align="center" width="20%"><img src="purple.gif" name="4" onMousedown="testclk(true,4)" onMouseup="testclk(false,4)"></td>
<td align="center" width="20%"><img src="purple.gif" name="5" onMousedown="testclk(true,5)" onMouseup="testclk(false,5)"></td>
<td align="center" width="20%"><img src="purple.gif" name="6" onMousedown="testclk(true,6)" onMouseup="testclk(false,6)"></td>
<td align="center" width="20%"><img src="purple.gif" name="7" onMousedown="testclk(true,7)" onMouseup="testclk(false,7)"></td>
<td align="center" width="20%"><img src="purple.gif" name="8" onMousedown="testclk(true,8)" onMouseup="testclk(false,8)"></td>

</tr>
<tr height = 60>
<td width="20%" align="center"><font size="3">Level<br></font><input type="text" size="2" value="1" name="st" readonly></td>
<td align="center" colspan="3"><input type="text"  name="s" value="Click 'Go!' to start" readonly></td>
<td align="center"><input type="button" value="    Go!    " name="b" onClick="ok=true ; if(!pcbusy) dopc()"></td>
</tr>
</table>
</form>
</center>

<p><center>
<font face="arial, helvetica" size="-2">Free JavaScripts provided<br/>
by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
</center><p>

<!-- Script Size:  4.21 KB -->


Js Numeric Guessing Game

Similar Tutorials View Content
Absolutely nothing happens when I click on the button, and I know NOTHING about Java. Need serious help!

The user is supposed to arbitrarily type a number (1-5) and see if it's the same one that JavaScript generates. The function "secretNum" is supposed to be a global variable, but I don't have a clue as to what that means. Anyways, an alert should pop up saying either congrats or try again.

Code:
<html>
<head>
<title>Guessing Game</title>
<script type="text/javascript">
function setUp ()
{
   secretNum = 1+Math.floor(5*Math.random());
   alert = (secretNum);
}

function checkGuess ()
{
	userGuess = document.IfForm.guessBox.value;
	userGuess = parseFloat(userGuess);
	// get value from text box

	if (secretNum == userGuess)
		  {alert ("Correct!");}
	else
		  {alert ("Sorry, Try Again");} 
}
</script>
</head>

<body style="text-align:center" onLoad="setUp();">
<h2>Guess the Number From 1 to 5</h2>
		<form name="IfForm">
Enter Your Guess:
<input type="text" size="5" name="guessBox" value="" />
<br />
<input type="button" value="Check Guess" onClick="checkGuess" />
		</form>
</body>
</html>


Game Making With Javascript?

Similar Tutorials View Content
can u like make games like pong wikth javascript? my friend said he did, but i dont think u can.

Forms In Javascript Game

Similar Tutorials View Content
Hello, this is my first post here, but I'm having some trouble figuring out what I messed up on my code

I'm making a Javascript game of Hangman for one of my classes and I originally had the input as a text box where you physically type in the letter and if it was wrong, it would draw the next sequence of the hangman picture and place the letter in another text box as a "Used Letters," or if you're right, it would place the letter you chose in the box for the word you're guessing. However, I decided that instead of doing that, I wanted to make it more visually appealing and add buttons with the letters on them instead. As you can see in the code which is down-loadable here (the one with the _2 is the one I'm currently using, but the original is supplied as well), the buttons register for the picture changing, but do not register for the "Used Letters" field or for filling in the actual word. One of the button's values is also replaced by "undefined" after each click of another button and I'm not really sure why

If anyone could take a look at my code and see if you can figure out what the deal is, that'd be awesome!

Game Engine Question..

Similar Tutorials View Content
I'm trying to build a small chess like gaming engine, and i'm wondering what soulution would be better. To try and create the whole board in javascript, or to use flash instead!

Problem is that is that i kinda don't have money to buy adobe/macromedia/flash but javascript could be a bit more difficult couse of browser limitations..

How To Creat Puzzle Game

Similar Tutorials View Content
how to empty one of the cells and identify the adjacent cells (the ones with which the empty cell could swap on the first move.)
Code:
<script type="text/javascript">
<!--
		var img_name = new Array("vinnpt1.jpg","vinnpt2.jpg","vinnpt3.jpg","vinnpt4.jpg","vinnpt5.jpg","vinnpt6.jpg","vinnpt7.jpg","vinnpt8.jpg");
		img_name.sort(function() {return 0.5 - Math.random()})
   document.write('<table border="1"><tbody>');
   document.write('<tr>');
   document.write('<td height="200" width="300">');
   document.write('<img src ='+img_name[0]+'/>');
   document.write('</td>');
   document.write('<td height="200" width="300">');
   document.write('<img src ='+img_name[1]+'/>');
   document.write('</td>');
   document.write('<td height="200" width="300">');
   document.write('<img src ='+img_name[2]+'/>');
   document.write('</td>');
   document.write('</tr>');

   document.write('<tr>');
   document.write('<td height="200" width="300">');
   document.write('<img src ='+img_name[3]+'/>');
   document.write('</td>');
   document.write('<td height="200" width="300">');
   document.write('<img src ='+img_name[4]+'/>');
   document.write('</td>');
   document.write('<td height="200" width="300">');
   document.write('<img src ='+img_name[5]+'/>');
   document.write('</td>');
   document.write('</tr>');

   document.write('<tr>');
   document.write('<td height="200" width="300">');
   document.write('<img src ='+img_name[6]+'/>');
   document.write('</td>');
   document.write('<td height="200" width="300">');
   document.write('<img src ='+img_name[7]+'/>');
   document.write('</td>');
   document.write('<td height="200" width="300">');
   document.write('<img src ='+img_name[8]+'/>');
   document.write('</td>');
   document.write('</tr>');

   document.write('</tbody></table>');
   document.write('<table border="2"><tbody><tr><td height="50" width="452">Moves Used Goes Here</td><td height="50" width="452">Last Move Goes Here</td></tr></tbody></table>');
//-->

</script>


Privacy