NaN in result variable and calculation - javascript

I have been studying JavaScript and experiment with some things. I have build a small application (see code below). Everything is going well untill the function eindResultaat(). Here it seems that there is something with resultaat3 (it is NaN) but I can not figure out why. resultaat1 and resultaat2 are getting processed in the same way and there it goes fine.
var resultatenArray = [];
var eindcijfer, eRes1, eRes2, eRes3, resultaat1, resultaat2, resultaat3;
function berekening1() {
resultaat1 = document.getElementById("eersteTentamen").value;
console.log("Dit is resultaat1 " + resultaat1);
if ((resultaat1 == "GR") || (resultaat1 == "gr")) {
document.getElementById("res1").innerHTML = "Geen resultaat";
resultaat1 = resultaat1 || 0;
//eRes1 = 0.0;
} else {
let res1 = document.getElementById("res1");
res1.innerHTML = resultaat1;
res1.style.color = resultaat1 >= 5.5 ? 'green' : 'red';
document.getElementById("res1").innerHTML = resultaat1;
//eRes1 = resultaat1;
resultatenArray.push(resultaat1);
console.log(resultatenArray);
}
}
function berekening2() {
resultaat2 = document.getElementById("tweedeTentamen").value;
console.log("Dit is resultaat2 " + resultaat2);
if ((resultaat2 == "GR") || (resultaat2 == "gr")) {
document.getElementById("res2").innerHTML = "Geen resultaat";
eRes2 = 0.0;
} else {
let res2 = document.getElementById("res2");
res2.innerHTML = resultaat2;
res2.style.color = resultaat2 >= 5.5 ? 'green' : 'red';
document.getElementById("res2").innerHTML = resultaat2;
//eRes2 = resultaat2;
resultatenArray.push(resultaat2);
console.log(resultatenArray);
}
}
function berekening3() {
resultaat3 = document.getElementById("derdeTentamen").value;
console.log("Dit is resultaat3 " + resultaat3);
if ((resultaat3 == "GR") || (resultaat3 == "gr")) {
document.getElementById("res3").innerHTML = "Geen resultaat";
var resultaat3 = 0.0;
//eRes3 = 0;
console.log(resultaat3);
} else {
let res3 = document.getElementById("res3");
res3.innerHTML = resultaat3;
res3.style.color = resultaat3 >= 5.5 ? 'green' : 'red';
document.getElementById("res3").innerHTML = resultaat3;
//eRes3 = resultaat3;
resultatenArray.push(resultaat3);
console.log(resultatenArray);
}
console.log(isNaN(resultaat3));
}
function eindResultaat() {
var aantalDeelTentamens = resultatenArray.length;
console.log(aantalDeelTentamens);
console.log("resultaten: " + resultaat1, resultaat2, resultaat3);
//console.log("eRes resultaten:" + eRes1, eRes2, eRes3);
//parseFloat(resultaat1);
//parseFloat(resultaat2);
//parseFloat(resultaat3);
console.log(isNaN(resultaat1));
console.log(isNaN(resultaat2));
console.log(isNaN(resultaat3));
eindcijfer = ((resultaat1 + resultaat2 + resultaat3) / aantalDeelTentamens).toFixed(1);
//var eindcijfer = ((eRes1 + eRes2 + eRes3)/aantalDeelTentamens).toFixed(1);
console.log(eindcijfer);
console.log(isNaN(eindcijfer));
document.getElementById("eindresultaat").innerHTML = eindcijfer;
}
Resultaat <b>eerste</b> deeltentamen: <input type="text" value="" id="eersteTentamen"><input type="submit" name=buttonResultaat1 value="Resultaat bevestigen" onclick="berekening1()"><br><br> Resultaat <b>tweede</b> deeltentamen: <input type="text" value=""
id="tweedeTentamen"><input type="submit" name=buttonResultaat2 value="Resultaat bevestigen" onclick="berekening2()"><br><br> Resultaat <b>derde</b> deeltentamen: <input type="text" value="" id="derdeTentamen"><input type="submit" name=buttonResultaat3
value="Resultaat bevestigen" onclick="berekening3()"><br><br>
<hr> Resultaat <b>eerste</b> deeltentamen: <span id="res1"></span><br> Resultaat <b>tweede</b> deeltentamen: <span id="res2"></span><br> Resultaat <b>derde</b> deeltentamen: <span id="res3"></span><br><br>
<hr>
<br>
<input type="submit" name=eindresultaat value="Bereken eindresultaat" onclick="eindResultaat()"><br><br>
<b>Het eindresultaat is: </b> <span id="eindresultaat"></span>

