How do I check for winner tic tac toe jquery? - javascript

Stuck setting tic tac toe up. I have the board set, turns for players 1 and 2, all box# win possibilities, and some reason it's alerting that player has won even though they didn't. Example player1=x player2=o sq1 && sq2 &&sq3 returns true so x-o-x alerts as winner for player one
$(document).ready(function() {
var player = 1;
$('.box').on('click', function(event) {
alert('add symbol here');
var boxSelected = $(this);
if (boxSelected.hasClass('exes') || boxSelected.hasClass('ohs')) {
alert('You cant do that! Nice try');
} else {
if (player == 1) {
boxSelected.addClass('exes');
if (checkIfPlayerWon('exes')) {
alert('Congrats! Player ' + player + 'has won the game!');
} else {
player = 2;
}
} else {
boxSelected.addClass('ohs');
if (checkIfPlayerWon('ohs')) {
alert('Congrats! Player ' + player + 'has won the game!');
} else {
player = 1;
}
}
}
});
function checkIfPlayerWon(symbol) {
if ($('.sq1').hasClass(symbol) && $('.sq2') && $('.sq3').hasClass(symbol)) {
return true;
} else if ($('.sq4').hasClass(symbol) && $('.sq5') && $('.sq6').hasClass(symbol)) {
return true;
} else if ($('.sq7').hasClass(symbol) && $('.sq8') && $('.sq9').hasClass(symbol)) {
return true;
} else if ($('.sq1').hasClass(symbol) && $('.sq4') && $('.sq7').hasClass(symbol)) {
return true;
} else if ($('.sq2').hasClass(symbol) && $('.sq5') && $('.sq8').hasClass(symbol)) {
return true;
} else if ($('.sq3').hasClass(symbol) && $('.sq6') && $('.sq9').hasClass(symbol)) {
return true;
} else if ($('.sq3').hasClass(symbol) && $('.sq5') && $('.sq7').hasClass(symbol)) {
return true;
} else if ($('.sq1').hasClass(symbol) && $('.sq5') && $('.sq9').hasClass(symbol)) {
return true;
} else if ($('.sq3').hasClass(symbol) && $('.sq5') && $('.sq7').hasClass(symbol)) {
return true;
} else {
return false;
}
}
});

