I have a big problem with my JavaScript timer. Everything working fine, except 1 button: STOP! I cant figure out how to stop everything on my counter (like reset every input and the counter). Any ideas how can I fix this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Feladat 5</title>
</head>
<body>
<form>
<label>Indulás: </label><input type="number" id="n_start" placeholder="1000"/> <label> (4 számjegyű
szám)</label><br /><br />
<label>Megállás: </label><input type="number" id="n_end" placeholder="1008"/> <label> (4 számjegyű szám)</label><br/><br />
<label>Számolás léptei: </label><input type="number" id="n_count" placeholder="1"/> <br /><br />
<label>Időközönti számolás: </label><input type="number" id="n_timer" placeholder="1"/> <label> (másodpercben)</label><br /><br />
</form>
<label>Számláló: </label><span id="counter">0</span> <br /><br />
<button id="first" type="button" onclick="count()">Start</button>
<button id="pause" type="button" style="display:none;" onclick="show_resume()">Pause</button>
<button id="resume" type="button" style="display:none;" onclick="show_pause()">Resume</button>
<button id="stop" type="button" name="stop">Stop</button>
<script>
function counterLoop(callback, delay)
{
var id
,start
,remaining = delay;
this.pause = function()
{
window.clearTimeout(id);
remaining -= new Date() - start;
};
var resume = function()
{
start = new Date();
id = window.setTimeout(function()
{
remaining = delay;
resume();
callback();
}, remaining);
};
this.resume = resume;
this.resume();
}
function count()
{
var startValue = document.getElementById("n_start").value;
var endValue = document.getElementById("n_end").value;
var countValue = document.getElementById("n_count").value;
var timerValue = document.getElementById("n_timer").value;
var count = startValue;
if (startValue == "" || endValue == "" || countValue == "" || timerValue == "")
{
alert("Minden mező kitöltése kötelező!");
}
else
{
if (startValue < 999 || endValue < 999)
{
alert("Legalább 4 számjegyű kell legyen az érték!")
}
else
{
var math_check = endValue - startValue;
if (math_check % countValue != 0 )
{
alert("A számlálás léptei túl lépnék a megállást.");
}
else
{
var counter = new counterLoop(function ()
{
if (startValue <= endValue)
{
if (countValue == 1)
{
++count;
if (count == endValue )
{
counter.pause();
document.getElementById('pause').style.display = 'none';
document.getElementById('resume').style.display = 'none';
document.getElementById('first').style.display = 'inline';
counter = 0;
}
}
else
{
count = +countValue + +count;
if (count == endValue)
{
counter.pause();
document.getElementById('pause').style.display = 'none';
document.getElementById('resume').style.display = 'none';
document.getElementById('first').style.display = 'inline';
counter = 0;
}
}
}
document.getElementById('counter').innerHTML = count;
}, timerValue * 1000);
document.getElementById('pause').addEventListener('click', function () {
counter.pause()
}, false);
document.getElementById('resume').addEventListener('click', function () {
counter.resume()
}, false);
document.getElementById('pause').style.display = 'inline';
document.getElementById('first').style.display = 'none';
}
}
}
};
function show_resume()
{
document.getElementById('resume').style.display = 'inline';
document.getElementById('pause').style.display = 'none';
}
function show_pause()
{
document.getElementById('resume').style.display = 'none';
document.getElementById('pause').style.display = 'inline';
}
</script>
</body>
</html>
do you want to stop that timer and resume or just stop and reset all the fields?
Related
The code is creating a responsive page. But every time I press stop and then start again the countdown speeds up. Seconds pass like milliseconds and mins pass like seconds after about 10 or so stops and starts. What might be the issue here?
P.S. I haven't written code for the reset button.
let ms = 0;
let secs = 0;
let mins =0;
let flag = true;
var setIntID;
watchFunction =()=> {
if(flag){
ms +=4 ;
document.getElementById('msecs').innerText = `${ms}`;
if(ms == 1000){
ms =0;
secs++
document.getElementById('secs').innerText = `${secs}:`
if(secs == 60){
mins++;
document.getElementById('min').innerText = `${mins}:`;
secs = 0;
}
}}}
document.getElementById("start").addEventListener('click', function(){
flag = true;
var setIntID = setInterval(watchFunction,1);
console.log(flag) //tracker
})
document.getElementById("stop").addEventListener('click', function(){
flag = false;
console.log(flag); //tracker
clearInterval(setIntID);
})
<div id="mainDiv">
<div>
<span id="min">0:</span>
<span id="secs">0:</span>
<span id="msecs">0</span>
<div>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="reset">reset</button>
</div>
</div>
</div>
You have declared setIntID as a local variable in click for the start button, and therefore it isn't cleared in the click function for the stopbutton.
let ms = 0;
let secs = 0;
let mins =0;
let flag = false;
var setIntID;
watchFunction =()=> {
if(flag){
ms +=4 ;
document.getElementById('msecs').innerText = `${ms}`;
if(ms == 1000){
ms =0;
secs++
document.getElementById('secs').innerText = `${secs}:`
if(secs == 60){
mins++;
document.getElementById('min').innerText = `${mins}:`;
secs = 0;
}
}}}
document.getElementById("start").addEventListener('click', function(){
if (flag) return;
flag = true;
setIntID = setInterval(watchFunction,1);
console.log(flag) //tracker
})
document.getElementById("stop").addEventListener('click', function(){
flag = false;
console.log(flag); //tracker
clearInterval(setIntID);
})
<div id="mainDiv">
<div>
<span id="min">0:</span>
<span id="secs">0:</span>
<span id="msecs">0</span>
<div>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="reset">reset</button>
</div>
</div>
</div>
I think that solves the problem.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="mainDiv">
<div>
<span id="min">0:</span>
<span id="secs">0:</span>
<span id="msecs">0</span>
<div>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="reset">reset</button>
</div>
</div>
</div>
<script>
let ms = 0;
let secs = 0;
let mins =0;
let flag = true;
var setIntID;
var running_instance_count = 0;
watchFunction =()=> {
if(flag){
ms +=4 ;
document.getElementById('msecs').innerText = `${ms}`;
if(ms == 1000){
ms =0;
secs++
document.getElementById('secs').innerText = `${secs}:`
if(secs == 60){
mins++;
document.getElementById('min').innerText = `${mins}:`;
secs = 0;
}
}}}
document.getElementById("start").addEventListener('click', function(){
flag = true;
running_instance_count++;
if(running_instance_count == 1){
setIntID = setInterval(watchFunction,1);}
console.log(flag) //tracker
})
document.getElementById("stop").addEventListener('click', function(){
flag = false;
running_instance_count = 0;
console.log(flag); //tracker
clearInterval(setIntID);
})
document.getElementById('reset').addEventListener('click', function(){
flag = false;
ms=0; secs=0; mins=0;
running_instance_count = 0;
clearInterval(setIntID);
document.getElementById('msecs').innerText = `${0}`;
document.getElementById('secs').innerText = `${0}:`;
document.getElementById('min').innerText = `${0}:`;
})
</script>
</body>
</html>
I see a time boost now, but on it's it's first click it's actually slow at ms +=4 so I changed it to ms +=10. Also, there's no usage of the flag on the event handler which would help control the setInterval() and clearInterval() so that there is only one existing at a time. Everytime the "start" button was clicked in OP code there was another setInterval() added, therefore the time intervals combined accelerated. In the example, there's only one event handler that toggles between setInterval() and clearInterval().
let mil = 0;
let sec = 0;
let min = 0;
let flag = false;
let setIntID;
const form = document.forms.stopWatch;
const fc = form.elements;
const timer = () => {
if (flag) {
fc.milliseconds.value = mil += 10;
if (mil == 1000) {
mil = 0;
sec++;
if (sec < 10) sec = '0' + sec;
fc.seconds.value = sec + ' :';
if (sec == 60) {
min++;
if (min < 10) min = '0' + min;
fc.minutes.value = min + ' :';
sec = 0;
}
}
}
}
fc.toggle.addEventListener('click', function() {
if (!flag) {
flag = true;
setIntID = setInterval(timer, 1);
return
}
clearInterval(setIntID);
flag = false;
});
form.onreset = e => {
mil = 0;
sec = 0;
min = 0;
clearInterval(setIntID);
flag = false;
}
<form id="stopWatch">
<fieldset>
<output id="minutes">00 :</output>
<output id="seconds">00 :</output>
<output id="milliseconds">000</output><br>
<button id="toggle" type='button'>Start/Stop</button>
<button type="reset">Reset</button>
</fieldset>
</form>
i have no idea how to save and show out put next to stopwatch:
00:01:30 , 00:01:30 something like this.
its not important but can i make stopwatch to stop on some time like 45 min
i created a button "save" was playing whit code but i have no idea how to make it save output and show
i was trying to find in internet but could not find
I appreciate any help.
var ss = document.getElementsByClassName('stopwatch');
[].forEach.call(ss, function(s) {
var currentTimer = 0,
interval = 0,
lastUpdateTime = new Date().getTime(),
start = s.querySelector('button.start'),
stop = s.querySelector('button.stop'),
reset = s.querySelector('button.reset'),
mins = s.querySelector('span.minutes'),
secs = s.querySelector('span.seconds'),
cents = s.querySelector('span.centiseconds');
start.addEventListener('click', startTimer);
stop.addEventListener('click', stopTimer);
reset.addEventListener('click', resetTimer);
function pad(n) {
return ('00' + n).substr(-2);
}
function update() {
var now = new Date().getTime(),
dt = now - lastUpdateTime;
currentTimer += dt;
var time = new Date(currentTimer);
mins.innerHTML = pad(time.getMinutes());
secs.innerHTML = pad(time.getSeconds());
cents.innerHTML = pad(Math.floor(time.getMilliseconds() / 10));
lastUpdateTime = now;
}
function startTimer() {
if (!interval) {
lastUpdateTime = new Date().getTime();
interval = setInterval(update, 1);
}
}
function stopTimer() {
clearInterval(interval);
interval = 0;
}
function resetTimer() {
stopTimer();
currentTimer = 0;
mins.innerHTML = secs.innerHTML = cents.innerHTML = pad(0);
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Stopwatch</title>
</head>
<body>
<h1>Stopwatch</h1>
<div class="stopwatch">
<div class="controls">
<button class="start">Start</button>
<button class="stop">Stop</button>
<button class="reset">Reset</button>
<button class="save">save</button>
</div>
<div class="display">
<span class="minutes">00</span>:<span class="seconds">00</span>:<span class="centiseconds">00</span>
</div>
</div>
<script src="stopwatch.js"></script>
</body>
</html>
if i correct understand - here is solution. You still need some validations on input fields, checks on current timer and ithers, but it's worked version if user takes into account all these nuances himself.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Stopwatch</title>
</head>
<body>
<h1>Stopwatch</h1>
<div class="stopwatch">
<div class="controls">
<button class="start">Start</button>
<button class="stop">Stop</button>
<button class="reset">Reset</button>
||stop on:
<input class="min" placeholder="min" type="text" style="width: 30px" />:
<input class="sec" placeholder="sec" type="text" style="width: 30px" />:
<input class="ms" placeholder="ms" type="text" style="width: 30px" />
<button class="save">save</button>
<div class="savedTimeBlock" style="display: none">
saved time:
<div style="display: inline-block" class="time"></div>
</div>
</div>
<div class="display">
<span class="minutes">00</span>:<span class="seconds">00</span>:<span
class="centiseconds"
>00</span
>
</div>
</div>
<script src="stopwatch.js"></script>
</body>
</html>
stopwatch.js
var ss = document.getElementsByClassName("stopwatch");
[].forEach.call(ss, function(s) {
var currentTimer = 0,
interval = 0,
lastUpdateTime = new Date().getTime(),
timeToStop = {
min:null,
sec:null,
ms:null
},
start = s.querySelector("button.start"),
stop = s.querySelector("button.stop"),
reset = s.querySelector("button.reset"),
mins = s.querySelector("span.minutes"),
secs = s.querySelector("span.seconds"),
cents = s.querySelector("span.centiseconds"),
minutes = s.querySelector(".min"),
seconds = s.querySelector(".sec"),
milliseconds = s.querySelector(".ms"),
savedTimeBlock = s.querySelector(".savedTimeBlock"),
time = s.querySelector(".time"),
save = s.querySelector(".save");
start.addEventListener("click", startTimer);
stop.addEventListener("click", stopTimer);
save.addEventListener("click", saveStopTime);
reset.addEventListener("click", resetTimer);
function pad(n) {
return ("00" + n).substr(-2);
}
function saveStopTime() {
let min = timeToStop.min = pad(+minutes.value),
sec = timeToStop.sec = pad(+seconds.value),
ms = timeToStop.ms = pad(+milliseconds.value);
if (+min || +sec || +ms) {
showSavedTimeBlock(min, sec, ms)
} else {
killSavedTimeBlock()
}
}
const showSavedTimeBlock = (min, sec, ms) => {
savedTimeBlock.style.display = 'inline-block';
time.innerText = `${min}:${sec}:${ms}:`
};
const killSavedTimeBlock = () => {
savedTimeBlock.style.display = 'none';
timeToStop.min = null;
timeToStop.sec = null;
timeToStop.ms = null;
time.innerText = ''
};
function update() {
var now = new Date().getTime(),
dt = now - lastUpdateTime;
currentTimer += dt;
var time = new Date(currentTimer);
let min = pad(time.getMinutes());
let sec = pad(time.getSeconds());
let ms = pad(Math.floor(time.getMilliseconds() / 10));
mins.innerHTML = min;
secs.innerHTML = sec;
cents.innerHTML = ms;
let ts = timeToStop;
if (ts.min === min && ts.sec === sec && ts.ms === ms) {
stopTimer()
} else {
lastUpdateTime = now;
}
}
function startTimer() {
if (!interval) {
lastUpdateTime = new Date().getTime();
interval = setInterval(update, 1);
}
}
function stopTimer() {
clearInterval(interval);
interval = 0;
}
function resetTimer() {
stopTimer();
killSavedTimeBlock()
currentTimer = 0;
mins.innerHTML = secs.innerHTML = cents.innerHTML = pad(0);
}
});
This is supposed to be a dice game where 2 people click to roll dice and they add what they get until they reach the goal. Their score resets if they roll over 9 though. Images of dice are supposed to pop up and show what they rolled. I know the images are not on here but it still shows that there should an image there with the error symbol. I am having trouble with the second image not showing up which should come from the SetPic2 function. Any help would be appreciated. Also, the PASS buttons are supposed the pass the person's turn to the other player but the main problem is the images.
//console.log("file loaded");
//var p1Button = document.getElementById("p1");
var p1Button = document.querySelector("#p1");
var p2Button = document.querySelector("#p2");
var P1Pass = document.querySelector("P1Pass");
var P2Pass = document.querySelector("P2Pass");
var setButton = document.querySelector("#set");
var resetButton = document.querySelector("#reset");
var diceImage = document.querySelector("img");
var diceImage2 = document.querySelector("img2");
var p1Total = document.querySelector("#p1score");
var p2Total = document.querySelector("#p2score");
var targetScore = document.querySelector("#tscore");
var newScore = document.querySelector("#newtarget");
var num = 0,
num2 = 0,
p1val = 0,
p2val = 0,
target;
var playgame = true;
target = Number(targetScore.textContent); //convert the string to num
p1Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p1val = p1val + num + num2;
p1Total.textContent = p1val;
setButton.disabled = true;
p1Button.disabled = true;
p2Button.disabled = false;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p1val = 0;
}
if (p1val >= target) {
playgame = false;
p1Total.classList.add("winner");
stopGame();
}
}
});
p2Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p2val = p2val + num + num2;
p2Total.textContent = p2val;
setButton.disabled = true;
p1Button.disabled = false;
p2Button.disabled = true;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p2val = 0;
}
if (p2val >= target) {
playgame = false;
p2Total.classList.add("winner");
stopGame();
}
}
});
/*P1Pass.addEventListener("click", function(){
p1Button.disabled= true;
p2Button.disabled = false;
});
P2Pass.addEventListener("click", function(){
p1Button.disabled = false;
p2Button.disabled = true;
});*/
setButton.addEventListener("click", function() {
targetScore.textContent = newScore.value;
target = Number(targetScore.textContent);
setButton.disabled = true;
newScore.disabled = true;
});
resetButton.addEventListener("click", function() {
p1Button.disabled = false;
p2Button.disabled = true;
p1Total.textContent = "0";
p2Total.textContent = "0";
targetScore.textContent = "25";
setButton.disabled = false;
newScore.disabled = false;
p1Total.classList.remove("winner");
p2Total.classList.remove("winner");
playgame = true;
p1val = 0;
p2val = 0;
target = 25;
});
function stopGame() {
p1Button.disabled = true;
p2Button.disabled = true;
setButton.disabled = true;
newScore.disabled = true;
}
function setPic(val) {
if (val == 1) {
diceImage.src = "1.png";
} else if (val == 2) {
diceImage.src = "2.png";
} else if (val == 3) {
diceImage.src = "3.png";
} else if (val == 4) {
diceImage.src = "4.png";
} else if (val == 5) {
diceImage.src = "5.png";
} else if (val == 6) {
diceImage.src = "6.png";
}
}
function setPic2(val2) {
if (val2 == 1) {
diceImage2.src = "1.png";
} else if (val2 == 2) {
diceImage2.src = "2.png";
} else if (val2 == 3) {
diceImage2.src = "3.png";
} else if (val2 == 4) {
diceImage2.src = "4.png";
} else if (val2 == 5) {
diceImage2.src = "5.png";
} else if (val2 == 6) {
diceImage2.src = "6.png";
}
}
.winner {
color: green;
background-color: yellow;
}
;
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap
.min.css" integrity="sha384-
Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="gamestyle.css">
<title>Dice Game</title>
</head>
<body>
<div class="container">
<br>
<h1> <span id="p1score">0</span> vs. <span id="p2score">0</span> </h1>
<br>
<p>Target-Score: <span id="tscore">25</span></p>
<br>
<button class="btn btn-success" id="p1"> Player One </button>
<button class="btn btn-warning" id="p2"> Player Two </button>
<br><br>
<button class="btn btn-secondary" id="P1Pass">PASS</button>
<button class="btn btn-secondary" id="P2Pass">PASS</button>
<br><br> New Target: <input type="number" id="newtarget">
<br><br>
<button class="btn btn-primary" id="set"> Set </button>
<button class="btn btn-danger" id="reset"> Reset </button>
<br><br>
<img src="">
<img src="">
</div>
<script src="gamefunction.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-
J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min
.js" integrity="sha384-
Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.m
in.js" integrity="sha384-
wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
Your selector will not finding your second image element.
var diceImage2 = document.querySelector("img2");
You could give your images IDs and reference them directly:
HTML
<img id="die1" src="" />
<img id="die2" src="" />
JS
var diceImage1 = document.getElementById('die1');
var diceImage2 = document.getElementById('die2');
I have a code that uses localStorage and javascript. I tried to add more slots, like slot1, slot2, slot3 up to 5. I just copy and paste then change the variable names like like slot1, slot2, slot3 up to 5. But it won't work. Help will be appreciated so much.
Javascript:
var slot = localStorage.getItem("slot");
if (slot == null) {
slot = 10;
}
document.getElementById("slot").innerText = slot;
function reduceSlot() {
if (slot >= 1) {
slot--;
localStorage.setItem("slot", slot);
if (slot > 0) {
document.getElementById('slot').innerText = slot;
} else {
document.getElementById('slot').innerText = "FULL";
document.getElementById("button1").style.display = "none";
}
}
}
document.getElementById("button1").onclick = reduceSlot;
function clearLocalStorage() {
localStorage.clear();
}
HTML:
<p id="slot">10</p>
Deduct
<button onclick="window.localStorage.clear();">Clear All</button>
Fiddle: http://jsfiddle.net/barmar/K8stQ/3/
not sure but. is this what you want to do?? working demo
i changed your code a bit.. you can change it into your liking later..
<span id="slot0">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(0)})()" ><br>
<span id="slot1">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(1)})()" ><br>
<span id="slot2">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(2)})()" ><br>
<span id="slot3">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(3)})()" ><br>
<span id="slot4">10</span><input type="button" value="Deduct" onclick="(function(){reduceSlot(4)})()" ><br>
<p>
<button onclick="clearAll()">Clear All</button>
</p>
and for the js...
ls = localStorage.getItem("slots") ;
if(!ls) { localStorage.setItem("slots", "10,10,10,10,10");
}
var slots = localStorage.getItem("slots").split(',').map(Number);
window.onload = updateSlots;
function updateSlots() { for(var i=0;i<slots.length;i++) {
document.getElementById('slot' + i ).innerHTML = slots[i] ;
}}
var reduceSlot = function(slotId) {
console.log(slots[slotId]) ;
if(slots[slotId] >= 1) {
slots[slotId]--; localStorage.setItem("slots",slots);
document.getElementById('slot' + slotId).innerHTML = slots[slotId];
}
else { document.getElementById('slot'+slotId).innerText = "FULL";
}
};
function clearAll() {
window.localStorage.clear();
slots = [10,10,10,10,10];
updateSlots();
}
Try this,
Script
window.ready = function() {
checkStorage();
}
function checkStorage() {
var slot = localStorage.getItem("slot");
if (slot == null) {
slot = 10;
}
document.getElementById("slot").innerHTML = slot;
}
function reduceSlot() {
var slot = localStorage.getItem("slot");
if (slot == null) {
slot = 10;
}
if (slot >= 1) {
slot--;
localStorage.setItem("slot", slot);
if (slot > 0) {
document.getElementById('slot').innerHTML = slot;
} else {
document.getElementById('slot').innerHTML = "FULL";
document.getElementById("button1").style.display = "none";
}
}
}
document.getElementById("button1").onclick = reduceSlot;
document.getElementById("clear").onclick = clear_me;
function clear_me() {
localStorage.clear();
checkStorage();
}
HTML
<p id="slot">10</p>
Deduct
<button id="clear">Clear All</button>
Demo
I'm making a tic-tac-toe game, and I'm stuck. I sort of made an A.I. that moves after you but it's all a bit messed up. Try it yourself and see what happens. Can anybody have a look and see if they're able to improve it and explain how they did it? And to make things simple, how could I make the A.I. choose any box which hasn't been chosen yet.
Here's the code:
<!DOCTYPE html>
<html>
<body>
<input type="button" id="k1" value=" " onclick="tictactoe(this)">
<input type="button" id="k2" value=" " onclick="tictactoe(this)">
<input type="button" id="k3" value=" " onclick="tictactoe(this)">
<br />
<input type="button" id="k4" value=" " onclick="tictactoe(this)">
<input type="button" id="k5" value=" " onclick="tictactoe(this)">
<input type="button" id="k6" value=" " onclick="tictactoe(this)">
<br />
<input type="button" id="k7" value=" " onclick="tictactoe(this)">
<input type="button" id="k8" value=" " onclick="tictactoe(this)">
<input type="button" id="k9" value=" " onclick="tictactoe(this)">
<script>
var Xturn = true;
var nummoves = 0;
var cat;
function tictactoe(square) {
var value = square.value;
var doc1 = document.getElementById("k1").value;
var doc2 = document.getElementById("k2").value;
var doc3 = document.getElementById("k3").value;
var doc4 = document.getElementById("k4").value;
var doc5 = document.getElementById("k5").value;
var doc6 = document.getElementById("k6").value;
var doc7 = document.getElementById("k7").value;
var doc8 = document.getElementById("k8").value;
var doc9 = document.getElementById("k9").value;
for (nummoves = 0; nummoves < 2; nummoves++) {
if (doc1 == "X") {
cat = document.getElementById("k2").value = "O";
Xturn = true;
}
if (doc2 = "X") {
cat = document.getElementById("k4").value = "O";
Xturn = true;
}
if (doc3 == "X") {
cat = document.getElementById("k5").value = "O";
Xturn = true;
}
if (doc4 == "X") {
car = document.getElementById("k9").value = "O";
}
}
for (nummoves = 2; nummoves < 3; nummoves++) {
if (doc1 == "X") {
cat = document.getElementById("k7").value = "O";
Xturn = true;
}
}
if (value != "X" && value != "O") {
if (Xturn == true) {
square.value = "X";
return Xturn = false;
nummoves++;
} else if (Xturn == false) {
square.value = "O";
return Xturn = true;
nummoves++;
}
} else {
alert("That square has been clicked.");
}
}
</script>
</body>
</html>
Note the whole concept isn't mine I admit, but i did kind of it the A.O. part which is slightly messed up.
Keep track of a list of open squares, and just randomly select from that list.
That way you can eliminate the loop.
You can iterate thought the "buttons" and take the first that is not checked, or another one, based on random.
for(i=1;i<10;i++) {
if (document.getElementById('k'+i).value = ' ') {
// not played yet !
}
}
Consider the following logic:
// function that does an AI move
function doAIMove(xOrO) {
// randomly gets a number from 1 to 9
var randomSquare = document.getElementById("k" + getRandomInt(1, 9));
while (randomSquare.value != " ") {
randomSquare = document.getElementById("k" + getRandomInt(1, 9));
}
randomSquare.value(xOrO);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
That is not efficient, but it works as you asked. Anyway, you need to check if there's still remaining squares to fill in.
You should also consider implementing "the" tic tac toe AI, which is very simple. You should follow this pseudo algorithm for so:
When making a tic-tac-like game, the AI should work like this:
1. Check if there is a tile that you can win in 1 move
if there is no such tile:
2. Check if there is a tile that your opponent can win in 1 move
if there is no such tile:
3. Check if there is a tile that can make two tiles apply to the rule #1
if there is no such tile:
4. Check if there is a tile that your opponent can make two tiles apply to the rule #2
if there is no such tile:
5. implement your own AI form this point
jsFiddle link for the HTML and JS/JQuery implementation for Tic-Tac-Toe.
Currently its only a two player implementation without computer as opponent. Hope you can build on top of it.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo by bhatkrishnakishor</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
.tictactoe {
width: 125px;
height: 125px;
background: #A2A8A1;
};
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
//this is a demo tic tac toe game
$(document).ready($('input.tictactoe').click(tictactoe));
$(document).ready($('#ff').click(reset));
var whoseMove = 'X';
var xMove = new Array();
var oMove = new Array();
var gameOver = false;
var winningConditions = new Array( 'aa/ab/ac','ba/bb/bc','ca/cb/cc','aa/ba/ca','ab/bb/cb','ac/bc/cc','aa/bb/cc','ac/bb/ca');
var whoWon = '';
function tictactoe() {
if(gameOver == false && this.value == ' '){
if(whoseMove == 'X'){
this.value = whoseMove;
xMove[xMove.length] = this.id;
whoseMove = 'O';
}
else {
this.value = whoseMove;
oMove[oMove.length] = this.id;
whoseMove = 'X';
}
}
if(xMove.length >2){
whoWon = endGame();
}
if(gameOver && whoWon != '' && whoWon != 'draw') {
alert(whoWon + ' won!')
}
if(!gameOver && whoWon == 'draw') {
alert('Games been draw!');
}
}
function endGame() {
var winningCombinations = new Array();
//set this variable value to true incase the game is over
gameOver = true;
for(var index = 0; index < 8; index = index + 1){
var xMatchCount = 0;
var oMatchCount = 0;
winningCombinations = winningConditions[index].split('/');
for(var i = 0; i < 3; i = i + 1){
console.log('winningCombinations ' + winningCombinations[i]);
for(var j = 0; j < xMove.length; j = j + 1){
console.log('xMove ' + xMove[j]);
if(winningCombinations[i] == xMove[j]){
xMatchCount = xMatchCount + 1;
if(xMatchCount == 3){
return 'X';
}
}
}
for(var k = 0; k < oMove.length; k = k + 1){
//console.log('oMove ' + oMove[k]);
if(winningCombinations[i] == oMove[k]){
oMatchCount = oMatchCount + 1;
if(oMatchCount == 3){
return 'O';
}
}
}
}
}
console.log('x Move Count ' + xMove.length);
console.log('o Move Count ' + oMove.length);
if(xMatchCount < 3 && oMatchCount < 3){
gameOver = false;
}
if(xMove.length + oMove.length == 9){
return 'draw';
}
}
function reset() {
console.log('Xs Move - ' + xMove.join('/'));
console.log('Os Move - ' + oMove.join('/'));
console.log(winningConditions.length);
whoseMove = 'X';
xMove = new Array();
oMove = new Array();
gameOver = false;
whoWon = '';
$('input').filter(function() {
if(this.id != 'ff') {
this.value = ' ';
}
});
}
});//]]>
</script>
</head>
<body>
<input type="button" id="aa" class="tictactoe" value=" ">
<input type="button" id="ab" class="tictactoe" value=" ">
<input type="button" id="ac" class="tictactoe" value=" ">
<br />
<input type="button" id="ba" class="tictactoe" value=" ">
<input type="button" id="bb" class="tictactoe" value=" ">
<input type="button" id="bc" class="tictactoe" value=" ">
<br />
<input type="button" id="ca" class="tictactoe" value=" ">
<input type="button" id="cb" class="tictactoe" value=" ">
<input type="button" id="cc" class="tictactoe" value=" ">
<br /><br />
<input type="button" id="ff" value="Reset">
</body>