Indeed, it was deleting the var at some places so the code works. No I am busy with what to do if someone makes 2 test in stead of 3. So the average must be calculated over 2 tests.

Related

Javascript for card shuffle failing

Over my head with javascript. I'm trying to get the cards to shuffle when clicking next.
Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.
Please help—many thanks.
When I'm lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/
Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???
How I have it set up:
HTML:
var r = -1;
var mx = 499; // maximum
var a = new Array();
function AddNumsToDict(){
var m,n,i,j;
i = 0;
j = 0;
while (i <= 499)
{
m = (500 * Math.random()) + 1;
n = Math.floor(m);
for (j=0;j<=499;j++)
{
if (a[j] == (n-1))
{
j = -1;
break;
}
}
if (j != -1)
{
//a.push(n-1);
a[i] = (n-1);
i++;
j=0;
}
}
return;
}
function startup()
{
writit('SENTENCES<br><br><br>Robert Grenier', 'test');
SetCookie("pg", -1);
AddNumsToDict();
}
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue) + ";"
}
function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//if ((oNxt) && (oPrev))
//{
var num = GetCookie("pg");
if (num == mx){ //maximum
SetCookie("pg",parseInt(num) - 1);
num = GetCookie("pg");
}
// oNxt.disabled = false;
// if (num <= 1){
// oPrev.disabled = true;
// }
if (num >= 1){
num--;
writit(Caption[a[num]], 'test');
SetCookie("pg",num);
}
//}
}
function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
// if ((oNxt) && (oPrev))
// {
var num = GetCookie("pg");
// if (num > -1){
// oPrev.disabled = false;
// }
// else{
// oPrev.disabled = true;
// }
// if (num >= parseInt(mx)-1){ //maximum - 1
// oNxt.disabled = true;
// }
// else {
// oNxt.disabled = false;
// }
if (num <= parseInt(mx)-2){
num++;
writit(Caption[a[num]],'test');
SetCookie("pg",num);
}
// }
}
function writit(text,id)
{
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = '';
x.innerHTML = text;
}
else if (document.all)
{
x = document.all[id];
x.innerHTML = text;
}
else if (document.layers)
{
x = document.layers[id];
l = (480-(getNumLines(text)*8))/2;
w = (764-(getWidestLine(text)*8))/2;
text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
x.document.open();
x.document.write(text2);
x.document.close();
}
}
function getNumLines(mystr)
{
var a = mystr.split("<br>")
return(a.length);
}
function getWidestLine(mystr)
{
if (mystr.indexOf(" ") != -1)
{
re = / */g;
mystr = mystr.replace(re,"Z");
//alert(mystr);
}
if (mystr.indexOf("<u>") != -1)
{
re = /<u>*/g;
mystr = mystr.replace(re, "");
re = /<\/u>*/g;
mystr = mystr.replace(re, "");
}
if (mystr.indexOf("<br>") != -1)
{
var ss, t;
var lngest;
ss = mystr.split("<br>");
lngest = ss[0].length;
for (t=0; t < ss.length; t++)
{
if (ss[t].length > lngest)
{
lngest = ss[t].length;
}
}
}
else {
lngest = mystr.length;
}
return(lngest);
}
// -->
</script>
<body bgcolor="gainsboro" onload="startup();">
<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>
<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">
JS:
var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opener = _____WB$wombat$assign$function_____("opener");
function CaptionArray(len) {
this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"
}

