Solved

JavaScript Game, Only Plays Once....

Posted on 1998-04-04
8
297 Views
Last Modified: 2006-11-17
I have a Tic-Tac-Toe game on my homepage, it only plays one game...then it gives you the alert saying "You win!" all the time after that.  You can find the working model here:

http://www.geocities.com/SiliconValley/Way/9180/ttt.html

Here is the script for that game is below, can someone please fix the script properly and email it to me...or leave the revised script as a comment on here please?:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD>
<TITLE>My Home On The Web</TITLE>
<SCRIPT LNAGUAGE="JavaScript">

<!--
// This script was writteb by Michael Lauzon, (C) 1997
// and not to be used without the express consent from
// its author: ce940@freenet.toronto.on.ca
var row = 0;
var col = 0;
var playerSymbol = "X";
var computerSymbol = "O";
board = new createArray(3,3);

function createArray(row,col) {
  var index = 0;
  this.length = (row * 10) + col;
  for (var x = 1; x <= row; x++) {
    for (var y = 1; y <= col; y++) {
      index = (x*10) + y;
      this[index] = "";
    }
  }
}

function buildBoard(form) {
  var index = 0;
  for (var field = 0; field <= 8; field++) {
    index = eval(form.elements[field].name);
    form.elements[field].value = board[index];
  }
}

function clearBoard(form) {
  var index = 0;
  for (var field = 0; field <= 8; field++) {
    form.elements[field].value = "";
    index = eval(form.elements[field].name);
    board[index];
  }
}

function win(index) {
  var win = false;

  // Check rows.

  if ((board[index] == board[(index < 30) ? index + 10 : index - 20]) && (board[index] == board[(index > 11) ? index - 10 : index + 20])) {
    win = true;
  }

  // Check columns.

  if ((board[index] == board[(index%10 < 3) ? index + 1 : index - 2]) && (board[index] == board[(index%10 > 1) ? index - 1 : index + 2])) {
    win = true;
  }

  // Check diagonals.

  if (Math.round(index/10) == index%10) {
    if ((board[index] == board[(index < 30) ? index + 11 : index - 22]) && (board[index] == board[(index > 11) ? index - 11 : index + 22])) {
      win = true;
    }
    if (index == 22) {
      if ((board[index] == board[13]) && (board[index] == board[31])) {
        win = true;
      }
     }
  }
  if ((index == 31) || (index == 13)) {
    if ((board[index] == board[(index < 30) ? index + 9 : index - 18]) && (board[index] == board[(index > 11) ? index - 9 : index + 18])) {
      win = true;
    }
  }

  // Return with results.

  return win;
}

function play(form,field) {
  var index = eval(field.name);
  var playIndex = 0;
  var winIndex = 0;
  var done = false;
  field.value = playerSymbol;
  board[index] = playerSymbol;

  // Check for player win.

  if (win(index)) {

    // Player won.

    alert("Good play!  You win!");
    clearBoard(form);
  } else {

    // Player lost, check for winning position.

    for (row = 1; row <= 3; row++) {
      for (col = 1; col <= 3; col++) {
        index = (row*10) + col;
        if (board[index] == "") {
          board[index] = computerSymbol;
          if (win(index)) {
            playIndex = index;
            done = true;
            board[index] = "";
            break;
          }
          board[index] = "";
        }
      }
      if (done) {
        break;
      }
  }

  // Check if computer can win.

  if (done) {
    board[playIndex] = computerSymbol;
    buildBoard(form);
    alert("Computer won!  You lose!");
    clearBoard(form);
  } else {

    // Can't win, check if need to stop a win.

    for (row = 1; row <= 3; row++) {
      for (col = 1; col <= 3; col++) {
        index = (row*10) + col;
        if (board[index] == "") {
          board[index] = playerSymbol;
          if (win(index)) {
            playIndex = index;
            done = true;
            board[index] = "";
            break;
          }
          board[index] = "";
        }
      }
      if (done) {
        break;
      }
  }

  // Check if done.

  if (done) {
    board[playIndex] = computerSymbol;
    buildBoard(form);
  } else {

    // Not done, check for first empty space.

    for (row = 1; row <= 3; row++) {
      for (col = 1; col <= 3; col++) {
        index = (row*10) + col;
        if (board[index] == "") {
          playIndex = index;
          done = true;
          break;
        }
      }
      if (done) {
        break;
      }
    }
    board[playIndex] = computerSymbol;
    buildBoard(form);
} } } }

// -->

