javascript tic tac toe - javascript

I am trying to build a tic tac toe game but it is not working, what I mean by that is when I click the gameboard, I want the game to start and have my functions accordingly. Now the problem is I want this game to be human vs machine and the machine part(function AI()) is not working properly.
Here's the link codepen
I have all my functions in the "game" function(game ()) which should run when a user clicks on the game-board which is at the end of the js file.
Just try to play the game and you'll understand what I am talking about--weird behaviour and I am scratching my eyes out and still I'm stuck.
I would really appreciate it if anyone could help me. Thanks.
function game(){
symbDisp();
winCheck();
turns += 1;
if (gameEnd == false && turns % 2 == 0) {
AI();
winCheck();
turns += 1;
}
}

AI() function works (more or less). It's actually only the AI that's playing the game. Player moves don't work because you don't tell the symbDisp() function which square was clicked ('this' refers to the document, not the squares)
You could change the eventhandler to form
$('.square').on('click', function() {
game($(this));
});
Inside this anonymous function this refers to the square, as that's the element the event handler was bound to.
Now you also need to pass this square element around a bit by changing your game() and symbDisp() functions to take the element as their arguments and and using that inside symbDisp().
for example:
function game(elem){
symbDisp(elem);
//more stuff
function symbDisp(elem) {
if(elem.text()==='') {
//more stuff
There's also other bugs in your game but I'll leave those for you to tackle.

First symbDisp is receiving window as this instead of the correct td.
change line 10 to
$('.square').on('click', function() { game(this) } );
because of the change you have to pass this to the subfunctions. So make the following changes:
124: function game(ths){
125:
126: symbDisp(ths);
and then change symbDisp to:
function symbDisp (ths) {
if($(ths).text()==='') {
$(ths).text(pTurn);
if(pTurn == player){
pTurn =comp;
}else{
pTurn=player;
}
}
}
There is another error: pTurn is undefined when it first reaches symbDisp function. So change userIcon to:
function userIcon() {
if($(this).attr("id")=="x"){
player = pTurn ="X";
comp ="O";
} else if($(this).attr("id")=="o"){
player = pTurn ="O";
comp ="X";
}
$('#user').fadeOut(1000);
}
see that I setted pTurn when player is setted.
That's it. It should work now. I forked a working version here:
http://codepen.io/anon/pen/oxPyej
Hope it helps

Related

Function is repeating same values multiple times

I am writing some javascript code to create a flashcard system. In this system, a flashcard is displayed to the user and he decides whether the card is difficult or easy. In this way, each card is sorted into two different groups that will be used later. For the following code, arr is the flashcard list while the difficultList and easyList are the two lists. I have also used jquery to run a function according to the class. So, if the button with difficult flashcard is clicked, difficultList is changed. Do note that as of now, the end() function simply logs 'END' to the console. Finally, the text variable used in nothing but an HTML element with id of text whose value is changed to display the question.
function mainFunc() {
if (indexVal > arr.length) {
end();
} else {
console.log(indexVal);
text.innerHTML = arr[indexVal][0];
$(".difficult").click(function () {
indexVal += 1;
difficultList.push(arr[indexVal]);
mainFunc();
})
$(".easy").click(function () {
indexVal += 1;
mainFunc();
easyList.push(arr[indexVal]);
})
}
}
mainFunc();
When the code runs for the first time, everything works fine. But when I click on any of the buttons during second flashcard, an error occurs and the value of indexVal increases by 2 instead of 1, causing some unexpected behaviour. I have made several attempts in debugging the code but to no avail. Any help would be greatly appreciated (the problem with the code, a new solution etc). Thank you!

setInterval triggering faster than set

I am trying to build a dinosaur running game in React much like google chrome's.
My idea is that I will run a function at the exact moment the object is suppose to hit the dinosaur, around 3 seconds
function check4Death() {
if (playerClass !== '') {
console.log('safe')
}
else {
console.log('nope')
clearInterval()
}
}
setInterval(check4Death, 3000)
This function checks to see if the player is currently in the air
As my method of jumping is adding and then removing a class from my playerClass object
function Jump() {
setPlayerClass('jump')
setTimeout(() => {
setPlayerClass('')
}, 500);
}
Instead of the function telling me either safe or nope every three seconds, I get this
I am very confused as to why this is happening, I have a link to my full code here

How to prevent sprite stills moving after resume a scene? Phaser 3

everytime I resume some scene, the main character keeps walking along, because I think it's remember the movement from before the scene was paused. I set the velocity.x and velocity.y to 0 before pause the scene. But doesn't works. Any idea? Thanks!
Here is my code:
function workPopUp (){
this.scene.pause();
this.scene.launch('popup');
this.work.destroy();
}
This is the normal behaivor of velocity:
if (this.cursorKeys.left.isDown)
{
this.kid.setVelocityX(-200);
this.kid.anims.play('left', true);
}
else if (this.cursorKeys.right.isDown)
{
this.kid.setVelocityX(200);
this.kid.anims.play('run', true);
}
else
{
this.kid.setVelocityX(0);
this.kid.anims.play('idle', true);
};
if (this.cursorKeys.up.isDown && this.kid.body.touching.down)
{
this.kid.setVelocityY(-480);
this.kid.anims.play('jump', true);
}
if(this.cursorKeys.up.isDown && this.cursorKeys.right.isDown){
this.kid.anims.play('jump', true);
}else if(this.cursorKeys.up.isDown && this.cursorKeys.left.isDown){
this.kid.anims.play('jump', true);
}
UPDATE
I still don't know why it was happening, so I'd love if someone else could find a better way, but I did find a way to stop it.
In the tutorial I reference below, they had you add a wake function to reset the cursor keys by putting this line into your create:
this.sys.events.on('wake', this.wake, this);
And then this function:
wake: function() {
this.cursors.left.reset();
this.cursors.right.reset();
this.cursors.up.reset();
this.cursors.down.reset();
},
As I said, that didn't work for me. So instead, I set a boolean in my wake function:
wake: function() {
this.sleeping = true;
},
and then in my Update function, I check for the bool and reset the keys there:
update: function (time, delta)
{
if (this.sleeping)
{
this.sleeping = false;
this.cursors.left.reset();
this.cursors.right.reset();
this.cursors.up.reset();
this.cursors.down.reset();
}
Like I said, this works when putting the reset in my wake function didn't. Somewhere between my wake function running and the first update, the cursor was being updated to down, but I can't figure out where.
Hope this helps.
Original Post
I'm having the same problem and I think it's some change in the a recent version of Phaser 3.
I followed this tutorial:
https://gamedevacademy.org/how-to-create-a-turn-based-rpg-in-phaser-3-part-3/
The tutorial mentions having this problem where the sprite is moving after the scene resumes and adding an on wake function to reset the cursor keys. That wasn't working for me.
I downloaded the source code from the tutorial and found it didn't have this issue, but I noticed that the source code comes with a phaser.min.js whereas I was referencing the latest version online in my html file. When I updated the tutorial source code to use the latest version, the issue occurred.
Hope this context helps, I'll continue to troubleshoot and update if I find the issue.
I had similar problem with in my game when pausing and resuming the scene, so if I was pressing a key and paused the game, after resuming the player would continue the movement event if I was not pressing the key anymore.
So this is what I did
in my playScene add an event on pause
this.sys.events.on("pause, () => { this.player.sleep() })
in my player class created a function to reset all the key values that is called whenever the scene is paused
sleep() {
this.keys.left.reset();
this.keys.right.reset();
this.keys.up.reset();
this.keys.down.reset();
this.keys.jump.reset();
this.keys.fire.reset();
}
Probably there is a better way of handling this, but for what I want at the moment it works

Having trouble returning a value from an anonymous function

I am writing a calculator program that allows the user to turn on the calculator by pressing an ON button. This triggers a function that changes the variable calcStatus to true and displays a temporary message. However, if I press the ON button a second time, the same function that displays the temporary message runs even though the value for calcStatus should be true. What am I doing wrong? (I read somewhere that this is called an anonymous function so that might be contributing to the problem)
Also, am I doing this efficiently or is there an entirely better way to write the code I have now?
$(function(){
function main(calcStatus){
if (calcStatus == true) {
// WILL RUN IF CALCULATOR IS ON
}
else {
$('.button_on').click(function(){
calcStatus = true;
$('.screen_text').html("CALC ON");
setTimeout(function(){
$('.screen_text').html("");
}, 500);
return calcStatus;
});
}
}
main(false);
})
Thank you in advance for your help! This is my first time posting a question so hopefully I did it right!

Issue with execution order in javascript

I'm relatively new to javascript so please hold it against me.
I have a bit of code which should give the user a little time to reach the submenu from the base-menu.
My problem is that the code keeps executing in a weird order.
Here is the code:
function onFocusOut() {
var tester = 0;
setTimeout(function(){menuReset(tester)},1000);
}
function menuReset(tester) {
var hoverCheck = function (event) {
alert("#navBase a has focus"); //is fired, but to late...
var tester = event.data.varTester;
var tester = 1;
};
jQuery('#navBase').on('mousemove', 'a', { varTester: tester }, hoverCheck);
jQuery('#navBase').off('mousemove', 'a', { varTester: tester }, hoverCheck);
alert(tester); //This keeps firing first, before the alert in hoverCheck
if(tester == 1){
alert("tester = 1");
return;
}
else {
jQuery('#navBase ul').hide();
jQuery('#navBase').css({'width': ''});
jQuery('#navBaseAnchor').css({
'width': '', 'color': '',
'font-size': '',
'border-bottom-style': '',
'border-bottom-width': '',
'border-bottom-color': ''});
tester = 0;
}
}
Now I keep getting the alert that "tester" is 0, before the hoverCheck function is executed (which should set "tester" to 1) and fires the alert within that function.
Could someone tell me what I'm doing wrong?
I am also fairly new to JS, but should you also be watching out for variable scope errors too?
You have declared tester locally in onFocusOut() and in menuReset(tester), and then called it as a global var outside?
From answers.oreilly.com
LOCAL - Are those that are specific to a function and only work on it.
GLOBAL - Are those that are not defined within a function and may also serve to functions unless the function has not required that
variable.
Nevermind people...
I found a way around it all.
Currently i'm setting a .focus() to the anchor involved on mouseOver. (and of course blur() on mouseleave)
Then it's real easy to check the currently focussed element using document.activeElement.
So problem solved, altough in a bit different way.
alert(tester) is the first line of code that is executing something you notice as a user. The two function calls jQuery().on() and jQuery().off() are only attaching event handlers. If you want to see a "1" in the alert, you have to quickly move your mouse before hoverCheck is executed. But probably you cannot move your hand faster than JavaScript reaching the next line, which is the alert() with tester equals "0".
A little bit different approach would be to set a Javascript timeout() to make the submenu disappear after a certain amount of time if a certain condition isn't met.
Check out this JSFiddle example
Best of luck!

Categories

Resources