You are missing the hasClass(symbol) on some of the boxes.
Change all:
if ($('.sq1').hasClass(symbol) && $('.sq2') && $('.sq3').hasClass(symbol)) {
return true;
To:
if ($('.sq1').hasClass(symbol) && $('.sq2').hasClass(symbol) && $('.sq3').hasClass(symbol)) {
return true;

Related

How to check if switch is true or not to hide the div?

I have some problem when I check the function validation, I need when checking all the cassis is true hide the parent div * errors message *
var error_pass = false;
$('#pass').focusout(function(){
check_pass();
error_pass = false;
if(error_pass !== true){
console.log('its showing!');
}else{
$('.test').fadeOut('522');
}
});
function check_pass() {
var fpass= $('#pass').val();
switch(error_pass = true){
case(fpass.length < 6 ? $('#pass-error-message3').css('color','red'):$('#pass-error-message3').css('color','green') ):
$('#pass-error-message3').show();
case(fpass.search(/(?=.[a-z])(?=.*[A-Z])/) == -1 ? $('#pass-error-message4').css('color','red') : $('#pass-error-message4').css('color','green')):
$('#pass-error-message4').show();
case(fpass.search(/\d/) == -1 ? $('#pass-error-message2').css('color','red'):$('#pass-error-message2').css('color','green')):
$('#pass-error-message2').show();
default:break;
}
}
Use if else statements like this
function validation() {
var error = false;
if (fpass.length < 6) {
error = true;
$('#pass-error-message3').css('color', 'red').show();
} else {
$('#pass-error-message3').css('color', 'green');
}
if (fpass.search(/(?=.[a-z])(?=.*[A-Z])/) == -1) {
error = true;
$('#pass-error-message4').css('color', 'red').show();
} else {
$('#pass-error-message4').css('color', 'green')
}
if(fpass.search(/\d/) == -1){
error = true;
$('#pass-error-message2').css('color','red').show();
}else{
$('#pass-error-message2').css('color','green');
}
if(error === false){
hideParentDiv(); // Here hide the div
}
}
Much cleaner approach

Can't return a boolean to ionViewCanLeave

I have to show my customized alert(designed by modal) when user want to leave current page. It prompt yes or no buttons. If user click yes, I want to return false(ie shouldn't leave the page). If user click no, I want to return true(ie leave the page).
I've tried lots of solutions, but nothing helped me.
ionViewCanLeave(): boolean {
if (this.operationMode == undefined) {
if (this.cycleMode == "AA") {
if (
this.oroficeLevel != this.oroficeLevelInitial ||
this.name != this.nameInitial ||
this.scheduleMode != this.scheduleModeInitial
) {
let modal = this.modalCtrl.create(AlertPage, {
message: "Save Changes?"
});
modal.onDidDismiss(data => {
if (data == "yes") {
return false;
} else {
return true;
}
});
modal.present();
}
} else if (this.cycleMode == "CC") {
if (
this.oroficeLevel != this.oroficeLevelInitial ||
this.name != this.nameInitial ||
this.scheduleMode != this.scheduleModeInitial
) {
let modal = this.modalCtrl.create(AlertPage, {
message: "Save Changes?"
});
modal.onDidDismiss(data => {
if (data == "yes") {
return false;
} else {
return true;
}
});
modal.present();
}
}
}
}

Tic Tac Toe if no player is a winner?

How would I determine if there's a draw? ( begginer coder problems)
I can identify who's the winner but can't seem to figure out how to implement the draw part! please help
heres my code not the prettiest, let me know how I can improve
var player = 1;
$('.box').on('click', function(event) {
alert('add symbol here');
var boxSelected = $(this);
$("#goAgain").click(function(event) {
location.reload();
});
if (boxSelected.hasClass('exes') || boxSelected.hasClass('ohs')) {
alert('Sorry, that has already been taken!');
} else {
if (player === 1) {
boxSelected.addClass('exes');
if (checkIfPlayerWon('exes')) {
alert('Congrats! Player ' + player + 'has won the game!');
} else {
player = 2;
}
} else {
boxSelected.addClass('ohs');
if (checkIfPlayerWon('ohs')) {
alert('Congrats! Player ' + player + 'has won the game!');
} else {
player = 1;
}
}
}
});
function checkIfPlayerWon(symbol) {
if ($('.sq1').hasClass(symbol) && $('.sq2').hasClass(symbol) && $('.sq3').hasClass(symbol)) {
return true;
} else if ($('.sq4').hasClass(symbol) && $('.sq5').hasClass(symbol) && $('.sq6').hasClass(symbol)) {
return true;
} else if ($('.sq7').hasClass(symbol) && $('.sq8').hasClass(symbol) && $('.sq9').hasClass(symbol)) {
return true;
} else if ($('.sq1').hasClass(symbol) && $('.sq4').hasClass(symbol) && $('.sq7').hasClass(symbol)) {
return true;
} else if ($('.sq2').hasClass(symbol) && $('.sq5').hasClass(symbol) && $('.sq8').hasClass(symbol)) {
return true;
} else if ($('.sq3').hasClass(symbol) && $('.sq6').hasClass(symbol) && $('.sq9').hasClass(symbol)) {
return true;
} else if ($('.sq1').hasClass(symbol) && $('.sq5').hasClass(symbol) && $('.sq9').hasClass(symbol)) {
return true;
} else if ($('.sq3').hasClass(symbol) && $('.sq5').hasClass(symbol) && $('.sq9').hasClass(symbol)) {
return true;
} else {
return false;
}
}
});
If you have a class .square which all the squares have, then you can run a forEach loop over that class like $(.square).forEach(function(){..., which checks if the square is empty. If none of the squares are empty then a boolean game_still_on would be false and from that, after your syncronous loop has completed you would initiate the draw-game routine.

Minimax Tic Tac Toe Javascript game wont play intelligently

Good Afternoon,
can someone please help me figure out why my Tic Tac Toe javascript game wont play intelligently...meaning that it shouldn't let me win. I've spent hours on this and still cant figure it out. Here is the link to my project:
http://codepen.io/tbraden30/pen/WrorjE Thank you so much!
"use-strict"
$(document).ready(function() {
var gameBoard = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
humanPlayer = 'X',
EMPTY = ' ',
computerPlayer = 'O',
currentPlayer = 'computer',
choice;
function buildBoard(board) {
$('td').each(function(index) {
$(this).text(board[index]);
});
}
function makeMove(board, symbol, move) {
board[move] = symbol;
}
function checkWin(board, player) {
return ((board[0] == player && board[1] == player && board[2] == player) || (board[3] == player && board[4] == player && board[5] == player) || (board[6] == player && board[7] == player && board[8] == player) || (board[0] == player && board[3] == player && board[6] == player) || (board[1] == player && board[4] == player && board[7] == player) || (board[0] == player && board[4] == player && board[8] == player) || (board[2] == player && board[4] == player && board[6] == player) || (board[2] == player && board[5] == player && board[8] == player));
}
function boardSpaceOpen(board, move) {
return board[move] == EMPTY;
}
function boardIsFull(board) {
for (var i = 0; i < board.length; i++) {
if (boardSpaceOpen(board, i)) {
return false;
}
}
return true;
}
function resetBoard() {
gameBoard = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '];
buildBoard(gameBoard);
currentPlayer = 'computer';
computerPlay();
}
function computerPlay() {
var moves = getOpenSpaces(gameBoard);
var move = moves[0];
var score = -10000;
for (var i = 0; i < moves.length; i++) {
var newBoard = gameBoard.slice();
newBoard[moves[i]] = computerPlayer;
if (checkWin(computerPlayer, newBoard)) {
move = moves[i];
break;
}
var newScore = minimax(humanPlayer, newBoard);
if (newScore > score) {
score = newScore;
choice = moves[i];
}
}
makeMove(gameBoard, computerPlayer, move);
buildBoard(gameBoard);
if (checkWin(gameBoard, computerPlayer)) {
alert('computer Wins!!');
resetBoard();
} else if (boardIsFull(gameBoard)) {
alert('DRAW!!');
resetBoard();
} else {
currentPlayer = 'human';
}
}
function getOpenSpaces(board) {
var emptySpaces = [];
for (var i = 0; i < board.length; i++) {
if (boardSpaceOpen(board, i)) {
emptySpaces.push(i);
}
}
return emptySpaces;
}
function getOpponentOf(player) {
return currentPlayer == 'computer' ? 'human' : 'computer';
}
function minimax(board, player) {
if (checkWin(board, humanPlayer)) {
return -100
}
if (checkWin(board, computerPlayer)) {
return 100
}
if (boardIsFull(board)) {
return 0;
}
var availableMoves = getOpenSpaces(board);
var scores = availableMoves.map(function(move){
var newBoard = board.slice();
newBoard[move] = player;
return minimax(getOpponentOf(currentPlayer), newBoard);
});
if(currentPlayer == 'computer'){
return Math.max.apply(null,scores);
}
else{
return Math.min.apply(null,scores)
}
}
$('#reset').on('click', function() {
resetBoard();
});
$('.piece').on('click', function() {
humanPlayer = this.id;
computerPlayer = humanPlayer == 'X' ? 'O' : 'X';
computerPlay();
});
$('td').on('click', function() {
if (currentPlayer == 'human') {
var move = this.id;
if (boardSpaceOpen(gameBoard, move)) {
makeMove(gameBoard, humanPlayer, move);
buildBoard(gameBoard);
if (checkWin(gameBoard, humanPlayer)) {
alert('You Won!!');
resetBoard();
} else if (boardIsFull(gameBoard)) {
alert('DRAW!!');
resetBoard();
} else {
currentPlayer = 'computer';
computerPlay();
}
}
}
});
});

Unintended Recursivity - How do I stop or reset a function on click?

I tried making a jsFiddle for this, but it's not working right (I think because of the alerts I have set up to test my code), so hopefully someone can simply look at my JS and see the problem.
The issue is that when you close the div with the form (#verizoni516) and then re-open it, you get as many alerts as times you have closed the div and re-opened it, instead of the ONE alert I'm intending. Does that make any sense?
Here's the JS:
/*--------------Validation Functions-------------------*/
function chkradio() {
var elem = document.forms['vzi5'].elements['element_0'];
len = elem.length - 1;
chkvalue = '';
sevenPlus = false;
fourToSix = false;
threeMin = false;
for (i = 0; i <= len; i++) {
if(elem[i].checked) chkvalue = elem[i].value;
}
if (chkvalue == '') {
$('#radio-error').fadeIn('fast').effect("bounce", {times:3}, 'fast', function(){
setTimeout(function(){
$('#radio-error').fadeOut('slow');}, 2000);
});
}
if (chkvalue >= 7) {
sevenPlus = true;
} else if (chkvalue >= 4 && chkvalue <= 6) {
fourToSix = true;
} else {
threeMin = true;
}
};
function chkselect() {
var elem = document.forms['vzi5'].elements['element_1'];
len = elem.length - 1;
chkvalue = '';
likeNew = false;
minProb = false;
nonFunc = false;
for (i = 0; i <= len; i++) {
if (elem[i].selected) chkvalue = elem[i].value;
}
if (chkvalue == '') {
elem.focus();
$('#select-error').fadeIn('fast').effect("bounce", {times:3}, 'fast', function(){
setTimeout(function(){
$('#select-error').fadeOut('slow');}, 2000);
});
} else if (chkvalue === 'Like New - No Functional Problems') {
likeNew = true;
} else if (chkvalue === 'Minor Functional Problems') {
minProb = true;
} else {
nonFunc = true;
}
};
function chkbox() {
var elem = document.forms['vzi5'].elements['element_2[]'];
chkvalue = elem.checked;
iUnderstand = true;
if (chkvalue === true) {
iUnderstand;
} else {
iUnderstand = false;
elem.focus();
$('#check-error').fadeIn('fast').effect("bounce", {times:3}, 'fast', function(){
setTimeout(function(){
$('#check-error').fadeOut('slow');}, 2000);
});
}
};
//Calling the validation functions---------------------------
$('#verizon img.apple, #unlocked img.apple').click(function(){
$(this).closest('div').fadeOut(500).animate({"top": "-414px"}, 100).fadeIn('fast', function(){
});
$('#verizon516').animate({"top": "+=557px"}, 500, function(){
$(this).animate({"top": "-=20px"}, 200);
});
$('div.next').click(function(){
chkradio();
chkselect();
chkbox();
if (sevenPlus === true) {
if (likeNew === true && iUnderstand === true) {
alert('Condition is 7+ and functions like new.');
} else if (minProb === true && iUnderstand === true) {
alert('Condition is 7+ and has minor functional problems');
} else if (nonFunc === true && iUnderstand === true) {
alert('Condition is 7+ and device does NOT function.');
} else {
};
};
if (fourToSix === true) {
if (likeNew === true && iUnderstand === true) {
alert('Condition is 4-6 and functions like new.');
} else if (minProb === true && iUnderstand === true) {
alert('Condition is 4-6 and has minor functional problems');
} else if (nonFunc === true && iUnderstand === true) {
alert('Condition is 4-6 and device does NOT function.');
} else {
};
};
if (threeMin === true) {
if (likeNew === true && iUnderstand === true) {
alert('Condition is 1-3 and functions like new.');
} else if (minProb === true && iUnderstand === true) {
alert('Condition is 1-3 and has minor functional problems');
} else if (nonFunc === true && iUnderstand === true) {
alert('Condition is 1-3 and device does NOT function.');
} else {
};
};
});
});
Move the div.next click handler out of the other click handler, it will cause a new handler to get registered every time you click on one of the #verizon img.apple, #unlocked img.apple elements which intern gets called one after another.
/*--------------Validation Functions-------------------*/
function chkradio() {
var elem = document.forms['vzi5'].elements['element_0'];
len = elem.length - 1;
chkvalue = '';
sevenPlus = false;
fourToSix = false;
threeMin = false;
for (i = 0; i <= len; i++) {
if (elem[i].checked) chkvalue = elem[i].value;
}
if (chkvalue == '') {
$('#radio-error').fadeIn('fast').effect("bounce", {
times: 3
}, 'fast', function () {
setTimeout(function () {
$('#radio-error').fadeOut('slow');
}, 2000);
});
}
if (chkvalue >= 7) {
sevenPlus = true;
} else if (chkvalue >= 4 && chkvalue <= 6) {
fourToSix = true;
} else {
threeMin = true;
}
};
function chkselect() {
var elem = document.forms['vzi5'].elements['element_1'];
len = elem.length - 1;
chkvalue = '';
likeNew = false;
minProb = false;
nonFunc = false;
for (i = 0; i <= len; i++) {
if (elem[i].selected) chkvalue = elem[i].value;
}
if (chkvalue == '') {
elem.focus();
$('#select-error').fadeIn('fast').effect("bounce", {
times: 3
}, 'fast', function () {
setTimeout(function () {
$('#select-error').fadeOut('slow');
}, 2000);
});
} else if (chkvalue === 'Like New - No Functional Problems') {
likeNew = true;
} else if (chkvalue === 'Minor Functional Problems') {
minProb = true;
} else {
nonFunc = true;
}
};
function chkbox() {
var elem = document.forms['vzi5'].elements['element_2[]'];
chkvalue = elem.checked;
iUnderstand = true;
if (chkvalue === true) {
iUnderstand;
} else {
iUnderstand = false;
elem.focus();
$('#check-error').fadeIn('fast').effect("bounce", {
times: 3
}, 'fast', function () {
setTimeout(function () {
$('#check-error').fadeOut('slow');
}, 2000);
});
}
};
//Calling the validation functions---------------------------
$('#verizon img.apple, #unlocked img.apple').click(function () {
$(this).closest('div').fadeOut(500).animate({
"top": "-414px"
}, 100).fadeIn('fast', function () {});
$('#verizon516').animate({
"top": "+=557px"
}, 500, function () {
$(this).animate({
"top": "-=20px"
}, 200);
});
});
//move this out of the other click handler
$('div.next').click(function () {
chkradio();
chkselect();
chkbox();
if (sevenPlus === true) {
if (likeNew === true && iUnderstand === true) {
alert('Condition is 7+ and functions like new.');
} else if (minProb === true && iUnderstand === true) {
alert('Condition is 7+ and has minor functional problems');
} else if (nonFunc === true && iUnderstand === true) {
alert('Condition is 7+ and device does NOT function.');
} else {
};
};
if (fourToSix === true) {
if (likeNew === true && iUnderstand === true) {
alert('Condition is 4-6 and functions like new.');
} else if (minProb === true && iUnderstand === true) {
alert('Condition is 4-6 and has minor functional problems');
} else if (nonFunc === true && iUnderstand === true) {
alert('Condition is 4-6 and device does NOT function.');
} else {
};
};
if (threeMin === true) {
if (likeNew === true && iUnderstand === true) {
alert('Condition is 1-3 and functions like new.');
} else if (minProb === true && iUnderstand === true) {
alert('Condition is 1-3 and has minor functional problems');
} else if (nonFunc === true && iUnderstand === true) {
alert('Condition is 1-3 and device does NOT function.');
} else {
};
};
});
Demo: Fiddle
This is because you are binding the click event for div.next inside the click event for #verizon img.apple, #unlocked img.apple, so every time the outer event is clicked, you are re-binding the inner click event. Fix this by moving the event binding for div.next outside the click event for #verizon img.apple, #unlocked img.apple
$('#verizon img.apple, #unlocked img.apple').click(function(){
// .. contents here
});
$('div.next').click(function(){
// ... contents here
});
You are binding the click event to $('div.next') every time $('#verizon img.apple, #unlocked img.apple') is clicked. Which means it will fire once for each time it is bound. Move the code for $('div.next') out of the $('#verizon img.apple, #unlocked img.apple') click handler.

Categories