Tic Tac Toe if no player is a winner? - javascript

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.

Related

Skip page timer with tampermonkey

My knowledge is limited, so I'm just praying y'all will enlighten me who knows bare minimum of JS. I want to bypass a timer that makes it unable to go to the next page (I need 35s every single time and that's a lot considering some lessons have over 200 slides). How do I write a script for tampermonkey to make it show the link to the next page instantly?
// Obsługa przycisku Dalej
function goNext(vIsExam) {
// Przycisk nieaktywny - blokada przejścia
if (document.getElementById("pNext").rel != 'enabled') return false;
if (vIsExam==1) {
} else {
location.href='../sql/MemSql.php?pRun=MemCourseGoNext&pCourseResultId=262261&pCourseLessonId=227436';
}
} // function
// Aktywacja przycisku Dalej
function waitNextLesson(vTimeLeft, vTimer) {
setCookie('cLessonTime',vTimeLeft);
if (vTimeLeft > 0) {
document.getElementById('pNext').rel = 'disabled';
document.getElementById('pNextDiv').className = 'CourseInactive';
if (vTimer == 0) {
document.getElementById('pNextIcon').className = 'FontAwesome';
document.getElementById('pNextIcon').innerHTML = vTimeLeft;
} else {
document.getElementById('pNextIcon').className = 'FontAwesome';
document.getElementById('pNextIcon').className = 'FontAwesome FontAwesomeArrowRight';
}
document.getElementById('pNextName').innerHTML = 'CZEKAJ';
vTimeLeft = vTimeLeft - 1;
setTimeout("waitNextLesson("+vTimeLeft+","+vTimer+")",1000);
} else {
document.getElementById('pNext').rel = 'enabled';
document.getElementById('pNextDiv').className = '';
document.getElementById('pNextIcon').className = 'FontAwesome FontAwesomeArrowRight';
document.getElementById('pNextIcon').innerHTML = '';
document.getElementById('pNextName').innerHTML = 'NASTĘPNY SLAJD';
if (document.getElementById('iLessonAutoPlay').checked == true) document.getElementById('pNext').click();
}
} // function
// Obsługa LessonAutoPlay
function jLessonAutoPlay(e) {
setCookie('LessonAutoPlay', document.getElementById('iLessonAutoPlay').checked);
jStopPropagation(e);
} // function
//if (getCookie('LessonAutoPlay') == 'true') document.getElementById('iLessonAutoPlay').checked = true;
// Obsługa skrótów klawiaturowych (strzałka [<] i [>])
$("body").keyup(function(oEvent){
// Sprawdzenie czy można obsługiwać skróty
if (document.getElementById('DIALOG').style.display == 'none' && document.getElementById('LOADER').style.display == 'none') {
// Klawisz [<]
if (oEvent.keyCode == 37) {
document.getElementById("pPrev").click();
}
// Klawisz [>]
if (oEvent.keyCode == 39) {
if (document.getElementById("pNext").rel == 'enabled') {
document.getElementById("pNext").click();
}
}
}
});

How can I make different levels for a game? Would I have to make different classes?

I already have a sketch.js file with some gameStates.
var gameState = "wait";
I added conditional statements such as:
if(gameState == "wait"){
background(backgroundImg);
textSize(50);
fill("blue");
text("Project42 Own",250,400);
startButton.visible = true;
gun.visible = false;
backBoard.visible = false;
}
Below is the code that has level 1, wait, play and end gameState:
function draw() {
if(gameState == "wait"){
background(backgroundImg);
textSize(50);
fill("blue");
text("Project42 Own",250,400);
startButton.visible = true;
gun.visible = false;
backBoard.visible = false;
}
if(mousePressedOver(startButton)&& gameState == "wait"){
gunSound.play();
gunSound.setVolume(0)
gameState = "play";
}
if(gameState == "play"){
background("#BDA297")
fill("red");
textSize(30);
text("Score:" + score + " ",300,100);
fill("green");
text("Life:" + life + " ",800,100)
gun.y=mouseY
startButton.visible = false;
gun.visible = true;
backBoard.visible = true;
if(keyDown("SHIFT")){
shootBullets();
}
if (frameCount % 80 === 0) {
drawBlueBubble();
}
if (frameCount % 100 === 0) {
drawRedBubble();
}
if(blueBubbleGroup.collide(bulletGroup)){
handleBubbleCollision(blueBubbleGroup);
score +=5;
}
if(redBubbleGroup.collide(bulletGroup)){
handleBubbleCollision(redBubbleGroup);
score += 10;
}
if (blueBubbleGroup.collide(backBoard)){
handleGameover(blueBubbleGroup);
}
if (redBubbleGroup.collide(backBoard)) {
handleGameover(redBubbleGroup);
}
}
if (life == 0) {
gameState == "end"
}
if(gameState == "end"){
background(gameOverImg)
redBubbleGroup.hideEverything()
blueBubbleGroup.hideEverything();
}
drawSprites();
}
However, I now want to make level 2 in which there will be more obstacles. Also, I'm not a professional coder so please be clear in your answer.

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

How do I check for winner tic tac toe jquery?

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;

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