Retrieving a value from a dropdown menu using PHP

I'm creating an appointment form. I'm trying to retrieve the hour and minute using $_POST['minute'] but I kept getting "Undefined variable or index".
HTML
<form id="theForm" method="POST" onsubmit="ajaxSubmit(); return false">
<h5>Schedule your 15 minute consultation</h5>
<p id="date">MM/DD/YYYY</p>
<div id="time">
<select id="hours" name="hour"></select>
<span>:</span>
<select id="minutes" name="minute"></select>
<div id="timeLabel">
<label class="ampm" name="am" id="am">AM</label> / <label class="ampm" name="pm" id="pm">PM</label>
</div>
</div>
<input placeholder="Name" name="name" id="name" />
<input placeholder="Email" name="email" id="email" />
<button class="submitBtn" name="submitBtn">SUBMIT</button>
<p id="isSent"></p>
</form>
JS
const hours = document.getElementById("hours");
for (let i = 1; i <= 12; i++) {
hours.innerHTML += `<option value="${i}">${i}</option>`;
}
const minutes = document.getElementById("minutes");
for(let i = 0; i <= 45; i+=15) {
if(i < 10) {
minutes.innerHTML += `<option value="0${i}">0${i}</option>`;
} else {
minutes.innerHTML += `<option value="${i}">${i}</option>`;
}
}
function ajaxSubmit() {
let name = document.getElementById('name'),
email = document.getElementById('email'),
date = document.getElementById('date'),
hours = document.getElementById('hours'),
minutes = document.getElementById('minutes'),
am = document.getElementById('am'),
pm = document.getElementById('pm');
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState == 4) {
document.querySelector("#isSent").innerHTML = xhr.responseText;
}
}
xhr.open('POST', 'mail.php?', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name=" + name.value +
"&email=" + email.value +
"&date=" + date.value +
"&hours=" + hours.value +
"&minutes=" + minutes.value +
"&am" + am.value +
"&pm" + pm.value);
}
I've tried $hour = $_POST['hour']; but that did not work, same with the minute. So here's my PHP
$hour = null;
$minute = null;
if(isset($_POST['hour'])) {
$hour = $_POST['hour'];
}
if(isset($_POST['minute'])) {
$minute = $_POST['minute'];
}
The issue is the way you are sending form data to PHP. Better way of doing is to use new FormData() function of Javascript. It sends the serialized data so no additional processing is needed.
const hours = document.getElementById("hours");
for (let i = 1; i <= 12; i++) {
hours.innerHTML += `<option value="${i}">${i}</option>`;
}
const minutes = document.getElementById("minutes");
for (let i = 0; i <= 45; i += 15) {
if (i < 10) {
minutes.innerHTML += `<option value="0${i}">0${i}</option>`;
} else {
minutes.innerHTML += `<option value="${i}">${i}</option>`;
}
}
function ajaxSubmit() {
var form = document.querySelector('form');
var data = Object.fromEntries(new FormData(form));
console.log(data)
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState == 4) {
document.querySelector("#isSent").innerHTML = xhr.responseText;
}
}
xhr.open('POST', 'mail.php?', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
}
<form id="theForm" method="POST" onsubmit="ajaxSubmit(); return false">
<h5>Schedule your 15 minute consultation</h5>
<p id="date">MM/DD/YYYY</p>
<div id="time">
<select id="hours" name="hour"></select> <span>:</span>
<select id="minutes" name="minute"></select>
<div id="timeLabel">
<label class="ampm" name="am" id="am">AM</label> / <label class="ampm" name="pm" id="pm">PM</label>
</div>
</div>
<input placeholder="Name" name="name" id="name" />
<input placeholder="Email" name="email" id="email" />
<button class="submitBtn" name="submitBtn">SUBMIT</button>
<p id="isSent"></p>
</form>
Change your $_POST from hour to plural hours, the same with minute to minutes.
$hours = null;
$minute = null;
if(isset($_POST['hours'])) {
$hours = $_POST['hours'];
}
if(isset($_POST['minutes'])) {
$minutes = $_POST['minutes'];
}
//this message will display on #isSent paragraph
if(isset($hours) and isset($minutes))
echo "your Schedule 15 minute consultation($hours:$minutes) has been registered!";
Tip: for javascript generating readable time format use padStart function:
for(let i = 0; i <= 45; i+=15) {
minutes.innerHTML += `<option value="${(''+i).padStart(2,'0')}">${(''+i).padStart(2,'0')}</option>`;
}
Insead of if else statement condition.
for(let i = 0; i <= 45; i+=15) {
if(i < 10) {
minutes.innerHTML += `<option value="0${i}">0${i}</option>`;
} else {
minutes.innerHTML += `<option value="${i}">${i}</option>`;
}
}

