Can't make 2 Player Tic Tac Toe game work JavaScript - javascript

HTML
<div class="container"> <-- div container -->
<div id="div1" onclick="canvasClicked(1);"></div>
<div id="div2" onclick="canvasClicked(2);"></div>
<div id="div3" onclick="canvasClicked(3);"></div>
<div id="div4" onclick="canvasClicked(4);"></div>
<div id="div5" onclick="canvasClicked(5);"></div>
<div id="div6" onclick="canvasClicked(6);"></div>
<div id="div7" onclick="canvasClicked(7);"></div>
<div id="div8" onclick="canvasClicked(8);"></div>
<div id="div9" onclick="canvasClicked(9);"></div>
</div> <-- div container end -->
Css
.container{ /*some css*/
border: 2px solid red;
width: 400px;
height: 400px;
margin: 0 auto;
margin-top: 10%;
}
.container div{
float: left;
height: 132px;
width: 131.3px;
border: 1px solid black;
}
JavaScript
var painted; //global variables
var content;
var winningCombinations;
var theCanvas;
var c;
var cxt;
var w;
var y;
var turn = 0;
var squaresFilled = 0; //global variables end
window.onload = function(){ //instantiating variables
painted = new Array(); //to check if the canvas contains something already
content = new Array(); //to see what the canvas contains 'X' or 'O'
winningCombinations = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],
[1,5,9],[3,5,7]]; //all possible combinations :P
for(var i=0; i<=8; i++){
painted[i] = false;
content[i]=false;
}
}
function canvasClicked(number){
theCanvas = "div" + number; //takes the div Id from html
c = document.getElementById(theCanvas);
if(painted[number-1]==false){
if(turn%2==0){ //use X here
c.innerHTML = '<img src="cross image" alt="x" width=100%
height=100%>';
content[number-1] = 'X'; //storing value in content array
}else{ // user O here
c.innerHTML = '<img src=" O image" height="100%"
width="100%" alt="O">';
content[number-1] = 'O'; //storing value in content array
}
}
else{
alert('This block is already occupied, try another block');
turn--;
squaresFilled--;
}
turn++;
painted[number-1]= true;
squaresFilled++;
checkForWinner(content[number-1]);
if(squaresFilled == 9){
alert('It is a TIE');
playAgain();
}
}
function checkForWinner(symbol){ // This functions seems to be the problem
for(var a = 0; a < winningCombinations.length; a++){
if(content[winningCombinations[a][0]]==symbol &&
content[winningCombinations[a][1]]==symbol && content[winningCombinations[a]
[2]]==symbol){
console.log(symbol + ' won!!');
}
}
}
function playAgain(){ // just another function to reset the game
y=confirm("PLAY AGAIN?");
if(y==true){
location.reload(true);
}else{
alert('Good Bye Then!!');
}
}
It runs normally but the results are not expected. It sometimes randomly make anyone winner(i guess), i can't seem to find the bug, i used debugger as well but i just can't find the problem...any help would be appreciated.
Thanks

