In: Computer Science
Provided is code for checking horizontal and vertical win in a tic tac toe game. Please provide code for checking diagonal win.
function checkWinVertical(player, row, col) {
var counter = 0; //each button
var btn = document.getElementsByTagName("button");
for (counterC = 0; counterC < col; counterC++){
for (countR = 0; countR < row; countR++){
if (player != btn[counter].innerHTML){
counter += 1;
break;
}
else if (countR + 1 == col)
{
for (countW = 0; countW < col; countW++){
btn[counter - row * countW].setAttribute("class",
"winClass");
}
alert("You Won");
}
else{
counter += row;
}
}
}
}
function checkWinHorizontal(player, row, col) {
var counter = 0; //each button
var btn = document.getElementsByTagName("button");
//checkWin for horizontal rows
//check the rows
for (counterR = 0; counterR < row; counterR++){
//check the columns
for (countC = 0; countC < col; countC++){
if (player != btn[counter].innerHTML){
counter += col-countC; //skip buttons in row
break;
}
else if (countC + 1 == col)
{
for (countW = 0; countW < col; countW++){
btn[counter-countW].setAttribute("class", "winClass");
}
alert("You Won");
}
else{
counter++;
}
}
}
}
If we think about the traditional tic-tac-toe board it's look something like hash tag, two parallel vertical lines and two parallel horizontal lines and if we think what we know about java that's really looks exactly like hash symbol so little bit of use of creativity in order to create a game board, let's use 2d array but rather than using numbers or boolean's or things like that so we can come up with something that will look like which made up of dashes some spaces and vertical bars but essentially gets the job done and it is a tic-tac-toe board. here the code in java make you better understanding by step by step would be create a dash a vertical bar another dash another vertical bar and another - and that would be our first row and second row be created with a dash with a vertical bar another dash another vertical bar and then finally another dash, last row is gonna be a little bit different but it's actually gonna be created with a space a vertical bar another space and another vertical bar so this actually gets up something that looks similar to tic-tac-toe board,
import java.util.Random;
import java.util.Scanner;
public class TicTacToe {
static int playerScore = 0;
static int computerScore = 0;
static Scanner input = new Scanner(System.in);
/*
Notes:
_ | _ | _
_ | _ | _
| |
Helpful indices
[0][0] , [0][2] , [0][4]
[1][0] , [1][2] , [1][4]
[2][0] , [2][2] , [2][4]
Player = 1
Computer = 2
*/
public static void main(String [] args){
char [][] gameBoard = {{'_','|','_','|','_'},{'_', '|', '_','|','_'},{' ','|',' ','|',' '}};
printBoard(gameBoard);
boolean gameOver = false;
boolean playAgain = true;
while(playAgain) {
while (!gameOver) {
System.out.println("Welcome to Tic Tac Toe!!");
playerMove(gameBoard);
gameOver = isGameOver(gameBoard);
if (gameOver) {
break;
}
computerMove(gameBoard);
gameOver = isGameOver(gameBoard);
if (gameOver) {
break;
}
}
System.out.println("Player Score: " +playerScore);
System.out.println("Computer Score: "+ computerScore);
System.out.println("Would you like to play again? Y/N");
input.nextLine();
String result = input.nextLine();
switch (result){
case "Y":
case "y":
playAgain = true;
System.out.println("Dope! Let's play again");
resetBoard(gameBoard);
gameOver = false;
printBoard(gameBoard);
break;
case "N":
case "n":
playAgain = false;
System.out.println("Thanks for playing");
break;
default:
break;
}
}
}
public static void printBoard(char [][] gameBoard){
for(char[] row : gameBoard){
for( char c : row){
System.out.print(c);
}
System.out.println();
}
}
public static void updateBoard( int position, int player, char [][] gameBoard){
char character;
if(player==1){
character = 'X';
}else{
character = 'O';
}
switch (position){
case 1:
gameBoard[0][0] = character;
printBoard(gameBoard);
break;
case 2:
gameBoard[0][2] = character;
printBoard(gameBoard);
break;
case 3:
gameBoard[0][4] = character;
printBoard(gameBoard);
break;
case 4:
gameBoard[1][0] = character;
printBoard(gameBoard);
break;
case 5:
gameBoard[1][2] = character;
printBoard(gameBoard);
break;
case 6:
gameBoard[1][4] = character;
printBoard(gameBoard);
break;
case 7:
gameBoard[2][0] = character;
printBoard(gameBoard);
break;
case 8:
gameBoard[2][2] = character;
printBoard(gameBoard);
break;
case 9:
gameBoard[2][4] = character;
printBoard(gameBoard);
break;
default:
break;
}
}
public static void playerMove(char[][] gameBoard){
System.out.println("Please make a move. (1-9)");
int move = input.nextInt();
boolean result = isValidMove(move,gameBoard);
while(!result){
System.out.println("Sorry! Invalid Move. Try again");
move = input.nextInt();
result = isValidMove(move,gameBoard);
}
System.out.println("Player moved at position " + move);
updateBoard(move,1,gameBoard);
}
public static boolean isValidMove(int move, char[][] gameboard){
switch (move){
case 1:
if(gameboard[0][0] == '_'){
return true;
} else{
return false;
}
case 2:
if(gameboard[0][2] == '_'){
return true;
} else{
return false;
}
case 3:
if(gameboard[0][4] == '_'){
return true;
} else{
return false;
}
case 4:
if(gameboard[1][0] == '_'){
return true;
} else{
return false;
}
case 5:
if(gameboard[1][2] == '_'){
return true;
} else{
return false;
}
case 6:
if(gameboard[1][4] == '_'){
return true;
} else{
return false;
}
case 7:
if(gameboard[2][0] == ' '){
return true;
} else{
return false;
}
case 8:
if(gameboard[2][2] == ' '){
return true;
} else{
return false;
}
case 9:
if(gameboard[2][4] == ' '){
return true;
} else{
return false;
}
default:
return false;
}
}
public static void computerMove(char [][] gameBoard){
Random rand = new Random();
int move = rand.nextInt(9)+1;
boolean result = isValidMove(move,gameBoard);
while(!result){
move = rand.nextInt(9)+1;
result = isValidMove(move, gameBoard);
}
System.out.println("Computer moved at position "+ move);
updateBoard(move,2,gameBoard);
}
public static boolean isGameOver(char [][] gameboard){
//Horizontal Win
if(gameboard[0][0] == 'X'&& gameboard[0][2] == 'X' && gameboard [0][4] == 'X' ){
System.out.println("Player Wins");
playerScore++;
return true;
}
if(gameboard[0][0] == 'O'&& gameboard[0][2] == 'O' && gameboard [0][4] == 'O' ){
System.out.println("Computer Wins");
computerScore++;
return true;
}
if(gameboard[1][0] == 'X'&& gameboard[1][2] == 'X' && gameboard [1][4] == 'X' ){
System.out.println("Player Wins");
playerScore++;
return true;
}
if(gameboard[1][0] == 'O'&& gameboard[1][2] == 'O' && gameboard [1][4] == 'O' ){
System.out.println("Computer Wins");
computerScore++;
return true;
}
if(gameboard[2][0] == 'X'&& gameboard[2][2] == 'X' && gameboard [2][4] == 'X' ){
System.out.println("Player Wins");
playerScore++;
return true;
}
if(gameboard[2][0] == 'O'&& gameboard[2][2] == 'O' && gameboard [2][4] == 'O' ) {
System.out.println("Computer Wins");
computerScore++;
return true;
}
//Vertical Wins
if(gameboard[0][0] == 'X'&& gameboard[1][0] == 'X' && gameboard [2][0] == 'X' ){
System.out.println("Player Wins");
playerScore++;
return true;
}
if(gameboard[0][0] == 'O'&& gameboard[1][0] == 'O' && gameboard [2][0] == 'O' ){
System.out.println("Computer Wins");
computerScore++;
return true;
}
if(gameboard[0][2] == 'X'&& gameboard[1][2] == 'X' && gameboard [2][2] == 'X' ){
System.out.println("Player Wins");
playerScore++;
return true;
}
if(gameboard[0][2] == 'O'&& gameboard[1][2] == 'O' && gameboard [2][2] == 'O' ){
System.out.println("Computer Wins");
computerScore++;
return true;
}
if(gameboard[0][4] == 'X'&& gameboard[1][4] == 'X' && gameboard [2][4] == 'X' ){
System.out.println("Player Wins");
playerScore++;
return true;
}
if(gameboard[0][4] == 'O'&& gameboard[1][4] == 'O' && gameboard [2][4] == 'O' ){
System.out.println("Computer Wins");
computerScore++;
return true;
}
//Diagonal Wins
if(gameboard[0][0] == 'X'&& gameboard[1][2] == 'X' && gameboard [2][4] == 'X' ){
System.out.println("Player Wins");
playerScore++;
return true;
}
if(gameboard[0][0] == 'O'&& gameboard[1][2] == 'O' && gameboard [2][4] == 'O' ){
System.out.println("Computer Wins");
computerScore++;
return true;
}
if(gameboard[2][0] == 'X'&& gameboard[1][2] == 'X' && gameboard [0][4] == 'X' ){
System.out.println("Player Wins");
playerScore++;
return true;
}
if(gameboard[2][0] == 'O'&& gameboard[1][2] == 'O' && gameboard [0][4] == 'O' ){
System.out.println("Computer Wins");
computerScore++;
return true;
}
if(gameboard[0][0] != '_' && gameboard[0][2] != '_' && gameboard[0][4] != '_' && gameboard[1][0] !='_'&&
gameboard[1][2] != '_' && gameboard[1][4] != '_' && gameboard[2][0] != ' ' && gameboard[2][2] != ' ' && gameboard[2][4] != ' '){
System.out.println("Its a tie");
return true;
}
return false;}
public static void resetBoard(char [][] gameBoard){
gameBoard[0][0] = '_';
gameBoard[0][2] = '_';
gameBoard[0][4] = '_';
gameBoard[1][0] = '_';
gameBoard[1][2] = '_';
gameBoard[1][4] = '_';
gameBoard[2][0] = ' ';
gameBoard[2][2] = ' ';
gameBoard[2][4] = ' ';
}
}
once execute the program, here the output:
Assing number 1 to 9 to the different positions in the chart array, make sure get player winning or computer winning or we get tie, here we build tic-tac-toe in the console and java with computer player.
For the Javascript Tic Toe Game, using HTML & Javascript, here the HTML code will be,
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe</title>
<style>
*, *::after, *::before {
box-sizing: border-box;
}
:root {
--cell-size: 100px;
--mark-size: calc(var(--cell-size) * .9);
}
body {
margin: 0;
}
.board {
width: 100vw;
height: 100vh;
display: grid;
justify-content: center;
align-content: center;
justify-items: center;
align-items: center;
grid-template-columns: repeat(3, auto)
}
.cell {
width: var(--cell-size);
height: var(--cell-size);
border: 1px solid black;
display: flex;
justify-content: center;
align-items: center;
position: relative;
cursor: pointer;
}
.cell:first-child,
.cell:nth-child(2),
.cell:nth-child(3) {
border-top: none;
}
.cell:nth-child(3n + 1) {
border-left: none;
}
.cell:nth-child(3n + 3) {
border-right: none;
}
.cell:last-child,
.cell:nth-child(8),
.cell:nth-child(7) {
border-bottom: none;
}
.cell.x,
.cell.circle {
cursor: not-allowed;
}
.cell.x::before,
.cell.x::after,
.cell.circle::before {
background-color: black;
}
.board.x .cell:not(.x):not(.circle):hover::before,
.board.x .cell:not(.x):not(.circle):hover::after,
.board.circle .cell:not(.x):not(.circle):hover::before {
background-color: lightgrey;
}
.cell.x::before,
.cell.x::after,
.board.x .cell:not(.x):not(.circle):hover::before,
.board.x .cell:not(.x):not(.circle):hover::after {
content: '';
position: absolute;
width: calc(var(--mark-size) * .15);
height: var(--mark-size);
}
.cell.x::before,
.board.x .cell:not(.x):not(.circle):hover::before {
transform: rotate(45deg);
}
.cell.x::after,
.board.x .cell:not(.x):not(.circle):hover::after {
transform: rotate(-45deg);
}
.cell.circle::before,
.cell.circle::after,
.board.circle .cell:not(.x):not(.circle):hover::before,
.board.circle .cell:not(.x):not(.circle):hover::after {
content: '';
position: absolute;
border-radius: 50%;
}
.cell.circle::before,
.board.circle .cell:not(.x):not(.circle):hover::before {
width: var(--mark-size);
height: var(--mark-size);
}
.cell.circle::after,
.board.circle .cell:not(.x):not(.circle):hover::after {
width: calc(var(--mark-size) * .7);
height: calc(var(--mark-size) * .7);
background-color: white;
}
.winning-message {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, .9);
justify-content: center;
align-items: center;
color: white;
font-size: 5rem;
flex-direction: column;
}
.winning-message button {
font-size: 3rem;
background-color: white;
border: 1px solid black;
padding: .25em .5em;
cursor: pointer;
}
.winning-message button:hover {
background-color: black;
color: white;
border-color: white;
}
.winning-message.show {
display: flex;
}
/* Background Styles Only */
@import url('https://fonts.googleapis.com/css?family=Raleway');
* {
font-family: Raleway;
}
.side-links {
position: absolute;
top: 15px;
right: 15px;
}
.side-link {
display: flex;
align-items: center;
justify-content: center;
text-decoration: none;
margin-bottom: 10px;
color: white;
width: 180px;
padding: 10px 0;
border-radius: 10px;
}
.side-link-youtube {
background-color: red;
}
.side-link-twitter {
background-color: #1DA1F2;
}
.side-link-github {
background-color: #6e5494;
}
.side-link-text {
margin-left: 10px;
font-size: 18px;
}
.side-link-icon {
color: white;
font-size: 30px;
}
</style>
</head>
<body>
<div class="board" id="board">
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
</div>
<div class="winning-message" id="winningMessage">
<div data-winning-message-text></div>
<button id="restartButton">Restart</button>
</div>
</body>
</html>
To run the program, need some operation using javascript code, here the code
const X_CLASS = 'x'
const CIRCLE_CLASS = 'circle'
const WINNING_COMBINATIONS = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
const cellElements = document.querySelectorAll('[data-cell]')
const board = document.getElementById('board')
const winningMessageElement = document.getElementById('winningMessage')
const restartButton = document.getElementById('restartButton')
const winningMessageTextElement = document.querySelector('[data-winning-message-text]')
let circleTurn
startGame()
restartButton.addEventListener('click', startGame)
function startGame() {
circleTurn = false
cellElements.forEach(cell => {
cell.classList.remove(X_CLASS)
cell.classList.remove(CIRCLE_CLASS)
cell.removeEventListener('click', handleClick)
cell.addEventListener('click', handleClick, { once: true })
})
setBoardHoverClass()
winningMessageElement.classList.remove('show')
}
function handleClick(e) {
const cell = e.target
const currentClass = circleTurn ? CIRCLE_CLASS : X_CLASS
placeMark(cell, currentClass)
if (checkWin(currentClass)) {
endGame(false)
} else if (isDraw()) {
endGame(true)
} else {
swapTurns()
setBoardHoverClass()
}
}
function endGame(draw) {
if (draw) {
winningMessageTextElement.innerText = 'Draw!'
} else {
winningMessageTextElement.innerText = `${circleTurn ? "O's" : "X's"} Wins!`
}
winningMessageElement.classList.add('show')
}
function isDraw() {
return [...cellElements].every(cell => {
return cell.classList.contains(X_CLASS) || cell.classList.contains(CIRCLE_CLASS)
})
}
function placeMark(cell, currentClass) {
cell.classList.add(currentClass)
}
function swapTurns() {
circleTurn = !circleTurn
}
function setBoardHoverClass() {
board.classList.remove(X_CLASS)
board.classList.remove(CIRCLE_CLASS)
if (circleTurn) {
board.classList.add(CIRCLE_CLASS)
} else {
board.classList.add(X_CLASS)
}
}
function checkWin(currentClass) {
return WINNING_COMBINATIONS.some(combination => {
return combination.every(index => {
return cellElements[index].classList.contains(currentClass)
})
})
}
Now add javascript code on HTML Page, the complete code will be
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe</title>
<style>
*, *::after, *::before {
box-sizing: border-box;
}
:root {
--cell-size: 100px;
--mark-size: calc(var(--cell-size) * .9);
}
body {
margin: 0;
}
.board {
width: 100vw;
height: 100vh;
display: grid;
justify-content: center;
align-content: center;
justify-items: center;
align-items: center;
grid-template-columns: repeat(3, auto)
}
.cell {
width: var(--cell-size);
height: var(--cell-size);
border: 1px solid black;
display: flex;
justify-content: center;
align-items: center;
position: relative;
cursor: pointer;
}
.cell:first-child,
.cell:nth-child(2),
.cell:nth-child(3) {
border-top: none;
}
.cell:nth-child(3n + 1) {
border-left: none;
}
.cell:nth-child(3n + 3) {
border-right: none;
}
.cell:last-child,
.cell:nth-child(8),
.cell:nth-child(7) {
border-bottom: none;
}
.cell.x,
.cell.circle {
cursor: not-allowed;
}
.cell.x::before,
.cell.x::after,
.cell.circle::before {
background-color: black;
}
.board.x .cell:not(.x):not(.circle):hover::before,
.board.x .cell:not(.x):not(.circle):hover::after,
.board.circle .cell:not(.x):not(.circle):hover::before {
background-color: lightgrey;
}
.cell.x::before,
.cell.x::after,
.board.x .cell:not(.x):not(.circle):hover::before,
.board.x .cell:not(.x):not(.circle):hover::after {
content: '';
position: absolute;
width: calc(var(--mark-size) * .15);
height: var(--mark-size);
}
.cell.x::before,
.board.x .cell:not(.x):not(.circle):hover::before {
transform: rotate(45deg);
}
.cell.x::after,
.board.x .cell:not(.x):not(.circle):hover::after {
transform: rotate(-45deg);
}
.cell.circle::before,
.cell.circle::after,
.board.circle .cell:not(.x):not(.circle):hover::before,
.board.circle .cell:not(.x):not(.circle):hover::after {
content: '';
position: absolute;
border-radius: 50%;
}
.cell.circle::before,
.board.circle .cell:not(.x):not(.circle):hover::before {
width: var(--mark-size);
height: var(--mark-size);
}
.cell.circle::after,
.board.circle .cell:not(.x):not(.circle):hover::after {
width: calc(var(--mark-size) * .7);
height: calc(var(--mark-size) * .7);
background-color: white;
}
.winning-message {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, .9);
justify-content: center;
align-items: center;
color: white;
font-size: 5rem;
flex-direction: column;
}
.winning-message button {
font-size: 3rem;
background-color: white;
border: 1px solid black;
padding: .25em .5em;
cursor: pointer;
}
.winning-message button:hover {
background-color: black;
color: white;
border-color: white;
}
.winning-message.show {
display: flex;
}
/* Background Styles Only */
@import url('https://fonts.googleapis.com/css?family=Raleway');
* {
font-family: Raleway;
}
.side-links {
position: absolute;
top: 15px;
right: 15px;
}
.side-link {
display: flex;
align-items: center;
justify-content: center;
text-decoration: none;
margin-bottom: 10px;
color: white;
width: 180px;
padding: 10px 0;
border-radius: 10px;
}
.side-link-youtube {
background-color: red;
}
.side-link-twitter {
background-color: #1DA1F2;
}
.side-link-github {
background-color: #6e5494;
}
.side-link-text {
margin-left: 10px;
font-size: 18px;
}
.side-link-icon {
color: white;
font-size: 30px;
}
</style>
<script>
const X_CLASS = 'x'
const CIRCLE_CLASS = 'circle'
const WINNING_COMBINATIONS = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
const cellElements = document.querySelectorAll('[data-cell]')
const board = document.getElementById('board')
const winningMessageElement = document.getElementById('winningMessage')
const restartButton = document.getElementById('restartButton')
const winningMessageTextElement = document.querySelector('[data-winning-message-text]')
let circleTurn
startGame()
restartButton.addEventListener('click', startGame)
function startGame() {
circleTurn = false
cellElements.forEach(cell => {
cell.classList.remove(X_CLASS)
cell.classList.remove(CIRCLE_CLASS)
cell.removeEventListener('click', handleClick)
cell.addEventListener('click', handleClick, { once: true })
})
setBoardHoverClass()
winningMessageElement.classList.remove('show')
}
function handleClick(e) {
const cell = e.target
const currentClass = circleTurn ? CIRCLE_CLASS : X_CLASS
placeMark(cell, currentClass)
if (checkWin(currentClass)) {
endGame(false)
} else if (isDraw()) {
endGame(true)
} else {
swapTurns()
setBoardHoverClass()
}
}
function endGame(draw) {
if (draw) {
winningMessageTextElement.innerText = 'Draw!'
} else {
winningMessageTextElement.innerText = `${circleTurn ? "O's" : "X's"} Wins!`
}
winningMessageElement.classList.add('show')
}
function isDraw() {
return [...cellElements].every(cell => {
return cell.classList.contains(X_CLASS) || cell.classList.contains(CIRCLE_CLASS)
})
}
function placeMark(cell, currentClass) {
cell.classList.add(currentClass)
}
function swapTurns() {
circleTurn = !circleTurn
}
function setBoardHoverClass() {
board.classList.remove(X_CLASS)
board.classList.remove(CIRCLE_CLASS)
if (circleTurn) {
board.classList.add(CIRCLE_CLASS)
} else {
board.classList.add(X_CLASS)
}
}
function checkWin(currentClass) {
return WINNING_COMBINATIONS.some(combination => {
return combination.every(index => {
return cellElements[index].classList.contains(currentClass)
})
})
}
</script>
</head>
<body>
<div class="board" id="board">
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
<div class="cell" data-cell></div>
</div>
<div class="winning-message" id="winningMessage">
<div data-winning-message-text></div>
<button id="restartButton">Restart</button>
</div>
</body>
</html>