</SCRIPT>
</HEAD>
<BODY BGCOLOR="WHITE" TEXT="BLACK" LINK="GREEN" ALINK="YELLOW" VLINK="RED">
<CENTER>
<H1>Tic-Tac-Toe</H1>
<BR><BR>
<FORM METHOD="POST">
<TABLE>
<TR>
<TD>
<INPUT TYPE="text" SIZE="3" NAME="11" onFocus="if (this.value != '') {blur();}" onChange="play(this.form,this);">
</TD>
<TD>
<INPUT TYPE="text" SIZE="3" NAME="12" onFocus="if (this.value != '') {blur();}" onChange="play(this.form,this);">
</TD>
<TD>
<INPUT TYPE="text" SIZE="3" NAME="13" onFocus="if (this.value != '') {blur();}" onChange="play(this.form,this);">
</TD>
</TR>
<TR>
<TD>
<INPUT TYPE="text" SIZE="3" NAME="21" onFocus="if (this.value != '') {blur();}" onChange="play(this.form,this);">
</TD>
<TD>
<INPUT TYPE="text" SIZE="3" NAME="22" onFocus="if (this.value != '') {blur();}" onChange="play(this.form,this);">
</TD>
<TD>
<INPUT TYPE="text" SIZE="3" NAME="23" onFocus="if (this.value != '') {blur();}" onChange="play(this.form,this);">
</TD>
</TR>
<TR>
<TD>
<INPUT TYPE="text" SIZE="3" NAME="31" onFocus="if (this.value != '') {blur();}" onChange="play(this.form,this);">
</TD>
<TD>
<INPUT TYPE="text" SIZE="3" NAME="32" onFocus="if (this.value != '') {blur();}" onChange="play(this.form,this);">
</TD>
<TD>
<INPUT TYPE="text" SIZE="3" NAME="33" onFocus="if (this.value != '') {blur();}" onChange="play(this.form,this);">
</TD>
</TR>
</TABLE>
<INPUT TYPE="button" VALUE="I'm done!  Your go!"><BR>
<INPUT TYPE="button" VALUE="Start over!" onClick="clearBoard(this.form);">
</FORM>
</CENTER>
</BODY>
</HTML>
0
Comment
Question by:CyberMage
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 5

Expert Comment

by:julio011597
ID: 1279030
Hello CyberMage,

i must apologize in advance, since i didn't like the code and rewrote it almost from scrach.
So i won't submit an answer, because you were just asking for a fix... but, if you like it please let me know, and i'll lock this question.

BTW, there's a little game here too: i'll submit a code with a BUG in it!!

If you'll be able to fix it yourself, then i will renounce to the points and let you use it as you prefer; if you are not able (or don't feel like) to fix it, then i want 200 points, an A grade, and my name in the author comment at the beginning of the script.