In the function checkForWinner change:
if(content[winningCombinations[a][0]]==symbol &&
content[winningCombinations[a][1]]==symbol &&
content[winningCombinations[a][2]]==symbol){
to:
if(content[winningCombinations[a][0]-1]==symbol &&
content[winningCombinations[a][1]-1]==symbol &&
content[winningCombinations[a][2]-1]==symbol){
It would make things easier if you numbered everything from 0 instead of 1. Then you don't need all those -1.

Check your indices.
Either content[0-8] or content[1-9]
winningCombination uses 1-9
but canvasClicked uses 0-8
That's why you getting some strange results

I know I should help you with your code, but I decided to use parts of your code and suggest you an approach:
HTML :
<div class="turnInfo" id="turnInfo">Turn : O</div>
<div class="container">
<div id="div1" cell="1" onclick="canvasClicked(this);"></div>
<div id="div2" cell="2" onclick="canvasClicked(this);"></div>
<div id="div3" cell="3" onclick="canvasClicked(this);"></div>
<div id="div4" cell="4" onclick="canvasClicked(this);"></div>
<div id="div5" cell="5" onclick="canvasClicked(this);"></div>
<div id="div6" cell="6" onclick="canvasClicked(this);"></div>
<div id="div7" cell="7" onclick="canvasClicked(this);"></div>
<div id="div8" cell="8" onclick="canvasClicked(this);"></div>
<div id="div9" cell="9" onclick="canvasClicked(this);"></div>
</div>
CSS :
.turnInfo{
text-align:center;
font-size:40px;
font-weight:bold;
margin-top: 6%;
margin-bottom:10px;
}
.container{ /*some css*/
border: 2px solid red;
width: 400px;
height: 400px;
margin: 0 auto;
}
.container div{
float: left;
height: 102px;
width: 131.3px;
border: 1px solid black;
text-align:center;
padding-top:30px;
font-size:50px;
}
JS :
Variables
var cells = [0,0,0,0,0,0,0,0,0,0]; // make it 10 for the sake of array index
var turn = 'O'; // first turn : O
var infoDiv = document.getElementById('turnInfo');
Toggle the Trun
function toggleTurn(){
turn = turn == 'O' ? 'X' : 'O';
infoDiv.innerHTML = 'Turn : '+turn;
return turn;
}
Canvas Click Handler
function canvasClicked(cell){
var cellIndex = cell.getAttribute('cell');
if(!cells[cellIndex]){
cells[cellIndex] = toggleTurn();
cell.innerHTML = turn; // you can add image here.
checkWinner();
}
}
Check Result function
function checkWinner(){
winningCombinations = [
[1,2,3],
[4,5,6],
[7,8,9],
[1,4,7],
[2,5,8],
[3,6,9],
[1,5,9],
[3,5,7]
]; //all possible combinations :P
for(var index=0; index < winningCombinations.length;index++){
winCond = winningCombinations[index];
if(cells[winCond[0]] != 0 &&
cells[winCond[0]] == cells[winCond[1]] &&
cells[winCond[1]] == cells[winCond[2]])
{
alert(turn + ' is winner');
playAgain();
return;
}
}
var allCellsFilled = 1;
for(var index =1; index < cells.length; index++){
if(!cells[index]){
allCellsFilled = 0;
break;
}
}
if(allCellsFilled){
alert('Game is draw!');
playAgain();
}
}
New Game function
function playAgain(){ // just another function to reset the game
y=confirm("PLAY AGAIN?");
if(y==true){
location.reload(true);
}else{
alert('Good Bye Then!!');
}
}
You can see it here : https://codepen.io/FaridNaderi/pen/awROjY
Hope it helps.

Related

Display different text values in an array with a button

Currently all values in the array are displayed at once when clicking on one of the two buttons. My goal is that the first value is displayed by default and with next/previous the next/previous array entry is displayed.
How can I realize realize this simply?
var array = ["text1", "text2", "text3"];
function next(){
//Next text in Array
document.getElementById('text').innerHTML = array.join('<br />');
}
function prev(){
//Previous text in Array
document.getElementById('text').innerHTML = array.join('<br />');
}
<div id="siggen">
<div style="background-color: orange; height: 150px; width: 300px" id="content">
<p id="text"></p>
</div>
<button id="btnPrev" onclick="prev()">Previous</button>
<button id="btnNext" onclick="next()">Next</button>
</div>
Follow up Question
I looked at the link below from the answer. I have now added new datas to my array and would like to output the id in the left column and the name in the right column of my div.
The name is output correctly in the right column. But the id is not displayed but undefined is displayed. What is the reason for this?
The default values do not work yet either.
const arr = [{_id:1,name:"T-Rex"},{_id:3,name:"Predator X"},{_id:4 ,name:"Velociraptor"},{_id: 6, name:"Triceratops"}]
let currentIndex = 1;
let currentName = arr[0].name;
// initial log
log(currentId)
log(currentName);
function next(){
move();
}
function previous(){
move(false);
}
function move(advance = true){
currentIndex = (currentIndex + (advance ? 1 : -1) + arr.length) % arr.length;
currentName = arr[currentIndex].name;
currentId = arr[currentIndex].id;
log();
}
function log(){
document.getElementById('text').innerHTML = currentName;
document.getElementById('id').innerHTML = currentId;
}
<div style="background-color: orange; height: 300px; width: 500px" id="content">
<div style="background-color: green; height: 100%; width: 250px; float: left">
<p id="id"></p>
</div>
<div style="background-color: lightblue; height: 100%; width: 250px; float: right">
<p id="text"></p>
</div>
</div>
<button onclick="previous();">Previous</button>
<button onclick="next();">Next</button>
Follow up answer:
const arr = [{_id:1,name:"T-Rex"},{_id:3,name:"Predator X"},{_id:4 ,name:"Velociraptor"},{_id: 6, name:"Triceratops"}]
let currentIndex = 1;
let currentId = arr[0]._id;
let currentName = arr[0].name;
// initial log
log(currentId, currentName)
function next(){
move();
}
function previous(){
move(false);
}
function move(advance = true){
currentIndex = (currentIndex + (advance ? 1 : -1) + arr.length) % arr.length;
currentName = arr[currentIndex].name;
currentId = arr[currentIndex]._id;
log(currentId, currentName);
}
function log(currentId, currentName){
document.getElementById('id').innerHTML = currentId;
document.getElementById('text').innerHTML = currentName;
}
<div style="background-color: orange; height: 300px; width: 500px" id="content">
<div style="background-color: green; height: 100%; width: 250px; float: left">
<p id="id"></p>
</div>
<div style="background-color: lightblue; height: 100%; width: 250px; float: right">
<p id="text"></p>
</div>
</div>
<button onclick="previous();">Previous</button>
<button onclick="next();">Next</button>
Something like this?
var array = ["text1", "text2", "text3"];
let currentIndex = 0;
let currentId = array[0];
log(currentId);
function next(){
move();
}
function previous(){
move(false);
}
function move(advance = true){
currentIndex = (currentIndex + (advance ? 1 : -1) + array.length) % array.length;
currentId = array[currentIndex];
log(currentId);
}
function log(currentId){
document.getElementById('text').innerHTML = currentId;
}
<p id="text"></p>
<button onclick="next();">Next</button>
<button onclick="previous();">Previous</button>
Also, I got the code from this question, I only changed the code to make it display the text on the tag p

TicTacToe - trouble alternating players

First mouse click gives me the expected 'x' marker but the next mouse click results in the alert ("Player o: tile has already been selected) even though the grid-item is blank. What am I doing wrong?
In the HTML body, I have created a 3x3 grid, 9 gridItems in total.
$(document).ready(function(){
let grid = $("#grid-container")
let gridItem = $(".grid-item")
function select(){
for (i = 0; i < gridItem.length; i++){
gridItem[i].addEventListener("click", function(){
if ($(this).html() == ""){
$(this).html("x");
nextSelect();
} else {alert ("Player X: tile has already been selected"); select()}
})
}
}
function nextSelect(){
for (i = 0; i < gridItem.length; i++){
gridItem[i].addEventListener("click", function(){
if ($(this).html() == ""){
$(this).html("o");
select();
} else {alert ("Player o: tile has already been selected"); nextSelect()}
})
}
}
select()
});
The addEventListener should be executed only once. Your problem is that you're adding multiple event handlers. A possible version in the snippet bellow.
The idea is that you only need one function and attach it to click event only once per cell, which is done with jQuery .click(callback). To manage the turns you can use a boolean variable (isTurnOfPlayerOne).
$(document).ready(function() {
let isTurnOfPlayerOne = true;
$(".grid-item").click(handleClick);
function handleClick() {
if ($(this).html() == " ") {
let symbol = (isTurnOfPlayerOne ? "x" : "o");
$(this).html(symbol);
} else {
alert("Tile has already been selected");
}
isTurnOfPlayerOne = !isTurnOfPlayerOne;
}
});
.grid-item {
width: 40px;
height: 40px;
display: inline-block;
border: solid 1px #000;
text-align: center;
margin-bottom: 3px;
line-height: 30px;
font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grid-container">
<div class="grid-item"> </div>
<div class="grid-item"> </div>
<div class="grid-item"> </div>
<br/>
<div class="grid-item"> </div>
<div class="grid-item"> </div>
<div class="grid-item"> </div>
<br/>
<div class="grid-item"> </div>
<div class="grid-item"> </div>
<div class="grid-item"> </div>
</div>

How can I update attributes with jQuery?

$(document).ready(function() {
var hero_image = new Array();
hero_image[0] = new Image();
hero_image[0].src = 'assets/images/link.png';
hero_image[0].id = 'image';
hero_image[1] = new Image();
hero_image[1].src = 'assets/images/bongo.png';
hero_image[1].id = 'image';
hero_image[2] = new Image();
hero_image[2].src = 'assets/images/gandondorf.jpg';
hero_image[2].id = 'image';
hero_image[3] = new Image();
hero_image[3].src = 'assets/images/queen.png';
hero_image[3].id = 'image';
var young_hero = ["Link", "Bongo Bongo", "Gandondorf", "Queen Gohma"];
var health = [100, 70, 120, 50];
var attack_power = [];
var counter_power = [];
console.log(hero_image[0]);
function it_is_over_9000(){
for (var i = 0; i < young_hero.length; i++) {
var x = Math.floor(Math.random(attack_power)*20) + 3;
var y = Math.floor(Math.random(attack_power)*10) + 3;
attack_power.push(x);
counter_power.push(y);
}
}
function ready_board(){
it_is_over_9000();
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<button>");
hero_btns.addClass("hero hero_button");
hero_btns.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
hero_btns.text(young_hero[i]);
hero_btns.append(hero_image[i]);
hero_btns.append(health[i]);
$("#buttons").append(hero_btns);
}
}
function char(){
$(".hero_button").on("click", function() {
var hero = $(this);
var hero_select = hero.data('index');
for (var i = 0; i < young_hero.length; i++) {
//var attack = ;
if (i != hero_select){
var enemies = $("<button>");
enemies.addClass("hero enemy");
enemies.attr({
"data-power" : it_is_over_9000(),
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
enemies.text(young_hero[i]);
enemies.append(hero_image[i]);
enemies.append(health[i]);
$("#battle").append(enemies);
}
}
$("#buttons").html($(this).data('name','health','image'));
defender();
});
}
function defender(){
$(".enemy").on("click", function() {
var enemy = $(this);
var enemy_select = enemy.data("index");
console.log(enemy_select);
for (var i = 0; i < young_hero.length; i++) {
if (i == enemy_select) {
var defender = $("<button>");
defender.addClass("hero defender");
defender.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
defender.text(young_hero[i]);
defender.append(hero_image[i]);
defender.append(health[i]);
$("#defend").append(defender);
$(this).remove();
}
}
});
}
$(".defend_button").on("click" , function(){
if($(".defender").data("health") == 0){
$(".defender").remove();
}
$(".defender").attr({
"data-health": $(".defender").data("health") - $(".hero_button").data("attack")
});
});
ready_board();
char();
});
I am trying to make a RPG game and I have the characters being generated the way I want them too but on the $(".defend_button").on("click" , function() at the end it doesn't update the data-health as it should. It only updates once but upon many clicks on the defend-button it doesn't update past the first time.
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Zelda</title>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.2.0.min.js'></script>
<script type = "text/javascript" src = "assets/javascript/game.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<style type="text/css">
.hero { width: 125px; height:150px; border-style: solid; padding: 2px; float: left; margin: 2px; float: left; }
.letter-button-color { color: darkcyan; }
.fridge-color { color: orange; }
#display { margin-top:78px; height:500px; width:220px; margin-left:60px; }
#buttons { padding-top:60px; }
#clear { margin-left: 20px; font-size: 25px; color: black; border-style: solid; width: 100px; }
#image{width: 100px; height: 100px; margin-left: 10px; }
</style>
<body>
<div class="row">
<div class="col-md-8">Select Your Character</div>
</div>
<div class="row">
<div id="buttons" class="col-md-8"></div>
</div>
<div class="row">
<div id="battle" class="col-md-8">
</div>
</div>
<div class="row">
<div class="col-md-8">
<button class="btn btn-primary defend_button">Defend</button>
</div>
</div>
<div class="row">
<div id="defend">
</div>
</div>
</body>
</html>
You have to use .data() to update the health value.
var battleResult = $(".defender").data("health") - $(".hero_button").data("attack");
console.log("battleResult should be: "+battleResult );
$(".defender").data({
"health": battleResult
});
I played a little with your game.
I found how to update the health display below the image too...
Since only updating the data wasn't changing anything on the screen.
So, I left the above code there, for you to see it is effectively working.
But since you have to re-create the button to update health on scrreen... It is kind of useless.
I also fixed the death condition
from if($(".defender").data("health") == 0){
to if($(".defender").data("health") <= 0){
I have to stop here before changing to much things.
See it in CodePen
Check your loop in it_is_over_9000(), because I think it is running uselessly too often.
And a dead defender has to be "buried" (lol).
Because when it is killed, a click on the defend button is kind of ressurrecting it.
;)
Try setting the attribute like this. Also, I recommend putting $(".defender") in a variable so you aren't requerying it each time.
var defender = $(".defender");
var loweredHealth = defender.data("health") - $(".hero_button").data("attack");
defender.attr('data-health`, loweredHealth);
Update:
It looks like the $('.defender') call will return multiple items. You either need to select a specific defender or iterate through them individually like so:
$('.defender').each(function(i, nextDefender) {
var loweredHealth = nextDefender.data("health") - $(".hero_button").data("attack");
nextDefender.attr('data-health`, loweredHealth);
});`

Could help me to resolve mouse events?

<script>
var theNumOfWins;
var part;
theNumOfWins = 0;
function openWindow(){
part = partOfWindow("outlayer",theNumOfWins,"section0");
setCSS(part.css,"-1","400px","400px","#65A8E8","relative","30px","30px","initial","none");
part = partOfWindow("headerOfWindow",theNumOfWins,part.id);
setCSS(part.css,"1","400px","25px","#65A8E8","relative","0px","0px","initial","none");
part = partOfWindow("zoneOfWindowPosition",theNumOfWins,part.id);
setCSS(part.css,"1","204px","22px","transparent","absolute","192px","4px","move","1px solid red");
document.getElementById("5").innerHTML = document.getElementById(part.id).attributes[2].value;
theNumOfWins++;
}
function partOfWindow(name,theNumOfWins,parent){
var id;
var css;
var idAndCSS;
var tag;
var att;
id = name + "Id" + theNumOfWins;
css = name + "CSS";
tag = document.createElement("div");
tag.setAttribute("id",id);
tag.setAttribute("class",css);
document.getElementById(parent).appendChild(tag);
idAndCSS = {
tag: tag,
id: id,
css: css
}
return idAndCSS;
}
function setCSS(className,zIndex,width,height,backgroundColor,position,left,top,cursor,border){
var i;
var cssPart;
cssPart = document.getElementsByClassName(className);
document.getElementById("1").innerHTML = cssPart.length;
document.getElementById("2").innerHTML = cssPart[0];
document.getElementById("3").innerHTML = cssPart[1];
document.getElementById("4").innerHTML = cssPart[2];
for(i=0; i < cssPart.length; i++){
cssPart[i].style.zIndex = zIndex;
cssPart[i].style.width = width;
cssPart[i].style.height = height;
cssPart[i].style.backgroundColor = backgroundColor;
cssPart[i].style.position = position;
cssPart[i].style.left = left;
cssPart[i].style.top = top;
cssPart[i].style.cursor = cursor;
cssPart[i].style.border = border;
}
}
</script>
Hi!!! I need help!!!
I made a object of "div".
and then I added one more "div" into first "div".
second "div" is a red box. You can see it when you click the "+"mark.
But, second "div" has mouse event, and the event does not work.
I want to change mouse cursor when cursor become on the red box.
Why does not the mouse event work?
My last purpose is to make window object.
And there will be a lot of mouse events.
I already made window object similar to this one. However, it also did not work.
How can I try mouse event?
This is my full source: https://drive.google.com/file/d/0B4p8lZSEMXcqZUdacVJyVlBiUWc/view?usp=sharing
This is a CSS issue. Your problem is here:
part = partOfWindow("outlayer",theNumOfWins,"section0");
setCSS(part.css,"-1","400px","400px","#65A8E8","relative","30px","30px","initial","none");
Specifically, where you set the z-index to -1, by doing so you place the div and everything contained in it under the active layer so to speak. As such the hover event doesn't propagate to your div. change this to 1 and the cursor will behave as expected.
var theNumOfWins;
var part;
theNumOfWins = 0;
function openWindow(){
part = partOfWindow("outlayer",theNumOfWins,"section0");
setCSS(part.css,"1","400px","400px","#65A8E8","relative","30px","30px","initial","none");
part = partOfWindow("headerOfWindow",theNumOfWins,part.id);
setCSS(part.css,"1","400px","25px","#65A8E8","relative","0px","0px","initial","none");
part = partOfWindow("zoneOfWindowPosition",theNumOfWins,part.id);
setCSS(part.css,"1","204px","22px","transparent","absolute","192px","4px","pointer","1px solid red");
document.getElementById("5").innerHTML = document.getElementById(part.id).attributes[1].value;
theNumOfWins++;
}
function partOfWindow(name,theNumOfWins,parent){
var id;
var css;
var idAndCSS;
var tag;
var att;
id = name + "Id" + theNumOfWins;
css = name + "CSS";
tag = document.createElement("div");
tag.setAttribute("id",id);
tag.setAttribute("class",css);
document.getElementById(parent).appendChild(tag);
idAndCSS = {
tag: tag,
id: id,
css: css
}
return idAndCSS;
}
function setCSS(className,zIndex,width,height,backgroundColor,position,left,top,cursor,border){
var i;
var cssPart;
cssPart = document.getElementsByClassName(className);
document.getElementById("1").innerHTML = cssPart.length;
document.getElementById("2").innerHTML = cssPart[0];
document.getElementById("3").innerHTML = cssPart[1];
document.getElementById("4").innerHTML = cssPart[2];
for(i=0; i < cssPart.length; i++){
cssPart[i].style.zIndex = zIndex;
cssPart[i].style.width = width;
cssPart[i].style.height = height;
cssPart[i].style.backgroundColor = backgroundColor;
cssPart[i].style.position = position;
cssPart[i].style.left = left;
cssPart[i].style.top = top;
cssPart[i].style.cursor = cursor;
cssPart[i].style.border = border;
}
}
#buttonToOpenWindow{
width:50px;
height:20px;
border: 1px solid #DCDCDC;
margin: 2px;
position:fixed;
left:-1px;
top:0px;
}
#buttonToOpenWindow div.positionOfPlus{
width:20px;
height:20px;
position:absolute;
left:30px;
}
div.wrapOfPlus{
width:20px;
height:20px;
}
div.inside01{
width:15px;
height:5px;
background-color: #B0C4DE;
position:absolute;
left:2.5px;
top:7.5px;
}
div.inside02{
width:5px;
height:15px;
background-color: #B0C4DE;
position:absolute;
left:7.5px;
top:2.5px;
}
<section id="section0">
<div id="buttonToOpenWindow" onclick="openWindow()">
<div class="positionOfPlus">
<div class="wrapOfPlus">
<div class="inside01"></div>
<div class="inside02"></div>
</div>
</div>
</div>
</section>
<footer>
<br><br><br><br><br>
<div style="display:inline-flex;">00: <div id="0"></div></div><br>
<div style="display:inline-flex;">01: <div id="1"></div></div><br>
<div style="display:inline-flex;">02: <div id="2"></div></div><br>
<div style="display:inline-flex;">03: <div id="3"></div></div><br>
<div style="display:inline-flex;">04: <div id="4"></div></div><br>
<div style="display:inline-flex;">05: <div id="5"></div></div><br>
<div style="display:inline-flex;">06: <div id="6"></div></div><br>
<div style="display:inline-flex;">07: <div id="7"></div></div><br>
<div style="display:inline-flex;">08: <div id="8"></div></div><br>
<div style="display:inline-flex;">09: <div id="9"></div></div><br>
<div style="display:inline-flex;">10: <div id="10"></div></div><br>
<div style="display:inline-flex;">11: <div id="11"></div></div><br>
<div style="display:inline-flex;">12: <div id="12"></div></div><br>
<div style="display:inline-flex;">13: <div id="13"></div></div><br>
<div style="display:inline-flex;">14: <div id="14"></div></div><br>
<div style="display:inline-flex;">15: <div id="15"></div></div><br>
<div style="display:inline-flex;">16: <div id="16"></div></div><br>
<div style="display:inline-flex;">17: <div id="17"></div></div><br>
<div style="display:inline-flex;">18: <div id="18"></div></div><br>
<div style="display:inline-flex;">19: <div id="19"></div></div><br>
<div style="display:inline-flex;">20: <div id="20"></div></div><br>
<div style="display:inline-flex;">21: <div id="21"></div></div><br>
<div style="display:inline-flex;">22: <div id="22"></div></div><br>
<div style="display:inline-flex;">23: <div id="23"></div></div><br>
<div style="display:inline-flex;">24: <div id="24"></div></div><br>
<div style="display:inline-flex;">25: <div id="25"></div></div><br>
<div style="display:inline-flex;">26: <div id="26"></div></div><br>
<div style="display:inline-flex;">27: <div id="27"></div></div><br>
<div style="display:inline-flex;">28: <div id="28"></div></div><br>
<div style="display:inline-flex;">29: <div id="29"></div></div><br>
<div style="display:inline-flex;">30: <div id="30"></div></div><br>
<div style="display:inline-flex;">111: <div id="111"></div></div><br>
<div style="display:inline-flex;">222: <div id="222"></div></div><br>
<div style="display:inline-flex;">333: <div id="333"></div></div><br>
<div style="display:inline-flex;">444: <div id="444"></div></div><br>
<div style="display:inline-flex;">555: <div id="555"></div></div><br>
<div style="display:inline-flex;">666: <div id="666"></div></div><br>
<div style="display:inline-flex;">777: <div id="777"></div></div><br>
<div style="display:inline-flex;">888: <div id="888"></div></div><br>
<div style="display:inline-flex;">999: <div id="999"></div></div><br>
</footer>

Random card/Image using buttonjavascript

I want to create a card game using java script. Being a beginner at java script, I am finding great difficulty finding a suitable tutorial for what I am trying to do. When the 'start game' button is selected, I want the computer to produce a random card. I have tried many ways of doing this and have came to no avail. Here is my code.
<html>
<head>
<title> Christmas Assignment </title>
<link rel="stylesheet" type="text/css" href="xmasass_1.css">
<script type = "text/javascript">
function randomImg(){
var myimages= [];
myimages[1] = "cards/1.gif";
myimages[2] = "cards/2.gif";
myimages[3] = "cards/3.gif";
myimages[4] = "cards/4.gif";
myimages[5] = "cards/5.gif";
myimages[6] = "cards/6.gif";
myimages[7] = "cards/7.gif";
myimages[8] = "cards/8.gif";
myimages[9] = "cards/9.gif";
myimages[10] = "cards/10.gif";
myimages[11] = "cards/11.gif";
myimages[12] = "cards/12.gif";
myimages[13] = "cards/13.gif";
function oddTrivia(){
var randomImg = Math.floor(Math.random()*(oddtrivia.length));
document.getElementById('comp').InnerHTML=myimages[randomImg];
}
ar total = 0;
function randomImg(){
var x = Math.floor(Math.random()*13)+1;
document.getElementById('img1').src = 'die'+x+'.gif';
document.getElementById('img2').src = 'die'+y+'.gif';
document.getElementById('score').innerHTML = total;
}
var card1Image;
var card2Image;
var card3Image;
var card4Image;
var card5Image;
var card6Image;
function start(){
var button = document.getElementById("startButton");
button.addEventListener("click", pickCards, false);
card1Image = document.getElementById("1");
card2Image = document.getElementById("2");
card3Image = document.getElementById("3");
card4Image = document.getElementById("4");
card5Image = document.getElementById("5");
card6Image = document.getElementById("6");
}
function pickCards(){
setImage(card1Image);
setImage(card2Image);
setImage(card3Image);
setImage(card4Image);
setImage(card5Image);
setImage(card6Image);
}
function setImage(cardImg){
var cardValue = Math.floor(1 + Math.random() * 13);
cardImg.setAttribute("src", "C:Xmas Assignment/cards/" + cardValue + ".gif");
}
window.addEventListener("load", start, false);
</script>
</head>
<body>
<div id = "settings">
<img src = "settings_img.png" width = "60" height = "60">
</div>
<div id = "bodydiv">
<h1> Card Game</h1>
<div id = "computer">
<img src = " cards/back.gif">
</div>
<div id = "comp" > Computer </div>
<div id ="arrow">
<img src ="arrow2.png" width = "100" height="100">
</div>
<div id = "player">
<img src = " cards/back.gif">
</div>
<div id = "play"> Player </div>
<div id = "kittens">
<button id = "startButton" onclick ="randomImg" > Start Game </button>
<div id = "buttons_1">
<button id ="higher"> Higher
</button>
<button id = "equal"> Equal
</button>
<button id = "lower"> Lower
</button>
</div>
<button id = "draw"> Draw your Card
</button>
<div id = "resetscore"> Reset Score
</div>
</div>
<div id = "score">
</div>
</div>
</body>
</html>
body {
background:#66ccff;
}
h1 {
text-align:center;
}
#settings {
float:right;
margin-top:10px;
}
#bodydiv {
width: 800px;
height:600px;
margin-left:200px;
margin-top:40px;
margin-bottom:60px;
background:#ffccff;
border-radius: 10px;
}
#computer {
border-radius: 10px;
position: absolute;
left:35%;
top:27%;
}
#player {
border-radius: 10px;
position: absolute;
left:55%;
top:27%;
}
#start_game {
width :120px;
height: 55px;
margin-left: 350px;
margin-top:50px;
background:white;
border:1px solid black;
}
#buttons_1 {
text-align: center;
margin-top:20px;
}
#higher {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#equal {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#lower {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#draw {
width:160px;
height:30px;
margin-left:325px;
margin-top: 30px;
border:1px solid black;
background:#FFFFCC;
}
#resetscore {
text-align: center;
margin-top: 40px;
}
#arrow {
margin-left:370px;
margin-top:-130px;
}
#comp {
margin-top:240px;
margin-left:265px;
}
#play{
margin-top:10px;
margin-left:540px;
}
You code is kind of hard to read.
You forgot to close the "{" of your main function.
You are declaring "randomImg" again in the body of the "randomImg" function(use a different name).
You wrote
ar total = 0;
I think you meant to write:
var total = 0;
oddtrivia in the function "OddTrivia" is not defined.
y in the inner randomImg function is not defined.
Having poked a little bit at the code, here is a few things:
Problem no 1: randomImg()
It's hard to know your intentions, but you should likely begin with removing the start of your first function randomImg(){.
Because 1) It does not have an end and 2) If it actually spans everything then this line window.addEventListener("load", start, false); will not load on startup (since it does not get executed until randomImg() gets executed, and by then the page has already loaded.)
Problem no 2: Cannot set property 'src' of null"
Now when the first problem is out of the way, you should see "Uncaught TypeError: Cannot set property 'src' of null" if you look in your console. Yes, USE YOUR CONSOLE. Click on the error to show what causes it. Here it is:
cardImg.setAttribute("src", "C:Xmas Assignment/cards/" + cardValue + ".gif");
This means that cardImg is null. We backtrack the first call of setImage() and find that the variable card1Image is passed in. So that must mean that card1Image also is null. You can check it yourself by adding a console.log('card1Image', card1Image); in your code. Or you add a breakpoint at that point. (Use the sources-tab in chrome dev tools, click at the line-numbering to add a break point. Refresh the page and it will stop at the break point. Now you can mouse-over variables to see their values.)
Let's look at where 'card1Image' is set.
card1Image = document.getElementById("1");
So why is this returning null? Do we even have a id="1" element in the html? That could be the reason. (It is.)
There are more problems, but I'll stop there, but when you have fixed this part AND have no errors please ask again. Always check your errors and if you ask a question here you should provide errors. And when you can also be more specific with your questions.
What might someone else have done differently?
When it comes to playing cards, why not an array of objects?
var cards = [
{ src : 'cards/1.gif', value: 1 },
{ src : 'cards/2.gif', value: 2 },
{ src : 'cards/3.gif', value: 3 },
{ src : 'cards/4.gif', value: 4 }
]; // (You can of course use code to generate it.)
// Then a function to put cards in the player's hand.
var playerHand = _.sample(cards, 2);
console.log(playerHand);
Here I assume lodash, a lightweight library for when you don't want to re-invent the wheel.

Categories

Resources