So I am doing a color picking game with JavaScript. I have the functionality of everything working perfectly. But I noticed a bug. When you first load onto the page or even refresh the page. The values of all squares are purple. If you click new colors or hard or the easy button different rgb values are populating. Why am I getting a default of purple values when I start the page or refresh? I am trying to have it so when the page is started it randomizes the rgb values without me or the user having to hit new colors to initiate the game.
heres my code
~html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="index.css">
<title>Color Game!</title>
</head>
<body>
<h1>The Great <span id="colorDisplay">RGB</span> Color Game</h1>
<div id="stripe">
<button id="reset">New Colors</button>
<span id="message"></span>
<button id="easyBtn">Easy</button>
<button id="hardBtn" class="selected">Hard</button>
</div>
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
~css
body {
background-color: #232323;
margin: 0;
font-family: "Montserrat", "Avenir";
}
.square {
width: 30%;
background: purple;
padding-bottom: 30%;
float: left;
margin: 1.66%;
}
#container {
max-width: 600px;
margin: 0 auto;
}
h1 {
text-align: center;
font-weight: normal;
color: white;
background-color: steelblue;
margin: 0;
}
#stripe {
background-color: white;
height: 30px;
text-align: center;
color: black;
}
.selected {
background: blue;
}
~ JS
var colors = generateRandomColors(numSquares);
var numSquares = 6;
var squares = document.querySelectorAll(".square");
var h1 = document.querySelector("h1");
var pickedColor = pickColor();
var colorDisplay = document.getElementById("colorDisplay");
var messageDisplay = document.querySelector("#message");
var resetButton = document.querySelector("#reset");
var easyBtn = document.getElementById("easyBtn");
var hardBtn = document.getElementById("hardBtn");
easyBtn.addEventListener("click", function(){
hardBtn.classList.remove("selected");
easyBtn.classList.add("selected");
numSquares = 3;
colors = generateRandomColors(numSquares);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
for(var i = 0; i < squares.length; i++) {
if(colors[i]) {
squares[i].style.backgroundColor = colors[i];
} else {
squares[i].style.display = "none";
}
}
})
hardBtn.addEventListener("click", function(){
hardBtn.classList.add("selected");
easyBtn.classList.remove("selected");
numSquares = 6;
colors = generateRandomColors(numSquares);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
for(var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = colors[i];
squares[i].style.display = "block";
}
})
resetButton.addEventListener("click", function(){
// generate all new colors
colors = generateRandomColors(numSquares);
// pick a new random color from the array
pickedColor = pickColor();
// change colorDisplay to match picked color
colorDisplay.textContent = pickedColor;
// change colors of squares
for(var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = colors[i];
}
h1.style.backgroundColor = "steelblue";
})
colorDisplay.textContent = pickedColor;
for(var i = 0; i < squares.length; i++) {
// add initial colors to squares
squares[i].style.backgroundColor = colors[i];
// add click listeners to squares
squares[i].addEventListener("click", function(){
// grab color of clicked square
var clickedColor = this.style.backgroundColor;
// compare color to pickedColor
if(clickedColor === pickedColor){
messageDisplay.textContent = "Correct!";
resetButton.textContent = "Play Again?";
changeColors(clickedColor);
h1.style.backgroundColor = clickedColor;
} else {
this.style.backgroundColor = "#232323";
messageDisplay.textContent = "Try Again";
}
});
}
function changeColors(color) {
//loop through all squares
for(var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = color;
}
}
function pickColor() {
var random = Math.floor(Math.random() * colors.length);
return colors[random];
}
function generateRandomColors(num) {
// make an array
var arr = [];
// repeat num times
for(var i = 0; i < num; i++) {
arr.push(randomColor());
}
return arr;
}
function randomColor() {
// pick a "red" from 0 - 255
var r = Math.floor(Math.random() * 256);
// pick a "green" from 0 - 255
var g = Math.floor(Math.random() * 256);
// pick a "blue" from 0 - 255
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + ", " + g + ", " + b + ")";
}
Your CSS hard codes the purple:
.square {
width: 30%;
background: purple;
You need to add an event handler for when the page loads to call your color changing code like this:
window.addEventListener("DOMContentLoaded", function(){
// Call color changing code here
});
Make sure numSquares is declared before colors.
So
var colors = generateRandomColors(numSquares);
var numSquares = 6;
becomes
var numSquares = 6;
var colors = generateRandomColors(numSquares);
Related
<!doctype html>
<html>
<head>
<title>Get home</title>
<style>
table {
border-collapse: collapse;
}
td {
border: solid 1px #888;
width: 30px;
height: 30px;
font-family: sans-serif;
font-size: calc(30px/4.0 + 1px);
text-align: center;
}
.cell0 {
background: #88ff99;
}
.cell1 {
background: #116615;
}
.player {
background: #e11;
}
.home {
background: white;
}
.status {
font-size: 15pt;
font-family: Arial;
}
</style>
<script>
// Will be initialised to a 2-dimensional array
var gameBoard = [];
// Size of game
var size = 10;
// Current fuel and supply
var fuel = 20;
var supply = 0;
// Current position of player (start in the bottom-right)
var positionX = size - 1;
var positionY = size - 1;
// Whether we are playing the game
var playing = true;
// Use this function to make a move where x and y represent the direction of
// a move, e.g.
// move(-1, 0) means going left
// move(1, 0) means going right
// move(0, -1) means going up
// move(0, 1) means going down
function move(x, y) {
//
if (positionX + x < size && positionX + x >= 0 &&
positionY + y < size && positionY + y >= 0) {
// Move is within the board
}
}
// Use this function to update the status
function updateStatus() {
document.getElementById("fuel").innerHTML = fuel;
document.getElementById("store").innerHTML = supply;
}
function setup() {
// Set the gameboard to be empty
gameBoard = [];
var board = document.getElementById("board");
for (var i = 0; i < size; i++) {
// Create a new row of the game
var htmlRow = document.createElement("tr");
board.appendChild(htmlRow);
var row = []
for (var j = 0; j < size; j++) {
// Chose a random type of cell
var type = Math.round(Math.random());
var cell = document.createElement("td");
cell.className = "cell" + type;
// Add the cell to the row
htmlRow.appendChild(cell);
row.push(cell);
}
gameBoard.push(row);
}
// Setup the player
gameBoard[size-1][size-1].className = "player";
// Setup the home
gameBoard[0][0].className = "home";
gameBoard[0][0].innerHTML = "HOME";
// Register the listener and update the state
updateStatus();
document.body.addEventListener("keydown", keyEvent);
}
</script>
</head>
<body onLoad="setup();">
<div class="status">Fuel: <span id="fuel"></div>
<div class="status">Store: <span id="store"></div>
<table id="board"></table>
<div class="status" id="outcome"></div>
</body>
</html>
I'm creating a simple game on HTML, and I can't think of how to get the move function to work, while it automatically updates the game and the map, is anyone able to help. I'm new to coding and I genuinely cant fathom what code to put in to make the move function work, whether it be using arrow keys or creating buttons to make the entity move.
Without making too many changes to the way you have things set up, I added a function that will add the "player" class to elements based on "wsad" or arrow key presses.
<!doctype html>
<html>
<head>
<title>Get home</title>
<style>
table {
border-collapse: collapse;
}
td {
border: solid 1px #888;
width: 30px;
height: 30px;
font-family: sans-serif;
font-size: calc(30px/4.0 + 1px);
text-align: center;
}
.cell0 {
background: #88ff99;
}
.cell1 {
background: #116615;
}
.player {
background: #e11;
}
.home {
background: white;
}
.status {
font-size: 15pt;
font-family: Arial;
}
</style>
<script>
// Will be initialised to a 2-dimensional array
var gameBoard = [];
// Size of game
var size = 10;
// Current fuel and supply
var fuel = 20;
var supply = 0;
// Current position of player (start in the bottom-right)
var positionX = size - 1;
var positionY = size - 1;
// Whether we are playing the game
var playing = true;
function move(direction) {
let x = positionX;
let y = positionY;
switch (direction) {
case "left":
x--;
break;
case "right":
x++;
break;
case "up":
y--;
break;
case "down":
y++;
break;
}
const validMove =
x < size &&
x >= 0 &&
y < size &&
y >= 0;
if (!validMove) return console.error(
"What are you trying to do?" + "\n" +
"Break the implied rules of a game?" + "\n" +
"I expect more from you" + "\n" +
"That's a wall you dummy!"
);
positionX = x;
positionY = y;
gameBoard[y][x].classList.add("player");
}
// Use this function to update the status
function updateStatus() {
document.getElementById("fuel").innerText = fuel;
document.getElementById("store").innerText = supply;
}
function keyEvent(e) {
const keyMoveDict = {
"ArrowLeft": "left",
"ArrowRight": "right",
"ArrowUp": "up",
"ArrowDown": "down",
"a": "left",
"d": "right",
"w": "up",
"s": "down",
}
const movement = keyMoveDict[e.key];
if (movement) move(movement);
}
function setup() {
// Set the gameboard to be empty
gameBoard = [];
var board = document.getElementById("board");
for (var i = 0; i < size; i++) {
// Create a new row of the game
var htmlRow = document.createElement("tr");
board.appendChild(htmlRow);
var row = []
for (var j = 0; j < size; j++) {
// Chose a random type of cell
var type = Math.round(Math.random());
var cell = document.createElement("td");
cell.className = "cell" + type;
// Add the cell to the row
htmlRow.appendChild(cell);
row.push(cell);
}
gameBoard.push(row);
}
// Setup the player
gameBoard[size-1][size-1].className = "player";
// Setup the home
gameBoard[0][0].className = "home";
gameBoard[0][0].innerHTML = "HOME";
// Register the listener and update the state
updateStatus();
document.body.addEventListener("keydown", keyEvent);
}
</script>
</head>
<body onLoad="setup();">
<div class="status">Fuel: <span id="fuel"></span></div>
<div class="status">Store: <span id="store"></span></div>
<table id="board"></table>
<div class="status" id="outcome"></div>
</body>
</html>
Can anyone help me on Javascript coding? Lines13-14 i try to create 9x div(class="square") but i get 18 childnodes when i check container from console. It also prints 18 in total?
Second issue is about resetbutton. When i try to clear container childnodes to start a new game it gives error. (maybe there's no need to add some code to clear container?) Thank you.
// Create div elements inside container according to difficulty
for (let i = 0; i < difficulty; i++) {
container.appendChild(createDiv());
}
function createDiv() {
// create a div element and assign "square" class
let div = document.createElement("div");
div.classList.toggle("square");
return div;
};
function resetGame () {
// Clean boxes
for (let i = 0; i < difficulty; i++) {
container.removeChild(container.childNodes[i]);
}
var buttonReset = document.querySelector("#reset");
var container = document.querySelector("#boxes");
var difficulty = 9;
var h1 = document.querySelectorAll("h1");
var message = document.querySelector("#message");
var pickedColor = "";
// Listener for reset button
buttonReset.addEventListener("click", resetGame());
function newGame () {
// Create div elements inside container according to difficulty
for (let i = 0; i < difficulty; i++) {
container.appendChild(createDiv());
}
// Select all squares.
var squares = document.querySelectorAll(".square");
// Create and fill colors array
let colors = createColors();
// Pick a random color from colors
pickedColor = colors[
Math.floor(Math.random() * squares.length)
];
// Update text on screen
colorDisplay.textContent = pickedColor;
// Draw squares with colors and check clicked color.
for(let i = 0; i < squares.length; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = colors[i];
// Add click events to squares
squares[i].addEventListener("click", function() {
// check if clickedColor is pickedColor.
if (this.style.backgroundColor === pickedColor) {
message.textContent = "Yes, you've found the color";
//change all square colors to pickedColor
for (let i = 0; i < difficulty; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = pickedColor;
};
h1.forEach(function(item) {
item.style.backgroundColor = pickedColor;
});
} else {
message.textContent = "Please try again!"
this.style.backgroundColor = "#232323";
}
});
};
}
function createColors() {
let createdList = [];
for(let i = 0; i < difficulty; i++) {
createdList.push("rgb(" +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ")");
};
return createdList;
};
function createDiv() {
// create a div element and assign "square" class
let div = document.createElement("div");
div.classList.toggle("square");
return div;
};
function resetGame () {
/// Clean boxes
for (let i = 0; i < difficulty; i++) {
container.removeChild(container.childNodes[i]);
}
// Create new game
newGame();
};
newGame(); // Only for first run
body {
background-color: #232323;
}
h1 {
color: white;
}
.square {
background: greenyellow;
float: left;
margin: 1.66%;
padding-bottom: 30%;
width: 30%;
}
#container {
margin: 0 auto;
max-width: 800px;
}
#stripe {
background: white;
color: black;
height: 30px;
text-align: center;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Color Game</title>
</head>
<body>
<h1 class="display-4">THE GREAT</h1>
<h1 class="display-2"><span id="colorDisplay">RGB(175, 203, 2)</span></h1>
<h1 class="display-4">GUESSING GAME</h1>
<div id="stripe">
<button id="reset">NEW COLORS</button>
<span id="message"></span>
</div>
<!-- Color boxes -->
<div class="container" id="boxes"></div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#2.0.0-next.4/dist/umd/index.min.js" integrity="sha384-AWosBrv7t83vzfQDzCZrtcVWT9tFVGuP7uL1EqwhTLscYSCGShI9+FOYrSL1wQYT" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
For the first problem of having 18 divs instead of 9 in is because newGame method is called twice. One is at the end of code, the other one is in this line:
// Listener for reset button
buttonReset.addEventListener("click", resetGame());
The resetGame method is called there but it should be just passed as it is:
buttonReset.addEventListener("click", resetGame);
For the second problem of resetGame method not working as expected is that you are modifying the array that is being accessed (container.childNodes) in the loop.
That makes your i skip the element next to the each removed one.
Your difficulty may eventually become larger than childNodesCount
One solution is that do not remove items immediately, accumulate them in an array array and then remove based on that array
const toBeRemoved = []
for (let i = 0; i < difficulty; i++) {
toBeRemoved.push(container.childNodes[i]);
}
toBeRemoved.forEach(child => {
container.removeChild(child);
})
OR, another solution is that copy the childNodes to another variable so when you modify the original childNodes the copied array does not get affected:
const arrayOfChildren = Array.from(container.childNodes)
for (let i = 0; i < difficulty; i++) {
container.removeChild(arrayOfChildren[i]);
}
After fixing both problems:
var buttonReset = document.querySelector("#reset");
var container = document.querySelector("#boxes");
var difficulty = 9;
var h1 = document.querySelectorAll("h1");
var message = document.querySelector("#message");
var pickedColor = "";
// Listener for reset button
buttonReset.addEventListener("click", resetGame);
function newGame() {
// Create div elements inside container according to difficulty
for (let i = 0; i < difficulty; i++) {
container.appendChild(createDiv());
}
// Select all squares.
var squares = document.querySelectorAll(".square");
// Create and fill colors array
let colors = createColors();
// Pick a random color from colors
pickedColor = colors[
Math.floor(Math.random() * squares.length)
];
// Update text on screen
colorDisplay.textContent = pickedColor;
// Draw squares with colors and check clicked color.
for (let i = 0; i < squares.length; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = colors[i];
// Add click events to squares
squares[i].addEventListener("click", function() {
// check if clickedColor is pickedColor.
if (this.style.backgroundColor === pickedColor) {
message.textContent = "Yes, you've found the color";
//change all square colors to pickedColor
for (let i = 0; i < difficulty; i++) {
// Add initial colors to squares
squares[i].style.backgroundColor = pickedColor;
};
h1.forEach(function(item) {
item.style.backgroundColor = pickedColor;
});
} else {
message.textContent = "Please try again!"
this.style.backgroundColor = "#232323";
}
});
};
}
function createColors() {
let createdList = [];
for (let i = 0; i < difficulty; i++) {
createdList.push("rgb(" +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ", " +
Math.floor(Math.random() * 256) + ")");
};
return createdList;
};
function createDiv() {
// create a div element and assign "square" class
let div = document.createElement("div");
div.classList.toggle("square");
return div;
};
function resetGame() {
/// Clean boxes
const arrayOfChildren = Array.from(container.childNodes)
for (let i = 0; i < difficulty; i++) {
container.removeChild(arrayOfChildren[i]);
}
// Create new game
newGame();
};
newGame(); // Only for first run
body {
background-color: #232323;
}
h1 {
color: white;
}
.square {
background: greenyellow;
float: left;
margin: 1.66%;
padding-bottom: 30%;
width: 30%;
}
#container {
margin: 0 auto;
max-width: 800px;
}
#stripe {
background: white;
color: black;
height: 30px;
text-align: center;
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Color Game</title>
</head>
<body>
<h1 class="display-4">THE GREAT</h1>
<h1 class="display-2"><span id="colorDisplay">RGB(175, 203, 2)</span></h1>
<h1 class="display-4">GUESSING GAME</h1>
<div id="stripe">
<button id="reset">NEW COLORS</button>
<span id="message"></span>
</div>
<!-- Color boxes -->
<div class="container" id="boxes"></div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#2.0.0-next.4/dist/umd/index.min.js" integrity="sha384-AWosBrv7t83vzfQDzCZrtcVWT9tFVGuP7uL1EqwhTLscYSCGShI9+FOYrSL1wQYT" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
I am making on an RGB Guessing game hence I have added easy and hard button for the same wherein the easy mode will have random colored 3 square blocks while on the other hand, the hard mode will have 6 colored random blocks each time the hard and easy button is clicked but my class list is not working and showing the error also the following code for the easy button isn't effective.
HTML file:
<!DOCTYPE html>
<html>
<head>
<title>RGB Guess Game</title>
<link rel="stylesheet" type="text/css" href="RGB.css">
</head>
<body>
<h1> The Great <span id="colorDisplay">RGB</span> Game</h1>
<div id="stripe">
<button id="reset">New Color</button>
<span id="message"></span>
<button id="easybtn">Easy</button>
<button id="hardbtn" class="selects">Hard</button>
</div>
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<script src="RGB.js"></script>
</body>
</html>
Javascript file:
var numSquares=6;
var color = generateRandomColor(numSquares);
var square=document.querySelectorAll(".square");
var colorDisplay=document.getElementById("colorDisplay");
var pickcolor=selectedColor();
var messageDisplay= document.querySelector("#message");
var h1= document.querySelector("h1");
var resetButton= document.querySelector("#reset");
var easybtn= document.querySelector("#easybtn");
var hardbtn= document.querySelector("#hardbtn");
easybtn.addEventListener("click",function(){
easybtn.classlist.add("selects");
hardbtn.classlist.remove("selects");
numSquares=3;
color=generateRandomColor(numSquares);
pickcolor=selectedColor();
colorDisplay.textContent=pickcolor;
for(var i=0; i<square.length;i++)
{
if(color[i])
{
//square[i].style.display="block";
square[i].style.backgroundColor=color[i];
}
else
{
square[i].style.display="none";
}
}
});
hardbtn.addEventListener("click",function(){
hardbtn.classlist.add("selects");
easybtn.classlist.remove("selects");
numSquares=6;
color=generateRandomColor(numSquares);
pickcolor=selectedColor();
colorDisplay.textContent=pickcolor;
for(var i=0; i<square.length;i++)
{
square[i].style.backgroundColor=color[i];
square[i].style.display="block";
}
});
resetButton.addEventListener("click",function()
{
//generate random colors
color = generateRandomColor(numSquares);
//pick color
pickcolor= selectedColor();
//change the color
colorDisplay.textContent=pickcolor;
for(var i=0; i<square.length; i++)
{
//color set intially
square[i].style.backgroundColor=color[i];
}
h1.style.backgroundColor="#232323";
});
for(var i=0; i<square.length; i++)
{
//color set intially
square[i].style.backgroundColor=color[i];
//event listener being added
square[i].addEventListener("click",function(){
//grab the clicked color
var clickedColor = this.style.backgroundColor;
//compare it with the picked color
if(clickedColor === pickcolor)
{
messageDisplay.textContent="Correct";
resetButton.textContent="Play again?"
changeColor(clickedColor);
h1.style.backgroundColor=clickedColor;
}
else
{
this.style.backgroundColor = "#232323";
messageDisplay.textContent="Try Again";
}
});
}
function changeColor(color)
{
for(var i=0; i<square.length; i++)
{
//color set intially
square[i].style.backgroundColor=color;
}
}
function selectedColor()
{
var selected=Math.floor(Math.random()*color.length);
return color[selected];
}
function generateRandomColor(num)
{
//make an array
var arr=[];
//loop through num times
for(var i=0;i<num;i++)
{
arr.push(randomColor());
}
//return the array
return arr;
}
function randomColor()
{
//random selction for red from 0 to 256
var r= Math.floor(Math.random()*256);
//random selction for green from 0 to 256
var g= Math.floor(Math.random()*256);
//random selction for blue from 0 to 256
var b= Math.floor(Math.random()*256);
return "rgb(" + r + ", " + g + ", " + b + ")";
}
CSS file:
body{
background-color: #232323;
}
.square{
width: 30%;
background-color: purple;
padding-bottom: 30%;
margin: 1.66%;
float:left;
}
#container
{
margin: 0 auto;
max-width: 600px;
}
h1
{
color : white;
}
#stripe
{
height: 30px;
background: white;
text-align: center;
}
.selects
{
background: blue;
}
The classList property suppose to be camel case, it should fix it,
great game by the way)
it will be classList not classlist
function changeColor(color)
{
for(var i=0; i<square.length; i++)
{
//color set intially
square[i].style.backgroundColor=color;
}
}
function selectedColor()
{
var selected=Math.floor(Math.random()*color.length);
return color[selected];
}
function generateRandomColor(num)
{
//make an array
var arr=[];
//loop through num times
for(var i=0;i<num;i++)
{
arr.push(randomColor());
}
//return the array
return arr;
}
function randomColor()
{
//random selction for red from 0 to 256
var r= Math.floor(Math.random()*256);
//random selction for green from 0 to 256
var g= Math.floor(Math.random()*256);
//random selction for blue from 0 to 256
var b= Math.floor(Math.random()*256);
return "rgb(" + r + ", " + g + ", " + b + ")";
}
var numSquares=6;
var color = generateRandomColor(numSquares);
var square=document.querySelectorAll(".square");
var colorDisplay=document.getElementById("colorDisplay");
var pickcolor=selectedColor();
var messageDisplay= document.querySelector("#message");
var h1= document.querySelector("h1");
var resetButton= document.querySelector("#reset");
var easybtn= document.querySelector("#easybtn");
var hardbtn= document.querySelector("#hardbtn");
easybtn.addEventListener("click",function(){
console.log(this);
this.classList.add("selects");
hardbtn.classList.remove("selects");
numSquares=3;
color=generateRandomColor(numSquares);
pickcolor=selectedColor();
colorDisplay.textContent=pickcolor;
for(var i=0; i<square.length;i++)
{
if(color[i])
{
//square[i].style.display="block";
square[i].style.backgroundColor=color[i];
}
else
{
square[i].style.display="none";
}
}
});
hardbtn.addEventListener("click",function(){
hardbtn.classList.add("selects");
easybtn.classList.remove("selects");
numSquares=6;
color=generateRandomColor(numSquares);
pickcolor=selectedColor();
colorDisplay.textContent=pickcolor;
for(var i=0; i<square.length;i++)
{
square[i].style.backgroundColor=color[i];
square[i].style.display="block";
}
});
resetButton.addEventListener("click",function()
{
//generate random colors
color = generateRandomColor(numSquares);
//pick color
pickcolor= selectedColor();
//change the color
colorDisplay.textContent=pickcolor;
for(var i=0; i<square.length; i++)
{
//color set intially
square[i].style.backgroundColor=color[i];
}
h1.style.backgroundColor="#232323";
});
for(var i=0; i<square.length; i++)
{
//color set intially
square[i].style.backgroundColor=color[i];
//event listener being added
square[i].addEventListener("click",function(){
//grab the clicked color
var clickedColor = this.style.backgroundColor;
//compare it with the picked color
if(clickedColor === pickcolor)
{
messageDisplay.textContent="Correct";
resetButton.textContent="Play again?"
changeColor(clickedColor);
h1.style.backgroundColor=clickedColor;
}
else
{
this.style.backgroundColor = "#232323";
messageDisplay.textContent="Try Again";
}
});
}
body{
background-color: #232323;
}
.square{
width: 30%;
background-color: purple;
padding-bottom: 30%;
margin: 1.66%;
float:left;
}
#container
{
margin: 0 auto;
max-width: 600px;
}
h1
{
color : white;
}
#stripe
{
height: 30px;
background: white;
text-align: center;
}
.selects
{
background: blue;
}
<h1> The Great <span id="colorDisplay">RGB</span> Game</h1>
<div id="stripe">
<button id="reset">New Color</button>
<span id="message"></span>
<button id="easybtn" >Easy</button>
<button id="hardbtn" class="selects">Hard</button>
</div>
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
I don't know actual flow, but some changes in JS made this easy and hard button work.
var numSquares=6;
var color = generateRandomColor(numSquares);
var square=document.querySelectorAll(".square");
var colorDisplay=document.getElementById("colorDisplay");
var pickcolor=selectedColor();
var messageDisplay= document.querySelector("#message");
var h1= document.querySelector("h1");
var resetButton= document.querySelector("#reset");
var easybtn= document.getElementById("easybtn");
var hardbtn= document.getElementById("hardbtn");
easybtn.addEventListener("click",function(){
console.log('working');
document.getElementById("easybtn").classList.add("selects");
document.getElementById("hardbtn").classList.remove("selects");
numSquares=3;
color=generateRandomColor(numSquares);
pickcolor=selectedColor();
colorDisplay.textContent=pickcolor;
for(var i=0; i<square.length;i++)
{
if(color[i])
{
//square[i].style.display="block";
square[i].style.backgroundColor=color[i];
}
else
{
square[i].style.display="none";
}
}
});
hardbtn.addEventListener("click",function(){
document.getElementById("hardbtn").classList.add("selects");
document.getElementById("easybtn").classList.remove("selects");
numSquares=6;
color=generateRandomColor(numSquares);
pickcolor=selectedColor();
colorDisplay.textContent=pickcolor;
for(var i=0; i<square.length;i++)
{
square[i].style.backgroundColor=color[i];
square[i].style.display="block";
}
});
resetButton.addEventListener("click",function()
{
//generate random colors
color = generateRandomColor(numSquares);
//pick color
pickcolor= selectedColor();
//change the color
colorDisplay.textContent=pickcolor;
for(var i=0; i<square.length; i++)
{
//color set intially
square[i].style.backgroundColor=color[i];
}
h1.style.backgroundColor="#232323";
});
for(var i=0; i<square.length; i++)
{
//color set intially
square[i].style.backgroundColor=color[i];
//event listener being added
square[i].addEventListener("click",function(){
//grab the clicked color
var clickedColor = this.style.backgroundColor;
//compare it with the picked color
if(clickedColor === pickcolor)
{
messageDisplay.textContent="Correct";
resetButton.textContent="Play again?"
changeColor(clickedColor);
h1.style.backgroundColor=clickedColor;
}
else
{
this.style.backgroundColor = "#232323";
messageDisplay.textContent="Try Again";
}
});
}
function changeColor(color)
{
for(var i=0; i<square.length; i++)
{
//color set intially
square[i].style.backgroundColor=color;
}
}
function selectedColor()
{
var selected=Math.floor(Math.random()*color.length);
return color[selected];
}
function generateRandomColor(num)
{
//make an array
var arr=[];
//loop through num times
for(var i=0;i<num;i++)
{
arr.push(randomColor());
}
//return the array
return arr;
}
function randomColor()
{
//random selction for red from 0 to 256
var r= Math.floor(Math.random()*256);
//random selction for green from 0 to 256
var g= Math.floor(Math.random()*256);
//random selction for blue from 0 to 256
var b= Math.floor(Math.random()*256);
return "rgb(" + r + ", " + g + ", " + b + ")";
}
I want to add 10 points when blue box goes into brown box.
I tried to set score = 0 and points to add = 10 but it doesn't work.
I alert '+10 points' and it shows me the alert so I guess the problem is the DOM ?!?
Any suggestions ?
Thanks !
let moveCounter = 0;
let score = 0;
let obs = 10;
document.getElementById('score').textContent = '0';
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 49; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var obstacles = [];
while (obstacles.length < 10) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob")
}
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
$(drawPone).addClass("p-0")
}
}
var addPoints = $('#score');
$('#button_right').on('click', function() {
if ($(".p-0").hasClass("ob")) {
alert('add +10 points !!!')
addPoints.text( parseInt(addPoints.text()) + obs );
}
moveCounter += 1;
if ($(".p-0").hasClass("ob")) {
}
$pOne = $('.p-0')
$pOneNext = $pOne.next();
$pOne.removeClass('p-0');
$pOneNext.addClass('p-0');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.ob {
background-color: brown;
}
.p-0 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box">
</div>
<div class="move">
<button id="button_right">right</button><br>
</div>
<div id="score">
</div>
Thank you very much! I am new to JavaScript/ JQuery
Thank you very much!
You are trying to change the HTML inside of the div with id "score".
Selecting the css element using $("#id") retrieves the DOM element and not its contents so adding the score directly to it has no consequences.
What you want to do is: update the score variable and then set the HTML inside the div to the score value.
So instead of just:
addPoints += obs
you should
score += obs
addPoints.html(score)
I am trying to create a multicolored progress bar where I want to show the progress with incremental percentage value and respective color.
I am able to fetch the data from JSON and plot the progress bar but setInterval function is not working.
Currently I am writing the setInterval function inside the for loop.
For that may be its not working.
Please help me out on this and let me know if any other approaches is there.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
#dist_bar {
height: 30px;
width: 100%;
border: 1px solid #222;
position: relative;
margin: auto;
}
</style>
</head>
<body>
<div id="dist_bar"></div>
<script type="text/javascript">
var json_data = [
{
"color": "red",
"percentage": 30,
"speed": 10,
}, {
"color": "yellow",
"percentage": 20,
"speed": 10,
}
]
function draw_ProgressBar(parms) {
var arrayLength = json_data.length;
var progress = setInterval(progress, 1000);
var i = 0;
for (var i = 0; i < arrayLength; i++) {
var docid = document.getElementById('dist_bar');
var innerDiv = document.createElement('div');
innerDiv.id = 'dist' + i;
dist_bar.appendChild(innerDiv);
innerDiv.style.height = "30px";
innerDiv.style.float = "left";
innerDiv.style.backgroundColor = json_data[i].color;
var p = 0; //var percent = '';
var percent = json_data[i].percentage;
var inc = setInterval(progress,10);
(function progress(i) {
if (p != percent) {
for (var j = 0; j < percent; j++) {
p++;
var val = document.getElementById('dist' + i);
val.innerHTML = p + "%";
val.style.width = p + "%";
}
} else {
clearInterval(progress);
}
}(i));
}
}draw_ProgressBar(json_data)
</script>
</body>
</html>