I'm making a tic-tac-toe game. I've made my table cells clickable and once they are clicked they run a function called playPVPGame. To start, O and X are chosen randomly to go first. I have text in the corner of the page to indicate whose turn it is. Initially the text will be either "O goes first" or "X goes first". Afterwards it will change to "X is next" or "O is next" depending on the turn. The problem is after the initial text, the turn doesn't go back and forth like i want it to.
var $ = function(id) {
return document.getElementById(id);
};
var newGameAction = function()
{
//clear table
$("c1").innerHTML = "";
$("c2").innerHTML = "";
$("c3").innerHTML = "";
$("c4").innerHTML = "";
$("c5").innerHTML = "";
$("c6").innerHTML = "";
$("c7").innerHTML = "";
$("c8").innerHTML = "";
$("c9").innerHTML = "";
};
var pVpAction = function(elem)
{
var outputTect;
var turnCounter = 0;
var first_Turn = Math.floor(Math.random() * 2);
$("firstTurn").innerHTML = first_Turn;
first_turn = $("firstTurn").innerHTML;
if(first_turn == 0)
{
message = "O goes first";
}
if(first_turn == 1)
{
message = "X goes first";
}
$("goNext").innerHTML = message;
};
var playPVPGame = function(elem)
{
var turn = $("goNext").innerHTML;
var message;
if(turn == "O goes first")
{
elem.style.backgroundColor = "red";
elem.innerHTML = "O";
turn = "X is next";
$("goNext").innerHTML = turn;
}
if(turn == "X goes first")
{
elem.style.backgroundColor = "blue";
elem.innerHTML = "X";
turn = "O is next";
$("goNext").innerHTML = turn;
}
//does not work
/*if($("goNext").innerHTML = "X is next")
{
$("newGame").disabled = true;
}*/
message = $("goNext").innerHTML;
if(message == "X is next")
{
elem.style.backgroundColor = "blue";
elem.innerHTML = "X";
message = "O is next";
$("goNext").innerHTML = message;
}
if(message == "O is next")
{
elem.style.backgroundColor = "red";
elem.innerHTML = "O";
message = "X is next";
$("goNext").innerHTML = message;
}
};
window.onload = function() {
$("newGame").onclick = newGameAction;
$("playerVplayer").onclick = pVpAction;
};
table {width:100%}
table tr td{border:1px solid #000;height:50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="firstTurn"> </span>
<span id= "goNext"> </span>
<table class = "board">
<tr>
<td id = "c1" onclick="playPVPGame(this)" > . </td>
<td id = "c2" onclick="playPVPGame(this)"> . </td>
<td id = "c3" onclick="playPVPGame(this)"> . </td>
</tr>
<tr>
<td id = "c4" onclick="playPVPGame(this)"> . </td>
<td id = "c5" onclick="playPVPGame(this)"> . </td>
<td id = "c6" onclick="playPVPGame(this)"> . </td>
</tr>
<tr>
<td id = "c7" onclick="playPVPGame(this)"> . </td>
<td id = "c8" onclick="playPVPGame(this)">. </td>
<td id = "c9" onclick="playPVPGame(this)"> .</td>
</tr>
</table>
<input type="button"
id= "newGame"
value="New Game"/>
<input type="radio"
id= "playerVplayer"
value="Player vs Player"/>
<input type="radio"
id= "playerVcpu"
value="Player vs CPU"/>
Store the current player ('X' or 'O') in a variable instead of reading it from your GUI.
Reading from the GUI is bad practice and you having to ask this question shows why that's the case.
Here you have simplified minimal working example: https://jsfiddle.net/smajl/nr21zd9e/1/
I highly suggest you store the game state in some handy object like:
{
nextTurn: 'X',
isFirstTurn: true,
...
}
You are also ending </body> too soon in your HTML and have many other small or big issues in your code.
Related
I am making a shopping list in my web page where I add the items which I store in localStorage.The items are displayed in a table.The problem is that for each new item added it is showing also the data previously stored again.
My html is:
<form class="market">
<label>Nume produs</label>
<input type="text" id="np">
<label>Cantitate</label>
<input type="text" id="cp">
<input type="button" onclick="addItem();" id="adauga" value="Adaugă" />
</form>
<table>
<tbody id="shopping">
<tr>
<th>Nr.</th>
<th>Name</th>
<th>Quantity</th>
</tr>
And this is the function called on every button click
class Produs{
constructor(id, nume, cantitate){
this.id = id;
this.nume = nume;
this.cantitate = cantitate;
}
}
function addItem(){
let nume = document.getElementById("np").value;
let cantitate = document.getElementById("cp").value;
let produse = localStorage.getItem('produse');
if(produse == null){
produse = [];
}
else{
produse = JSON.parse(produse);
}
produse = produse.map((p) => {
return new Produs(p.id, p.nume, p.cantitate);
});
let lastId = localStorage.getItem('lastId');
if(lastId == null)
{
lastId=1;
}
else{
lastId = JSON.parse(lastId);
}
let id = lastId;
produse.push(new Produs(id, nume, cantitate));
localStorage.setItem('produse',JSON.stringify(produse));
localStorage.setItem('lastId',JSON.stringify(lastId+1));
var jsonData = JSON.parse(localStorage.getItem('produse'));
console.log(jsonData);
for(var i=0; i<jsonData.length; i++)
{
document.getElementById("shopping").innerHTML +="<tr><td>"+jsonData[i].id +"</td><td>" + jsonData[i].nume +"</td><td>"+jsonData[i].cantitate+"</td></tr>";
}
}
I have two divs. One has three elems(John,Snow,Stock).Before each elem,there is a checkbox.Once John is checked,it will display in staff div.When John is unchecked,It is gone. When elems is checked to add_sub(e), it works fine. Once unchecked, it failed which is displays Nana.
My div code :
<div id="role_div">
<table >
<td style="word-break:break-all;"><input type="checkbox" name="uId" value="John">John</td>
<td style="word-break:break-all;"><input type="checkbox" name="uId" value="Snow">Snow</td>
<td style="word-break:break-all;"><input type="checkbox" name="uId" value="Stock">Stock</td>
</table>
</div>
<div id="staff" onclick="this.focus();"></div>
my js code:
var staff = document.getElementById("staff");
function add_sub(el) {
if (el.checked){
currNum += el.value+'<br />';
} else {
currNum -= el.value+'<br />';
}
staff.value = currNum;
}
form.addEventListener("click", function(ev){
if(ev.target.getAttribute("type") == "checkbox"){
add_sub(ev.target);
}
},false);
} `
My code is not the best way.Who can help me ?
I hava solved this problem;
var currNum="" ;
var selected_staff = document.getElementById("selected_staff");
//var form = document.getElementById("transmit_form");
function add_sub(el)
{
if (el.checked)
{
//alert(el.value);
selected_staff.innerHTML += el.value+'<br />';
// selected_staff.innerHTML=currNum;
selectedStaff.value = selected_staff.innerHTML;
alert(selectedStaff.value);
}
else
{
// currNum -= el.value;
var strReplace = el.value+'<br>';
//alert(strReplace);
selected_staff.innerHTML = selected_staff.innerHTML.replace(new RegExp(strReplace,"g"),"");
selectedStaff.value = selected_staff.innerHTML;
alert(selectedStaff.value);
}
}
staff_div.addEventListener("click", function(ev){
if(ev.target.getAttribute("type") == "checkbox"){
add_sub(ev.target);
}
},false);
I am creating a dice game. I am trying to make it so the user can re-click a button after the loop as gone through to reset the page to play again. My gut tells me an if statement is involved but after several attempts I cannot figure out how to set it up.
I was able to change the button value to show "play again" after pressed, I just need to get the page to reload after the user re-presses the button "play again." Any help would be appreciated thanks.
<script>
var rolls = new Array();
var maxMoney = 0;
var rollCountMoney = new Array();
var count = 0;
var startingBet = 0;
var betStarter = new Array();
var mostRoll = 0;
function rollDice() {
do {
count++;
var userInput = parseInt(document.getElementById("bet").value);
var wallet = userInput;
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2;
rolls.push(diceTotal);
rollCountMoney.push(wallet);
if(wallet > maxMoney){
maxMoney = wallet;
mostRoll = count - 1;
}
if(userInput > startingBet){
betStarter.push(userInput);
}
if (diceTotal === 7) {
document.getElementById("bet").value = wallet += 4;
console.log("Round: " + count + " ,you rolled a " + diceTotal + "! You win $4 for a total of: " +wallet);
} else {
document.getElementById("bet").value = wallet -= 1;
console.log("Round: " + count + " ,you rolled a " + diceTotal + "! You lose $1 for a total of: " +wallet);
}
} while (wallet > 0) {}
var displayMsg = count;
var highest = maxMoney;
var highestRoll = mostRoll;
document.getElementById("display").innerHTML = displayMsg;
document.getElementById("starter").innerHTML = betStarter[0];
document.getElementById("highPot").innerHTML = highest;
document.getElementById("rollPot").innerHTML = highestRoll;
var elem = document.getElementById("playAgain");
if (elem.value=="Play Again"){
elem.value = "Play";
}else {elem.value = "Play Again";
}
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="page-head">
<h1 align="center">Lucky Sevens</h1>
</div>
</div>
<div class="container" align="center">
<table class="table-responsive">
<tr>
<th><h3 align="center"><b>Lucky Sevens</b></h3></th>
</tr>
<tr>
<td>
<form>
Starting Bet:
<input id="bet" type="text"/>
</form>
</td>
</tr>
<tr>
<td align="center">
<form>
<input type="button" id="playAgain" onclick="rollDice()" value="Play"></input>
</form>
</td>
</tr>
</table>
<div class="jumbotron" style="width:400px; position: relative; top: 40px">
<table class="dicey" border="1" style="border-color: white">
<caption ALIGN="top">
<h3 align="center" style="color: black"><b><u>Results</u></b></h3>
</caption>
<tr>
<th style= "background-color: grey"><b>Starting Bet</b></th>
<th style= "background-color: grey" id="starter"></th>
</tr>
<tr>
<td>Total rolls before going broke </td>
<td id="display"></td>
</tr>
<tr>
<td>Highest amount won </td>
<td id="highPot"></td>
</tr>
<tr>
<td>Roll count at highest amount won </td>
<td id="rollPot"></td>
</tr>
</table>
</div>
</div>
If I understood your code correctly, you can either reload the page:
function rollDice(){
if (document.getElementById("playAgain").value=="Play Again")
location.reload();
...
or reset it to the initial state:
function rollDice() {
var rolls = new Array();
var maxMoney = 0;
var rollCountMoney = new Array();
var count = 0;
var startingBet = 0;
var betStarter = new Array();
var mostRoll = 0;
document.getElementById("display").innerHTML = "";
document.getElementById("starter").innerHTML = "";
document.getElementById("highPot").innerHTML = "";
document.getElementById("rollPot").innerHTML = "";
...
The simplest way would be to add a second button for play again like
<button id="play-again-button" style="display:none" onclick="location.reload()">play again</button >
Then show it when you need to via
document.getElementById("play-again-button').style.display = "block";
If you want to actually refresh the page. Or tie that button's onclick to a js function that resets things.
For short, I know the question doesn't make that sense, let me clear things up, if i click on the O's it changes to X and vise versa how can i fix this?
Like I don't know how to disable them to stay put and also do you guys know how can I reset the game with a for loop instead of doing it manually
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe</title>
<script text="javascript" src="tic.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<center>
<body>
<h1 style="font-family:arial;">Tic-Tac-Toe</h1>
<table>
<tr>
<td id = "case1" onclick="display_input('case1')"></td>
<td id = "case2" onclick="display_input('case2')"></td>
<td id = "case3" onclick="display_input('case3')"></td>
</tr>
<tr>
<td id = "case4" onclick="display_input('case4')"></td>
<td id = "case5" onclick="display_input('case5')"></td>
<td id = "case6" onclick="display_input('case6')"></td>
</tr>
<tr>
<td id = "case7" onclick="display_input('case7')"></td>
<td id = "case8" onclick="display_input('case8')"></td>
<td id = "case9" onclick="display_input('case9')"></td>
</tr>
</table>
<footer>
<p>Copyright© 2014</p>
</footer>
</body>
</center>
</html>
Javascript:
var player_one = 1;
function display_input(square){
if ( player_one == 1 ){
document.getElementById(square).innerHTML = "X";
player_one = 0;
} else {
document.getElementById(square).innerHTML = "O";
player_one = 1;
}
}
function reset() {
document.getElementById("case1").innerHTML = "";
document.getElementById("case2").innerHTML = "";
document.getElementById("case3").innerHTML = "";
document.getElementById("case4").innerHTML = "";
document.getElementById("case5").innerHTML = "";
document.getElementById("case6").innerHTML = "";
document.getElementById("case7").innerHTML = "";
document.getElementById("case8").innerHTML = "";
document.getElementById("case9").innerHTML = "";
}
You can always check that the square element is empty, and if it is not, then don't perform any action:
function display_input(square) {
//We get the associated DOM element
var element = document.getElementById(square);
//If the element already contains something, then don't change it
if(element.innerHTML != "") return;
if(player_one == 1) {
element.innerHTML = "X";
player_one = 0;
} else {
element.innerHTML = "O";
player_one = 1;
}
}
Overwrite the onclick function of the square by adding the following to display_input(square)
document.getElementById(square).onclick = function() {return};
What is the javascipt code that will edit a text on double click. The process is I have a text and if I double click it, a text box will appear, and if I press enter the word will change depends on what you've type.
Sample
This is sample text. $nbsp;$nbsp; --> if I double click it a textbox will appear.
<input type="text" value="This is sample text." name="" />
Sorry for asking this. I am a newbie in javascript
Here is a great example.
I'm going to paste in the script from that example so that it's preserved in case that link goes away, but you should follow the link -- the article does a great job of breaking the script down line by line and explaining what it does. A great learning opportunity for javascript.
var editing = false;
if (document.getElementById && document.createElement) {
var butt = document.createElement('BUTTON');
var buttext = document.createTextNode('Ready!');
butt.appendChild(buttext);
butt.onclick = saveEdit;
}
function catchIt(e) {
if (editing) return;
if (!document.getElementById || !document.createElement) return;
if (!e) var obj = window.event.srcElement;
else var obj = e.target;
while (obj.nodeType != 1) {
obj = obj.parentNode;
}
if (obj.tagName == 'TEXTAREA' || obj.tagName == 'A') return;
while (obj.nodeName != 'P' && obj.nodeName != 'HTML') {
obj = obj.parentNode;
}
if (obj.nodeName == 'HTML') return;
var x = obj.innerHTML;
var y = document.createElement('TEXTAREA');
var z = obj.parentNode;
z.insertBefore(y,obj);
z.insertBefore(butt,obj);
z.removeChild(obj);
y.value = x;
y.focus();
editing = true;
}
function saveEdit() {
var area = document.getElementsByTagName('TEXTAREA')[0];
var y = document.createElement('P');
var z = area.parentNode;
y.innerHTML = area.value;
z.insertBefore(y,area);
z.removeChild(area);
z.removeChild(document.getElementsByTagName('button')[0]);
editing = false;
}
document.onclick = catchIt;
I wanted to know how it works as I have seen it on many websites. And I build it using jQuery
$(document).dblclick(function(event) {
var id = event.target.id; //id
// var id = $(this).attr('id');
if (id == "") {
console.log("nope");
} else {
id = "#" + id + "";
console.log(typeof(id)); //concatenated with #
text = $(id).text().trim();
console.log(text); //asscociated text
$(id).html('<textarea name="" id="tex" cols="10" rows="1" onkeypress="myFunction(event)">' + text + '</textarea>');
// alert(id);
}
})
function myFunction(event) {
var x = event.code;
var id = $(this).attr('id');
parentId = event.path[1].id;
parentId = "#" + parentId + "";
if (x == 'Enter') {
name = $('#tex').val();
$(parentId).text(name);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container mt-3">
<h2>Striped Rows</h2>
<p>The .table-striped class adds zebra-stripes to a table:</p>
<table class="table table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td id="name1" class="name">
john
</td>
<td id="sirname1">Doe</td>
<td id="email1">john#example.chdm som</td>
</tr>
<tr>
<td id="name2" class="name">Mary</td>
<td id="sirname2">Moe</td>
<td id="email2">mary#example.com</td>
</tr>
<tr>
<td id="name3" class="name">July</td>
<td id="sirname3">Dooley</td>
<td id="email3">july#example.com</td>
</tr>
</tbody>
</table>
</div>