Enjoy ;-) (hope you don't mind this little game)
0
 
LVL 5

Expert Comment

by:julio011597
ID: 1279031
(warning: cut-and-paste from this table may cause troubles)

--//--
<HTML>
  <HEAD>
    <TITLE>My Home On The Web</TITLE>
      <SCRIPT LANGUAGE="JavaScript"><!--
        /* This script was writteb by Julio...(etc.) */

        var playerSymbol = " X";
        var computerSymbol = " O";

        var voidMove = 0;
        var playerMove = 1;
        var computerMove = 2;
        var canMove;

        /* the board array mapping:
         *
         *  0 | 1 | 2
         *  ---------
         *  3 | 4 | 5
         *  ---------
         *  6 | 7 | 8
         */
        var board = new Array(9);

        /* to keep track of empty slots remaining */
        var voidSlots = new Array(9);
        function rmv(elVal) {
          for(var i=0; i<this.length; i++)
            if(this[i] == elVal) {
              this.splice(i, 1);
              break;
            }
          return this.length;
        }
        voidSlots.remove = rmv;


        function initBoard(aForm) {
          for(var i=0; i<9; i++) {
            aForm.elements[i].value = "";
            board[i] = voidMove;
            voidSlots[i] = i;
            canMove = true;
          }
        }

        function doFocus(aField) {
          if(!canMove) return;
          if(aField.value == "") {
            aField.value = playerSymbol;
            setTimeout(Play, 10, aField.form, aField.name);
          }
          aField.blur();
        }

        function Play(aForm, aName) {
          var i, idx = eval(aName);
          var vsCount;

          // Check for player win
          if(isWin(idx, playerMove)) {
            canMove = false;
            self.alert("Good play!  You win!");
            return;
          }

          // Process player move
          board[idx] = playerMove;
          vsCount = voidSlots.remove(idx);

          // Check for draw
          if(vsCount == 0) {
            canMove = false;
            self.alert("So, you cannot beat computer!");
            return;
          }

          // Check for computer winning position
          for(i=0; i<vsCount; i++) {
            idx = voidSlots[i];
            if(board[idx] == voidMove)
              if(isWin(idx, computerMove)) {
                canMove = false;
                aForm.elements["" + idx].value = computerSymbol;
                self.alert("Computer won!  You lose!");
                return;
              }
          }

          // Check if need to stop a win
          for(i=0; i<vsCount; i++) {
            idx = voidSlots[i];
            if(board[idx] == voidMove)
              if(isWin(idx, playerMove)) {
                aForm.elements["" + idx].value = computerSymbol;
                board[idx] = computerMove;
                voidSlots.remove(idx);
                return;
              }
          }

          // Fill first empty space
          idx = voidSlots[0];
          aForm.elements["" + idx].value = computerSymbol;
          board[idx] = computerMove;
          voidSlots.remove(idx);
        }

        function isWin(index, aMove) {
          // Check row
          if(board[(index % 3 == 0) ? index+2 : index-1] == aMove &&
             board[((index+1) % 3 == 0) ? index-2 : index+1] == aMove)
            return true;

          // Check column
          if(board[(index < 3) ? index+6 : index-3] == aMove &&
             board[(index > 5) ? index-6 : index+3] == aMove)
            return true;

          // Check diagonal 0-4-8
          if(index % 4 == 0)
            if(board[index == 0 ? 8 : index-4] == aMove &&
               board[index == 8 ? 0 : index+4] == aMove)
              return true;

          // Check diagonal 2-4-6 (treat them as 0-2-4)
          if(index > 1 && index < 7) {
            index -= 2;
            if(index % 2 == 0)
              if(board[index == 0 ? 4 : index-2] == aMove &&
                 board[index == 4 ? 0 : index+2] == aMove)
                return true;
          }

          return false;
        }
    // --></SCRIPT>
  </HEAD>
  <BODY BGCOLOR="WHITE" TEXT="BLACK" LINK="GREEN" ALINK="YELLOW" VLINK="RED"
    onLoad="initBoard(document.forms[0])">
    <CENTER>
      <H1>Tic-Tac-Toe</H1><BR><BR>
      <FORM METHOD="POST">
        <TABLE>
          <TR><TD>
            <INPUT TYPE="text" SIZE="3" NAME="0" onFocus="doFocus(this)">
          </TD><TD>
            <INPUT TYPE="text" SIZE="3" NAME="1" onFocus="doFocus(this)">
          </TD><TD>
            <INPUT TYPE="text" SIZE="3" NAME="2" onFocus="doFocus(this)">
          </TD></TR><TR><TD>
            <INPUT TYPE="text" SIZE="3" NAME="3" onFocus="doFocus(this)">
          </TD><TD>
            <INPUT TYPE="text" SIZE="3" NAME="4" onFocus="doFocus(this)">
          </TD><TD>
            <INPUT TYPE="text" SIZE="3" NAME="5" onFocus="doFocus(this)">
          </TD></TR><TR><TD>
            <INPUT TYPE="text" SIZE="3" NAME="6" onFocus="doFocus(this)">
          </TD><TD>
            <INPUT TYPE="text" SIZE="3" NAME="7" onFocus="doFocus(this)">
          </TD><TD>
            <INPUT TYPE="text" SIZE="3" NAME="8" onFocus="doFocus(this)">
          </TD></TR>
        </TABLE>
        <INPUT TYPE="button" VALUE="Start over!" onClick="initBoard(this.form);">
      </FORM>
    </CENTER>
  </BODY>
</HTML>
--//--
0
 
LVL 1

Expert Comment

by:vsinha
ID: 1279032
Required change to fix the problem:

function clearBoard(form) {
  var index = 0;
  for (var field = 0; field <= 8; field++) {
    form.elements[field].value = "";
    index = eval(form.elements[field].name);
    board[index] = "";  //<------ note this was only 'board[index];'
  }
}

not that julio's is wrong or anything, i had written the answer to this a long time back but I forgot to submit it.
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 

Author Comment

by:CyberMage
ID: 1279033
Thank you Vsinha! Julio, sorry...I don't like playing games like that; because if I would have known how to fix the bug myself in my game: don't you think I would have?!
0
 
LVL 5

Expert Comment

by:julio011597
ID: 1279034
Ok. Consider though that the bug doesn't prevent you to try it - indeed, it will work on 90% of the games. So, if you like it, and don't mind giving _100_ points and the author's note (i do care for it), i'll send the fixed version.

Otherwise, never mind... i've had fun here anyway, and this is enough for me.
Just sorry if i made you waste your time.
0
 
LVL 1

Expert Comment

by:vsinha
ID: 1279035
CyberMage I would highly recommend you to try julio's problem (though I haven't had a look at it yet). Trying to find bugs will help you in your programming. I am quite sure julio wouldn't mind giving you hints.

Otherwise, if you want to give me the points let me know and I can place an answer. Also while going through your code, I made some minor changes (which in my view made it better). Let me know if you want to look at them and I can post them also.
0
 
LVL 5

Expert Comment

by:julio011597
ID: 1279036
CyberMage, IMHO, if vsinha has solved your problem - as it seems - he deserves the points... if i were you, vsinha, i'd submit anyway an answer to - at least - get autograded (a C grade within 15 days).

This apart, i'd like to apologies to you both: i didn't mean to mess things up, but i was evedently wrong... i'll be more careful in future, but by now i'm really sorry.

-julio
0
 
LVL 1

Accepted Solution

by:
vsinha earned 100 total points
ID: 1279037
Submitting, as you said julio.

As far as I am concerned, it was in CyberMage's best interests (if he had resources) to look at your soln. and give it a try. Debugging is one thing that always sharpens your programming skills.

Julio, you don't need to apologise to me. The only reason I placed my answer was that I had already done it before and didn't want that work to go for a waste.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Avoid defining the variables in the global scope; trying to define them in a local function scope. Because:   • Look-up is performed every time a variable is accessed.   • Variables are resolved backwards from most specific to least specific scope…
Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question