Show javascript function output in html - javascript

My JavaScript contains two functions. One function gets a number from the user and returns a string that shows if the number is a prime or not and then store the number and the result in an array.
results = new Array();
i = 0;
function isPrime(num) {
flag = false;
if (num > 1) {
for (i = 2; i < num; i++) {
if (num % i == 0) {
flag = true;
break;
}
}
}
return !flag;
}
function getNumberPrime(number) {
condition = (isPrime(number)) ? ('is') : ('is not');
console.log('' + number + ' ' + condition + ' prime');
dict = {}
dict['number'] = number
dict['isPrime'] = isPrime(number);
results.push(dict);
}
function getAll() {
for (i = 0; i < results.length; i++) {
condition = (results[i]['isPrime']) ? ('is') : ('is not');
number = results[i]['number']
console.log('' + number + ' ' + condition + ' prime');
}
}
My HTML has an input and two buttons. One button returns the output of the first function and the second should show the items of array.
<!DOCTYPE html>
<html lang="fa">
<head>
<title>Prime Number</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="prime.js"></script>
</head>
<body>
<div class="container">
<h2>Find Prime Numbers</h2>
<form>
<div class="form-group">
<label class="control-label col-sm-2">Numbers:</label>
<div class="col-sm-10">
<input class="form-control" id="inp" name="nums" style="margin-left: -11%">
</div>
</div>
<button type="submit" class="btn btn-default" style=" margin-top: 2%;" onclick="getNumberPrime()">Check</button>
<button type="submit" class="btn btn-default" style="margin-top: 2%;" onclick="document.getElementById('showprime').innerHTML =getAll()">Show Result</button>
<p id="showprime"></p>
</form>
</div>
</body>
</html>
But the first button doesn't work and I don't know how to implement the second button.
Prime numbers must be blue and none primes must be red.

