W3101: Scripting Languages: Javascript -- HW3
Due: Friday, Feb 28 (anytime)
Please name the file as "yourname"-HW3.html with your Javascript code and submit in Courseworks.
-
In this homework you will write a Javascript program that plays TicTacToe.
Here the player will use 'X' and the computer (your program) will use 'O'.
All the squares are initialized to '-'It should have the following:
- A 3x3 global array of buttons, each one reprenting a tile o the game.
- A function to initialize the buttons. This function should do the following:
- Create nine buttons and make them each a child of "body".
- Initialize them and set them as part of the global array of buttons.
- Assign the buttions with some default value, say '-' indicatiing
the tile is blank.
- Assign a unique id to each button. For e.g., button i, j can have
an id id_ij where i and j can take values from 0 to 2 or 1 to 3.
- Give each button the same callback function. This callback function is called
'onClickButton(id)' where id is the id of the button.
- The callback function should do the following:
- Wait for the user to click on any button
- Show an alert box if the button was already used,
by either the user or the computer (your program).
- Assign the button 'X' if the button is available.
- Check if the player won. If so, it should show an alert box
saying the player won and end the game.
That is, your program should show an alert box saying the game is over,
if the user presses any button after that.
- If the game is not over, your program should select an unused
square (button) and place 'O' in it.
- Your program should then check if it won. If so,
it shold show an alert box saying it won and end the program.
If the user presses any button after that, it showld show
an alert box saying the game is over.
- If all the nine squares (buttons) are used an no player
has won, then your program should say the game ended in a tie
and then end the program.
- How smart can you make your program? That is, what square/button
doe it pick during its turn? Does it take the first available tile?
A random square? Something that would make it win the game?
Make it as smart as it possible. It need NOT be perfect,
but it should be a little smarter than picking a random square
or the first possible free square.