Auto populate form field with javascript

Sorry for such a noob problem - I've not found a solution after browsing many posts and I'm afraid I don't even know what question to ask - I'm trying to auto populate the 'sunits' input field to the value of the 'bunits' input, unless changed. I barely cobbled this together for some friends, and do apologize for the poor style and everything else. The code below is also the homepage at http://lootsim.com :
<div id="buyformdiv" class="fluid ">
<span id="pickingupspan" class="actionspan">Buying:</span>
<p># units to be bought:
<input id="bunits" type="number" step="1" onchange="update()"></p>
<p>
Cost per unit :
<input id="cunits" type="number" step="0.01" onchange="update()"></p>
<p>
Overhead :
<input id="cxbship" type="number" step="0.01" onchange="update()"></p>
</div>
<div id="sellformdiv" class="fluid ">
<span id="gettingridspan" class="actionspan">Selling:</span>
<p># units to be sold:
<input id="sunits" type="number" step="1" onchange="update()"></p>
<p>
selling for ($ each) :
<input id="sprice" type="number" step="0.01" onchange="update()"></p>
<p>
Frequency :
<select id="sfreq" onchange="update()">
<option value="1">Once</option>
<option value="7">Week</option>
<option value="31">Month (31 days)</option>
<option value="365">Year</option>
</select>
</p>
</div>
Javascript"
var bunits, cunits, cxb, cxbship, btotal, sunits, sfreq, sprice, net, profit;
function update() {
var bunits = document.getElementById('bunits').value;
var cunits = document.getElementById('cunits').value;
var cunits = parseFloat(cunits).toFixed(2);
var cxbship = document.getElementById('cxbship').value;
var cxbship = parseFloat(cxbship).toFixed(2);
var cxb = bunits * cunits;
var cxb = parseFloat(cxb).toFixed(2);
var btotal = parseFloat(cxb) + parseFloat(cxbship);
var btotal = parseFloat(btotal).toFixed(2);
var sunits = document.getElementById('sunits').value;
var sprice = document.getElementById('sprice').value;
var sprice = parseFloat(sprice).toFixed(2);
var sfreq = document.getElementById('sfreq').value;
var sunitxp = sunits * sprice;
var sunitxp = parseFloat(sunitxp).toFixed(2);
var salesxdays = sunitxp * sfreq;
var salesxdays = parseFloat(salesxdays).toFixed(2);
//populate numbers in results window
if (bunits > 0) {
document.getElementById('bunitsspan').innerHTML = "Buying " + bunits + " units";
document.getElementById('sunits').value = bunits;
}
if (cunits > 0) {
document.getElementById('costspan').innerHTML = "at $" + cunits + " per unit";
}
if (cxb > 0) {
document.getElementById('cxbspan').innerHTML = "Subtotal: $" + cxb;
}
if (cxbship > 0) {
document.getElementById('cxbshipspan').innerHTML = "Overhead: " + cxbship;
}
if (btotal > 0) {
document.getElementById('subtotalspan').innerHTML = "<b>Total: $" + btotal + "</b>";
}
//populate income in results span
if (sunits > 0) {
document.getElementById('sunitsspan').innerHTML = "Selling " + sunits + " units";
}
if (sprice > 0) {
document.getElementById('sellcostspan').innerHTML = "for $" + sprice + " each";
}
if (sunitxp > 0) {
document.getElementById('sunitxpspan').innerHTML = "Subtotal: $" + sunitxp;
}
if (sfreq > 0 ) {
if ((sfreq == 1) && (sprice > 0)){
document.getElementById('sellfreqspan').innerHTML = "all units";
} else if (sfreq == 7) {
document.getElementById('sellfreqspan').innerHTML = "every day for a week";
} else if (sfreq == 31) {
document.getElementById('sellfreqspan').innerHTML = "every day for a month";
} else if (sfreq == 365) {
document.getElementById('sellfreqspan').innerHTML = "every day for a year";
}
}
if (salesxdays > 0) {
document.getElementById('salesxdays').innerHTML = "Total: $" + salesxdays;
}
}