First: Your buttons need to have type="button" to prevent a reload because of the submit.
Your function getNumberPrime() wants a parameter number which you aren't offering in your inline event handler. Therefor you should get the number in that function by selecting the input and getting its value:
let number = document.querySelector('#inp').value;
Your function getAll() doesn't return anything and therefor the result isn't inserted in #showprime. Instead of loging the values to the console you could add them to an output string and return that string after the for loop:
let output = '';
for (i = 0; i < results.length; i++) {
...
output += number + ' ' + condition + ' prime<br>';
}
return output;
If you want the output to be colored you could wrap each result in a paragraph tag and give it a class dependent on the condition. In this case #showprime should be container element like a div. The class would be styled with CSS.
Inside the for loop:
check = (results[i]['isPrime']) ? true : false;
condition = check ? ('is') : ('is not');
...
output += '<p class=' + check + '>' + number + ' ' + condition + ' prime</p>';
In your CSS-file:
.true {
color: blue;
}
.false {
color: red;
}
Last: It's better to devide Javascript and HTML and not to use inline event handlers. Therefor you should change this:
<button ... onclick="getNumberPrime()">Check</button>
<button ... onclick="document.getElementById('showprime').innerHTML = getAll()">Show Result</button>
to this:
<button id="check" ...>Check</button>
<button id="show" ...>Show Result</button>
document.querySelector('#check').addEventListener('click', getNumberPrime);
document.querySelector('#show').addEventListener('click', function() {
document.getElementById('showprime').innerHTML = getAll();
});
Working example:
results = new Array();
i = 0;
function isPrime(num) {
flag = false;
if (num > 1) {
for (i = 2; i < num; i++) {
if (num % i == 0) {
flag = true;
break;
}
}
}
return !flag;
}
function getNumberPrime() {
let number = document.querySelector('#inp').value;
condition = (isPrime(number)) ? ('is') : ('is not');
console.log('' + number + ' ' + condition + ' prime');
dict = {}
dict['number'] = number
dict['isPrime'] = isPrime(number);
results.push(dict);
}
function getAll() {
let output = '';
for (i = 0; i < results.length; i++) {
check = (results[i]['isPrime']) ? true : false;
condition = check ? ('is') : ('is not');
number = results[i]['number'];
output += '<p class=' + check + '>' + number + ' ' + condition + ' prime</p>';
}
return output;
}
document.querySelector('#check').addEventListener('click', getNumberPrime);
document.querySelector('#show').addEventListener('click', function() {
document.getElementById('showprime').innerHTML = getAll();
});
.true {
color: blue;
}
.false {
color: red;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="container">
<h2>Find Prime Numbers</h2>
<form>
<div class="form-group">
<label class="control-label col-sm-2">Numbers:</label>
<div class="col-sm-10">
<input class="form-control" id="inp" name="nums" style="margin-left: -11%">
</div>
</div>
<button id="check" type="button" class="btn btn-default" style=" margin-top: 2%;">Check</button>
<button id="show" type="button" class="btn btn-default" style="margin-top: 2%;">Show Result</button>
<div id="showprime"></div>
</form>
</div>

Related

AngularJS --> ng-view not loading js

The code works when the day1.js script is loaded in the index and if a certain snippet from the HTML template is pasted into the file, but it doesn't work when I switch to the page using ng-view with the same code. There is nothing in my day1controller. I'm pretty lost at this point and would appreciate some insight.
I keep getting the error
day1.js:5 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
Here is my index:
<!-- Takes in an input.txt and counts how many times the numbers increase and decrease -->
<!DOCTYPE html>
<html ng-app="adventOfCode">
<head>
<title>Home</title>
<link rel="stylesheet" href="style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular-route.min.js"></script>
<meta name="vieport" content="width=device-width initial scale=1" />
</head>
<body>
<header><h2>Website Header</h2></header>
<div class="column">
<div class="links">
Home<br />
Day 1<br />
Day 2<br />
</div>
</div>
<!-- Where the pages change -->
<div ng-view></div>
<!-- Code only works as intended when this div is pasted here -->
<div>
<input type="file" />
<textarea name="" id="" cols="30" rows="10"></textarea>
</div>
<!-- End of pasted code -->
<footer><h3>Website footer lalalala</h3></footer>
<script>
var app = angular
.module("adventOfCode", ["ngRoute"])
.config(function ($routeProvider, $locationProvider) {
//inject $locationProvider service
$locationProvider.hashPrefix(""); // add configuration
$routeProvider
.when("/home", {
template: "About Us",
})
.when("/day1", {
templateUrl: "views/day1.html",
controller: "day1Controller",
})
.when("/day2", {
templateUrl: "views/day2.html",
controller: "day2Controller",
});
});
</script>
<!-- Controllers -->
<script src="js/controllers/day1Controller.js"></script>
<script src="js/controllers/day2Controller.js"></script>
<!-- My scripts -->
<script src="js/day1.js"></script>
</body>
</html>
`
Here is the javascript I am trying to run (day1.js):
//selecting the input and textarea elements and saving them to variables
let input = document.querySelector("input");
let textarea = document.querySelector("textarea");
input.addEventListener("change", () => {
//returns an array of File objects
let files = input.files;
if (files.length == 0) return;
//getting the first File object
const file = files[0];
//creating a FileReader
let reader = new FileReader();
reader.onload = (e) => {
var index = 0;
var lastLine = "";
var currentLine = "";
var increased = 0;
var decreased = 0;
var results = [];
const file = e.target.result;
console.log("inside onload");
/**We are using split() function and passing regex pattern /\r\n|\n/ as a parameter. This will generate an array of lines and we are storing that in the lines variable. */
const lines = file.split(/\r\n|\n/);
console.log("split the lines");
/**-------------- Our Workspace -------------- */
lines.forEach((line) => {
if (index === 0) {
lastLine = line;
console.log(line + "-->" + index);
index++;
} else {
currentLine = line;
if (currentLine > lastLine) {
console.log(line + " --> " + index + " :increased");
increased++;
} else if (currentLine < lastLine) {
console.log(line + " --> " + index + " :decreased");
decreased++;
} else {
console.log(line + " --> " + index);
}
index++;
lastLine = currentLine;
}
});
console.log("Number of inputs: " + index);
console.log("How many times the inputs increased: " + increased); //1582 is too low
console.log("How many times the inputs decreased: " + decreased);
document.getElementById("increase").innerHTML =
"How many times the inputs increased: " + increased;
document.getElementById("decrease").innerHTML =
"How many times the inputs decreased: " + decreased;
results = slidingWindow(lines, 3);
document.getElementById("increase_").innerHTML =
"How many times the inputs increased: " + results[0];
document.getElementById("decrease_").innerHTML =
"How many times the inputs decreased: " + results[1];
document.getElementById("Index").innerHTML = "Number of inputs: " + index;
/**We are using the join() method to join all lines by a newline character (\n). This will return a string and we are setting that string as the value of the textarea element. */
textarea.value = lines.join("\n");
console.log("joined the lines");
};
reader.onerror = (e) => alert(e.target.error.name);
reader.readAsText(file);
});
function slidingWindow(linesArray, windowSize) {
if (windowSize < 0 || windowSize > linesArray.length) return null;
let currentSum = 0;
let lastSum = 0;
let increased = 0;
let decreased = 0;
let results = [];
for (let i = 0; i < linesArray.length; i++) {
currentSum += parseInt(linesArray[i]);
if (i >= windowSize - 1) {
if ((lastSum === 0) && (currentSum > lastSum)) {
console.log(currentSum + " --> " + i + " :no change");
} else if (currentSum > lastSum) {
console.log(currentSum + " --> " + i + " :increased");
increased++;
} else if (currentSum < lastSum) {
console.log(currentSum + " --> " + i + " :decreased");
decreased++;
} else if ((currentSum = lastSum)) {
console.log(currentSum + " --> " + i + " :no change");
}
lastSum = currentSum;
currentSum -= linesArray[i - (windowSize - 1)];
}
}
return (results = [increased, decreased]);
}
Here is day1.html, which is what I'm want to use to run day1.js:
<div>
<input type="file">
<textarea name="" id="" cols="30" rows="10"></textarea>
</div>
<div>
<h3>Increase or Decrease</h3>
<h2 id="increase"></h2>
<h2 id="decrease"></h2>
<h3>Sliding window</h3>
<h2 id="increase_"></h2>
<h2 id="decrease_"></h2>
<h3 id="Index"></h3>
</div>
You have to use container for place your view.ng- view is a directive that works like a placeholder. It creates a placeholder where a corresponding view can be placed based on the configuration.
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="nav">
Home
About
</div>
</div>
</div>
</div>
<div class="container">
<div ng-view=""></div>
</div>
My problem was that I didn't have the Jquery library in my index.html. Without it the scripts aren't executed when loaded by ng-view.

Clear the old innerhtml from Javascript

I am trying to do an assignment where it makes random lotto numbers. I have it all built out, but when I put the first value in and it runs it will post to the HTML. Then doing a second value will concatenate to the first instead of clearing. I've tried .reset and value = "" but I must be doing something wrong. I tried searching the old posts, but couldn't find anything as I wasn't sure exactly what the problem was.
var buttons = document.getElementById("create");
var numbers = [];
var shownSelection = ""
function makeIt() {
var input = document.getElementById("count").value;
var resultsDiv = document.getElementById("results");
if (input > 8) {
alert("Too many numbers. Please try less than 8.")
} else if (input < 1)
alert("Nothing to predict.")
else
for (var i = 0; i < input; i++) {
numbers[i] = Math.ceil(Math.random() * 99);
}
for (var i = 0; i < input; i++) {
if (i == input - 1) {
shownSelection = shownSelection + numbers[i];
} else {
shownSelection = shownSelection + numbers[i] + "-";
}
}
resultsDiv.innerHTML =
shownSelection;
document.getElementById("results").value = "";
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lucky Lotto Game</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/javascript.js" defer></script>
</head>
<body>
<div class="entry">
<ul>
<li><input type="text" id="count" placeholder="Enter number between 1 and 8" /></li>
</ul>
</div>
<div id="buttons" class="buttons">
<button id="create" onclick="makeIt()" class="create">Get my numbers</button>
</div><br><br><br>
<span id="results"></span>
</body>
</html>
You should initialize your 'shownSelection' variable inside the function so it will be empty each time you press the button:
var buttons = document.getElementById("create");
var numbers = [];
function makeIt() {
var shownSelection = ""
var input = document.getElementById("count").value;
var resultsDiv = document.getElementById("results");
if (input > 8) {
alert("Too many numbers. Please try less than 8.")
} else if (input < 1)
alert("Nothing to predict.")
else
for (var i = 0; i < input; i++) {
numbers[i] = Math.ceil(Math.random() * 99);
}
for (var i = 0; i < input; i++) {
if (i == input - 1) {
shownSelection = shownSelection + numbers[i];
} else {
shownSelection = shownSelection + numbers[i] + "-";
}
}
resultsDiv.innerHTML =
shownSelection;
document.getElementById("results").value = "";
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Lucky Lotto Game</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/javascript.js" defer></script>
</head>
<body>
<div class="entry">
<ul>
<li><input type="text" id="count" placeholder="Enter number between 1 and 8" /></li>
</ul>
</div>
<div id="buttons" class="buttons">
<button id="create" onclick="makeIt()" class="create">Get my numbers</button>
</div><br><br><br>
<span id="results"></span>
</body>
</html>

data attribute grouped by value calculate sum of other data attribute

I am trying to calculate all the huishoudens that are in each provincie. For this question I created a fiddle which can be found here: http://jsfiddle.net/Lyf1sak3/1/
With this sample data:
<div data-provincie="Noord-Holland" data-huishoudens="102"></div>
<div data-provincie="Noord-Holland" data-huishoudens="1250"></div>
<div data-provincie="Zuid-Holland" data-huishoudens="956"></div>
<div data-provincie="Zuid-Holland" data-huishoudens="235"></div>
<div data-provincie="Groningen" data-huishoudens="495"></div>
<div data-provincie="Groningen" data-huishoudens="55"></div>
<div data-provincie="Groningen" data-huishoudens="247"></div>
<div data-provincie="Utrecht" data-huishoudens="123"></div>
<div data-provincie="Utrecht" data-huishoudens="675"></div>
And this code:
var provincies = {},
provincie;
sum = 0;
$('*[data-provincie]').each(function(i, el){
provincie = $(el).data('provincie');
if (provincies.hasOwnProperty(provincie)) {
provincies[provincie] += 1;
sum += $(this).data('huishoudens');
}
else {
provincies[provincie] = 1;
}
});
// print results
$('#result').append('<hr>');
for(var key in provincies){
$('#result').append(key + ' (' + provincies[key] + '|' + sum + ')<br>');
}
I am grouping each provincie by its own property and now I just need to calculate the other data attribute, but I am completely stuck here. I am getting either the result 675 which is the last div in the sample data or I get 2462 and I have no clue how it gets that number.
What do I need to modify to get this result:
Noord-Holland (2|1352)
Zuid-Holland (2|1191)
Groningen (3|797)
Utrecht (2|798)
Whatever answer you give it is really appreciated but please don't post answers where it requires to hard code the names of provincie like $('*[data-provincie="Noord-Holland"]');
If you know provincie before only you can create an array with all provincie and then you can use this as a key to compare it with all the div if matches you can add same to sum variable and finally append final result to your result div.
Demo Code :
//all data provinces
//var json_ = ["Noord-Holland", "Zuid-Holland", "Groningen", "Utrecht"]
var json_ = [];
$('*[data-provincie]').each(function(i, el) {
//check if in array or not
if ($.inArray($(this).data('provincie'), json_) < 0) {
json_.push($(this).data('provincie'));//push same
}
});
console.log(json_)
sum = 0;
count = 0;
//loop through keys
for (var key in json_) {
$('*[data-provincie]').each(function(i, el) {
var provincie = $(el).data('provincie');
//if key matches
if (json_[key] == provincie) {
sum += $(el).data('huishoudens');
count++;
}
});
//append result
$('#result').append(count + ' (' + json_[key] + '|' + sum + ')<br/>')
count = 0;
sum = 0 //change sum to 0 again
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-provincie="Noord-Holland" data-huishoudens="102"></div>
<div data-provincie="Noord-Holland" data-huishoudens="1250"></div>
<div data-provincie="Zuid-Holland" data-huishoudens="956"></div>
<div data-provincie="Zuid-Holland" data-huishoudens="235"></div>
<div data-provincie="Groningen" data-huishoudens="495"></div>
<div data-provincie="Groningen" data-huishoudens="55"></div>
<div data-provincie="Groningen" data-huishoudens="247"></div>
<div data-provincie="Utrecht" data-huishoudens="123"></div>
<div data-provincie="Utrecht" data-huishoudens="675"></div>
<div id="result"></div>
You could modify the function like,
Get the count attributes like,
var count = parseInt($(this).data('huishoudens'));
Then inside the condition assign it like,
if (provincies.hasOwnProperty(provincie)) {
provincies[provincie]["sum"] += count;
}
else {
provincies[provincie] = {"sum": count};
}
Working Snippet:
var provincies = {},
provincie;
sum = 0;
$('*[data-provincie]').each(function(i, el){
provincie = $(el).data('provincie');
var count = parseInt($(this).data('huishoudens'));
if (provincies.hasOwnProperty(provincie)) {
provincies[provincie]["sum"] += count;
provincies[provincie]["provinceCount"] += 1;
}
else {
provincies[provincie] = {"sum": count, "provinceCount": 1};
}
});
// print results
$('#result').append('<hr>');
for(var key in provincies){
$('#result').append(key + ' (' + provincies[key].provinceCount + '|' + provincies[key].sum + ')<br>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<title>Course example</title>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<div data-provincie="Noord-Holland" data-huishoudens="102"></div>
<div data-provincie="Noord-Holland" data-huishoudens="1250"></div>
<div data-provincie="Zuid-Holland" data-huishoudens="956"></div>
<div data-provincie="Zuid-Holland" data-huishoudens="235"></div>
<div data-provincie="Groningen" data-huishoudens="495"></div>
<div data-provincie="Groningen" data-huishoudens="55"></div>
<div data-provincie="Groningen" data-huishoudens="247"></div>
<div data-provincie="Utrecht" data-huishoudens="123"></div>
<div data-provincie="Utrecht" data-huishoudens="675"></div>
<div id="result"></div>
</body>
</html>

Call java script function from the button id

I want to call myfunc() using the id button, how I do that?
I dont want to use nothing but the id to call this function..what code I need to add in my script?
<html>
<head>
<script>
function myfunc() {
var count = 0;
var line = 0;
var i = 0;
var phrase = document.getElementById('phrase').value;
var filter = document.getElementById('filter').value;
var arr = phrase.split(" ").reverse();
for (i = 0; i < arr.length; i++) {
if (arr[i].search(filter) == -1) {
if (line % 2 == 0) {
document.getElementById('words').innerHTML += " <u><span class='word' style='background:#D8D8D8; border:1px solid black; ' >
" + arr[i] + "</span></u>";
line++;
} else {
document.getElementById('words').innerHTML += " <span class='word' style='background:#D8D8D8; border:1px solid black; '>
" + arr[i] + "</span>";
line++;
}
}
if ((arr[i].search(filter) != -1) && (filter)) {
count++;
}
}
document.getElementById('count').innerHTML = count + " word(s) filtered out";
}
</script>
</head>
<body>
<h1>Sentence Reverser!</h1>
<div>Phrase:
<input id="phrase" type="text" size="40" />
</div>
<div>Filter:
<input id="filter" type="text" size="10" />
</div>
<div>
<button id="go">Go!</button>
</div>
<div id="words"></div>
<div id="count"></div>
</body>
</html>
You can add the following
document.getElementById('go').onclick = myfunc
After the element has loaded. In practice this means below the element, or in the head within a window loaded event.
You can use addEventListener() to attach the function on particular event inside the window.onload, something like this.
window.onload = function (){
document.getElementById('go').addEventListener('click', myfunc);
function myfunc(){
//your all code be here
}
}
DEMO
To be as short as possible, you can add this script after the HTML, or in the document load event:
go.onclick = myfunc
But this is far from best practice. A better practice would be to add an onclick attribute to your button:
<button id="go" type="button" onclick="myfunc()"> Go! </button>

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