Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions 03week/ticTacToe.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,22 +25,116 @@ function printBoard() {

function horizontalWin() {
// Your code here
if (board[0][0] != " " && board[0][0] == board[0][1] && board[0][2]==board[0][0]){
return true;
}
if (board[1][0] != " " && board[1][0] == board[1][1] && board[1][2]==board[1][0]){
return true;
}
if (board[2][0] != " " && board[2][0] == board[2][1] && board[2][2]==board[2][0]){
return true;
}

}

function verticalWin() {
// Your code here
if (board[0][0] != " " && board[0][0] == board[1][0] && board[2][0]==board[0][0]){

return true;
}
if (board[0][1] != " " && board[0][1] == board[1][1] && board[2][1]==board[0][1]){

return true;
}
if (board[0][2] != " " && board[0][2] == board[1][2] && board[2][2]==board[0][2]){

return true;
}
}

function diagonalWin() {
// Your code here
if (board[0][0] != " " && board[0][0] == board[1][1] && board[2][2]==board[0][0]){
return true;
}
if (board[0][2] != " " && board[0][2] == board[1][1] && board[2][0]==board[0][2]){
return true;
}
}

function checkForWin() {
// Your code here
return horizontalWin() || verticalWin() || diagonalWin();
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perfect use of using forEach() and fill() methods

const resetGame=()=>{
board.forEach(element => {
element.fill(" ");
});
playerTurn = 'X';
}

const isValid =(row, column)=>{
if(row == '0' || row == '1' || row == '2'){
if(column == '0' || column == '1' || column == '2'){
return true;
}
}
};

const isEmpty =(row, column)=>{
if(board[row][column] == ' '){
return true;
}
};

const draw =()=>{
for(let i = 0; i < board.length; i++){
if (board[i].includes(' ')){
return false;
}
}
return true;
};

function ticTacToe(row, column) {
// Your code here
// user selelects position on the board to place their mark
// make sure it is a valid pick, isValid() T/F
// make sure the place is empty, isEmpty() T/F
// put the mark
// check win, checkForWin()
// swich user, swithUser()
// check for draw, checkForDraw()
if (isValid(row, column)){
if (isEmpty(row, column)){
board[row][column] = playerTurn;
if (checkForWin()){
console.log(playerTurn + ' Wins!');
resetGame();
}else{
if (draw()){
console.log('Draw! No One Wins, Restart Game');
resetGame();
}else{
switchPlayer()
}
}
}else{
console.log('Pick An Empty Space')
}
}else{
console.log('Enter Valid Entry!')
}
}

const switchPlayer =()=>{
if(playerTurn == 'X'){
playerTurn = 'O';
}else{
playerTurn = 'X';
}
}

function getPrompt() {
Expand Down