JavaScript not being executed onClick

I have a webpage where I'm processing an HTML form using JavaScript and onClick, but the JavaScript code isn't being executed.
This is my form:
<form action="" method="post" id="reportform">
<input type="radio" name="report" value="customer"><p>Customers</p>
<input type="radio" name="report" value="item"><p>Items Sold</p>
<input type="radio" name="report" value="department"><p>Sales Departments</p>
<input type="radio" name="report" value="person"><p>Sales People</p>
<input type="button" name="reportsubmit" value="Submit" onClick="checkReport(this.form)">
</form>
And this is the JavaScript code (by this way both the JavaScript and the form are located in the body tag):
function checkReport (form)
{
var checked = form.querySelector('input:checked');
var value = checked ? checked.value : null;
if (value == "customer")
{
var href = "http://bdpastudents.com/~a7068104/2013-2014/Lab_13/Reports/Reports.php";
var idx = href.indexOf("Reports", 0);
var new_href = href.slice(0,idx+19) + "#customer" + href.slice(idx+19);
window.location.replace(new_href);
}
else if (value == "item")
{
var href = "http://bdpastudents.com/~a7068104/2013-2014/Lab_13/Reports/Reports.php";
var idx = href.indexOf("Reports", 0);
var new_href = href.slice(0,idx+19) + "#item" + href.slice(idx+19);
window.location.replace(new_href);
}
else if (value == "department")
{
var href = "http://bdpastudents.com/~a7068104/2013-2014/Lab_13/Reports/Reports.php";
var idx = href.indexOf("Reports", 0);
var new_href = href.slice(0,idx+19) + "#department" + href.slice(idx+19);
window.location.replace(new_href);
}
else if (value == "person")
{
var href = "http://bdpastudents.com/~a7068104/2013-2014/Lab_13/Reports/Reports.php";
var idx = href.indexOf("Reports", 0);
var new_href = href.slice(0,idx+19) + "#person" + href.slice(idx+19);
window.location.replace(new_href);
}
}
function checkCustomer(form)
{
var checked = form.querySelector('input:checked');
var value = checked ? checked.value : null;
if (value == "all")
{
var href = "http://bdpastudents.com/~a7068104/2013-2014/Lab_13/Reports/Reports.php";
var idx = href.indexOf("Reports", 0);
var new_href = href.slice(0,idx+19) + "#allcustomers" + href.slice(idx+19);
window.location.replace(new_href);
}
else if (value == "one")
{
var href = "http://bdpastudents.com/~a7068104/2013-2014/Lab_13/Reports/Reports.php";
var idx = href.indexOf("Reports", 0);
var new_href = href.slice(0,idx+19) + "#onecustomer" + href.slice(idx+19);
window.location.replace(new_href);
}
}
Your HTML is illegal. You have not closed your input tags. Who knew, you don't have to close your tags. Sorry about that.
Can you replicate your problem on this fiddle? Or does this work for you?
var form = document.getElementById('reportForm');
http://jsfiddle.net/mgDGN/

When making a tic tac toe game in javascript, how can you create an A.I. that will select any random box, but one that hasn't been chosen?

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>

Categories