Having an issue with changing classes. I can get it to work if I hardcode pixels into the style change but wanted a cleaner version using classes and CSS. The goal is to have the pixel change sizes larger and smaller due to the value of healthPercent in width. This part works but the trouble part is changing the classes to change the color of the bar. For some reason, it does not pass through the if statements correctly and just stays green until death (zero or less for healthPercent), when it reaches zero and then turns red. I can't quite figure out why it passes through the first if check but not the rest. Any ideas on how to fix this?
EDIT: I'm working on a game. just to clarify.
JAVASCRIPT
displayLifeBar = function ()
{
pixelMod = 2.3; //added definition here but global on full code
healthPercent = 130; //added here for example but passed down
lifeBar = 'player_lifebar';
document.getElementById(lifeBar).style.width = healthPercent + 'px';
var criticalLife = 25 * pixelMod;
var lowLife = 50 * pixelMod;
var hurtLife = 75 * pixelMod;
if (healthPercent <= 0){
document.getElementById(lifeBar).className = '';
}
else if (healthPercent < criticalLife){
document.getElementById(lifeBar).className = 'lifebar critical';
}
else if (healthPercent < lowLife){
document.getElementById(lifeBar).className = 'lifebar low';
}
else if (healthPercent < hurtLife){
document.getElementById(lifeBar).className = 'lifebar hurt';
}
else
{
document.getElementById(lifeBar).className = 'lifebar';
}
}
CSS
/* LIFEBAR COLORS STARTS */
.lifebar{
height:20px;
background-color: forestgreen;
}
.lifebar.hurt{
background-color: gold;
}
.lifebar.low{
background-color: orange;
}
.lifebar.critical{
background-color: red;
}
/* LIFEBAR COLORS ENDS */
Your code snippet seems to be working from what you described - assuming your HTML just looks like <div id='player_lifebar'></div>.
var pixelMod = 2.3;
var healthPercent = 10;
var lifeBar = 'player_lifebar';
displayLifeBar = function ()
{
document.getElementById(lifeBar).style.width = healthPercent + 'px';
var criticalLife = 25 * pixelMod;
var lowLife = 50 * pixelMod;
var hurtLife = 75 * pixelMod;
if (healthPercent <= 0){
document.getElementById(lifeBar).className = '';
} else if (healthPercent < criticalLife){
document.getElementById(lifeBar).className = 'lifebar critical';
} else if (healthPercent < lowLife){
document.getElementById(lifeBar).className = 'lifebar low';
} else if (healthPercent < hurtLife){
document.getElementById(lifeBar).className = 'lifebar hurt';
} else {
document.getElementById(lifeBar).className = 'lifebar';
}
}
displayLifeBar();
// for testing:
function modifyHealth(points) {
healthPercent = healthPercent + points;
displayLifeBar(); //re-render healthbar
}
document.getElementById('heal').addEventListener('click', function() { modifyHealth(10) });
document.getElementById('attack').addEventListener('click', function() { modifyHealth(-10) });
.lifebar{
height:20px;
background-color: forestgreen;
}
.lifebar.hurt{
background-color: gold;
}
.lifebar.low{
background-color: orange;
}
.lifebar.critical{
background-color: red;
}
<div id='player_lifebar'></div>
<!-- for testing -->
<br>
<button id='heal'>♡ heal (+10)</button>
<button id='attack'>🗡 attack (-10)</button>
Related
I have this little block that I move around using javascript code. It works all good except if I keep moving it, it can easily get out of the box where it is supposed to be.
Can I prevent this somehow? So no matter how far I want to move it, it will stay stuck inside of the container/box ?
Here's my snippet code:
/// store key codes and currently pressed ones
var keys = {};
keys.UP = 38;
keys.LEFT = 37;
keys.RIGHT = 39;
keys.DOWN = 40;
/// store reference to character's position and element
var character = {
x: 100,
y: 100,
speedMultiplier: 2,
element: document.getElementById("character")
};
var is_colliding = function(div1, div2) {
var d1_height = div1.offsetHeight;
var d1_width = div1.offsetWidth;
var d1_distance_from_top = div1.offsetTop + d1_height;
var d1_distance_from_left = div1.offsetLeft + d1_width;
var d2_height = div2.offsetHeight;
var d2_width = div2.offsetWidth;
var d2_distance_from_top = div2.offsetTop + d2_height;
var d2_distance_from_left = div2.offsetLeft + d2_width;
var not_colliding =
d1_distance_from_top <= div2.offsetTop ||
div1.offsetTop >= d2_distance_from_top ||
d1_distance_from_left <= div2.offsetTop ||
div1.offsetLeft >= d2_distance_from_left;
return !not_colliding;
};
/// key detection (better to use addEventListener, but this will do)
document.body.onkeyup =
document.body.onkeydown = function(e){
if (e.preventDefault) {
e.preventDefault();
}
else {
e.returnValue = false;
}
var kc = e.keyCode || e.which;
keys[kc] = e.type == 'keydown';
};
/// character movement update
var moveCharacter = function(dx, dy){
character.x += (dx||0) * character.speedMultiplier;
character.y += (dy||0) * character.speedMultiplier;
character.element.style.left = character.x + 'px';
character.element.style.top = character.y + 'px';
};
/// character control
var detectCharacterMovement = function(){
if ( keys[keys.LEFT] ) {
moveCharacter(-5, 0);
}
if ( keys[keys.RIGHT] ) {
moveCharacter(5, 0);
}
if ( keys[keys.UP] ) {
moveCharacter(0, -5);
}
if ( keys[keys.DOWN] ) {
moveCharacter(0, 5);
}
};
/// update current position on screen
moveCharacter();
/// game loop
setInterval(function(){
detectCharacterMovement();
}, 1000/24);
body{
display: flex;
justify-content: center;
align-items: center;
}
#character {
position: absolute;
width: 42px;
height: 42px;
background: red;
z-index:99;
}
#container{
width: 400px;
height: 400px;
background: transparent;
border:5px solid rgb(0, 0, 0);
position: relative;
overflow: hidden;
}
<div id="container">
<div id="character"></div>
</div>
PS: You can move the box using keyboard arrows.
Get the container width and height into variable and set a condition on your move
var moveCharacter = function(dx, dy){
let div_width = document.getElementById('container').clientWidth;
let div_height = document.getElementById('container').clientHeight;
if((div_width - character.x) < 50 ){ // 50 = width of character and padding
character.x = div_width - 50;
}
if(character.x < 10){ // Padding
character.x = 11;
}
if((div_height - character.y) < 50 ){
character.y = div_height - 50;
}
if(character.y < 10){
character.y = 11;
}
<!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>
I'm working on a Slider Puzzle and stumbled on a question. I have been trying to make my reset function to stop counting moves on the page when it is pressed but had no luck. My start function starts the counter and ends when the game ends, so how would my counter end counting but still keep the number of moves on display before the user had pressed the reset button?
var gamePiece;
var notify;
var timer;
var spaceY;
var spaceX;
var ticker;
var totalMoves;
function initialize() {
var puzzleArea = document.getElementById("puzzlearea");
gamePiece = puzzleArea.getElementsByTagName("div"); //retrieve element within puzzlearea
for (var i = 0; i < gamePiece.length; i++) //applies features to each puzzle piece
{
gamePiece[i].className = "puzzlepiece"; //setting up the puzzle piece code
gamePiece[i].style.left = (i % 4 * 100) + "px"; //calculates the position for puzzle pieces from the left of the screen
gamePiece[i].style.top = (parseInt(i / 4) * 100) + "px"; //calculates the position for puzzle pieces from the top of the screen
gamePiece[i].onmouseover = function () //applies features when mouse moves over puzzle pieces
{
if (checkMove(parseInt(this.innerHTML))) //checks whenever a move is made
{
this.style.border = "3px solid red"; //changes to red when a puzzle piece is near an empty space
this.style.color = "#006600"; //text color changes to green when a puzzle piece is near an empty space
this.style.textDecoration = "underline"; //underlines the number of the puzzle piece piece
//console.log(totalMoves);
}
}
gamePiece[i].onmouseout = function () //activates whenever mouse moves out of puzzle piece
{
this.style.border = "2px solid black"; //reverts to its original size border
this.style.color = "#000000"; //reverts to original text color
this.style.textDecoration = "none"; //reverts to original text state
}
gamePiece[i].onclick = function () //activates when mouse clicks on a puzzle piece
{
if (checkMove(parseInt(this.innerHTML))) //checks whether or not the puzzle piece can move into an empty space
{
swap(this.innerHTML - 1); //moves into an empty space if true
totalMoves++;
display();
if (finish()) //checks when the all the 15 pieces are in its right space
{
win(); //alerts the player that they have won the game
}
return;
}
}
}
}
spaceX = '300px';
spaceY = '300px';
function checkMove(position) // returns true whenever a piece can be moved into an empty space
{
if (left(spaceX, spaceY) == (position - 1))
{
// totalMoves++;
return true;
}
if (down(spaceX, spaceY) == (position - 1))
{
// totalMoves++;
return true;
}
if (up(spaceX, spaceY) == (position - 1))
{
//totalMoves++;
return true;
}
if (right(spaceX, spaceY) == (position - 1))
{
//totalMoves++;
return true;
}
}
function Notify() //notifies the user
{
notify--; //decrements the value of
if (notify == 0) //if the value reaches the end then
{
var body = document.getElementsByTagName("body"); //retrieves body element in html
body[0].style.backgroundImage = "none"; //reverts to original page background
alert("Winner! ... Press Start and Play Again"); //tells the user that they have won the game
location.href = "15 Slider Puzzle.html"
return;
} else(notify % 2)
{
var body = document.getElementsByTagName("body");
}
timer = setTimeout(Notify, 100); //notifies the user for 1 secs
}
function win() //notifies user that they have won
{
var body = document.getElementsByTagName("body");
notify = 10; //initializes notify variable
timer = setTimeout(Notify, 10);
}
function finish() //checks when the game reaches its end
{
var flag = true;
for (var i = 0; i < gamePiece.length; i++) //for each puzzle piece
{
var top = parseInt(gamePiece[i].style.top);
var left = parseInt(gamePiece[i].style.left);
if (left != (i % 4 * 100) || top != parseInt(i / 4) * 100) //checks if each piece matches its left and top position
{
flag = false;
break; //breaks the loop
}
}
return flag;
}
function left(x, y) //calculates how far to the left a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordX > 0)
{
for (var i = 0; i < gamePiece.length; i++)
{
if (parseInt(gamePiece[i].style.left) + 100 == cordX && parseInt(gamePiece[i].style.top) == cordY)
{
return i;
}
}
} else
{
return -1;
}
}
function right(x, y) //calculates how far to the right a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordX < 300)
{
for (var i = 0; i < gamePiece.length; i++) {
if (parseInt(gamePiece[i].style.left) - 100 == cordX && parseInt(gamePiece[i].style.top) == cordY)
{
return i;
}
}
} else
{
return -1;
}
}
function up(x, y) //calculates how far up a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordY > 0)
{
for (var i = 0; i < gamePiece.length; i++)
{
if (parseInt(gamePiece[i].style.top) + 100 == cordY && parseInt(gamePiece[i].style.left) == cordX)
{
return i;
}
}
} else
{
return -1;
}
}
function down(x, y) //calculates how far down a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordY < 300)
{
for (var i = 0; i < gamePiece.length; i++)
{
if (parseInt(gamePiece[i].style.top) - 100 == cordY && parseInt(gamePiece[i].style.left) == cordX)
{
return i;
}
}
} else
{
return -1;
}
}
function swap(position) //moves the puzzle piece by switching position with an empty space
{
var temp = gamePiece[position].style.top;
gamePiece[position].style.top = spaceY;
spaceY = temp;
temp = gamePiece[position].style.left;
gamePiece[position].style.left = spaceX;
spaceX = temp;
}
function start() //starts the move counter when the button is pressed
{
totalMoves = 0;
ticker = document.getElementById("Moves");
}
function display() //helps update the display when a move is successfully made
{
ticker.innerHTML = totalMoves;
}
function reset()
{
}
body {
background-color: white;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
}
#controls,
#overall,
#puzzlearea {
width: 400px;
}
#controls {
padding-top: 10px;
text-align: center;
}
h1 {
margin: 10px 0px;
text-align: center;
}
/* Used to center the puzzle. */
#overall {
margin-left: auto;
margin-right: auto;
}
/* The area that holds the 15 puzzle pieces. */
#puzzlearea {
font-size: 32px;
height: 400px;
padding: 0px;
position: relative;
}
/* This class should be applied to each of the 15 puzzle pieces. */
.puzzlepiece {
border: 2px solid black;
height: 96px;
line-height: 96px;
position: absolute;
text-align: center;
vertical-align: middle;
width: 96px;
}
/* This class should be applied to a puzzle piece that can be moved. */
.movablepiece:hover {
border-color: red;
color: #006600;
text-decoration: underline;
}
<!DOCTYPE HTML>
<html>
<title> 15 Slider Puzzle</title>
<link rel="stylesheet" type="text/css" href="15 Slider.css" />
<script src="15 Slider.js" type="text/javascript"></script>
<head>
<body onload = "initialize()">
<h1>Slider Puzzle</h1>
<div id="overall">
<div id="puzzlearea">
<!-- the following are the fifteen puzzle pieces -->
<div>1</div> <div>2</div> <div>3</div> <div>4</div>
<div>5</div> <div>6</div> <div>7</div> <div>8</div>
<div>9</div> <div>10</div> <div>11</div> <div>12</div>
<div>13</div> <div>14</div> <div>15</div>
</div>
<div id="controls"></div>
<button onclick = "start();">Start</button>
<button onclick = "reset();">Reset</button>
<br>
Number Of Moves: <span id="Moves">0</span>
</div><!--content-->
<br>
</head>
</html>
I have added a var hasStopped which will only add moves if its false and if reset is clicked it will set to true which means the swap will still run but moves will not counted as well.
Also, when you clicked start() again the totalMoves will start counting the moves again. If you want that too.
Here is working demo for you: https://jsfiddle.net/usmanmunir/cs4d3qfm/16/
var gamePiece;
var notify;
var timer;
var spaceY;
var spaceX;
var ticker;
var totalMoves;
var hasStopped = false;
function initialize() {
var puzzleArea = document.getElementById("puzzlearea");
gamePiece = puzzleArea.getElementsByTagName("div"); //retrieve element within puzzlearea
for (var i = 0; i < gamePiece.length; i++) //applies features to each puzzle piece
{
gamePiece[i].className = "puzzlepiece"; //setting up the puzzle piece code
gamePiece[i].style.left = (i % 4 * 100) + "px"; //calculates the position for puzzle pieces from the left of the screen
gamePiece[i].style.top = (parseInt(i / 4) * 100) + "px"; //calculates the position for puzzle pieces from the top of the screen
gamePiece[i].onmouseover = function() //applies features when mouse moves over puzzle pieces
{
if (checkMove(parseInt(this.innerHTML))) //checks whenever a move is made
{
this.style.border = "3px solid red"; //changes to red when a puzzle piece is near an empty space
this.style.color = "#006600"; //text color changes to green when a puzzle piece is near an empty space
this.style.textDecoration = "underline"; //underlines the number of the puzzle piece piece
//console.log(totalMoves);
}
}
gamePiece[i].onmouseout = function() //activates whenever mouse moves out of puzzle piece
{
this.style.border = "2px solid black"; //reverts to its original size border
this.style.color = "#000000"; //reverts to original text color
this.style.textDecoration = "none"; //reverts to original text state
}
gamePiece[i].onclick = function() //activates when mouse clicks on a puzzle piece
{
if (checkMove(parseInt(this.innerHTML))) //checks whether or not the puzzle piece can move into an empty space
{
swap(this.innerHTML - 1); //moves into an empty space if true
if (!hasStopped) {
totalMoves++;
display();
}
if (finish()) //checks when the all the 15 pieces are in its right space
{
win(); //alerts the player that they have won the game
}
return;
}
}
}
}
spaceX = '300px';
spaceY = '300px';
function checkMove(position) // returns true whenever a piece can be moved into an empty space
{
if (left(spaceX, spaceY) == (position - 1))
{
// totalMoves++;
return true;
}
if (down(spaceX, spaceY) == (position - 1))
{
// totalMoves++;
return true;
}
if (up(spaceX, spaceY) == (position - 1))
{
//totalMoves++;
return true;
}
if (right(spaceX, spaceY) == (position - 1))
{
//totalMoves++;
return true;
}
}
function Notify() //notifies the user
{
notify--; //decrements the value of
if (notify == 0) //if the value reaches the end then
{
var body = document.getElementsByTagName("body"); //retrieves body element in html
body[0].style.backgroundImage = "none"; //reverts to original page background
alert("Winner! ... Press Start and Play Again"); //tells the user that they have won the game
location.href = "15 Slider Puzzle.html"
return;
} else(notify % 2)
{
var body = document.getElementsByTagName("body");
}
timer = setTimeout(Notify, 100); //notifies the user for 1 secs
}
function win() //notifies user that they have won
{
var body = document.getElementsByTagName("body");
notify = 10; //initializes notify variable
timer = setTimeout(Notify, 10);
}
function finish() //checks when the game reaches its end
{
var flag = true;
for (var i = 0; i < gamePiece.length; i++) //for each puzzle piece
{
var top = parseInt(gamePiece[i].style.top);
var left = parseInt(gamePiece[i].style.left);
if (left != (i % 4 * 100) || top != parseInt(i / 4) * 100) //checks if each piece matches its left and top position
{
flag = false;
break; //breaks the loop
}
}
return flag;
}
function left(x, y) //calculates how far to the left a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordX > 0)
{
for (var i = 0; i < gamePiece.length; i++)
{
if (parseInt(gamePiece[i].style.left) + 100 == cordX && parseInt(gamePiece[i].style.top) == cordY)
{
return i;
}
}
} else
{
return -1;
}
}
function right(x, y) //calculates how far to the right a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordX < 300)
{
for (var i = 0; i < gamePiece.length; i++) {
if (parseInt(gamePiece[i].style.left) - 100 == cordX && parseInt(gamePiece[i].style.top) == cordY)
{
return i;
}
}
} else
{
return -1;
}
}
function up(x, y) //calculates how far up a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordY > 0)
{
for (var i = 0; i < gamePiece.length; i++)
{
if (parseInt(gamePiece[i].style.top) + 100 == cordY && parseInt(gamePiece[i].style.left) == cordX)
{
return i;
}
}
} else
{
return -1;
}
}
function down(x, y) //calculates how far down a puzzlepiece should position
{
var cordX = parseInt(x);
var cordY = parseInt(y);
if (cordY < 300)
{
for (var i = 0; i < gamePiece.length; i++)
{
if (parseInt(gamePiece[i].style.top) - 100 == cordY && parseInt(gamePiece[i].style.left) == cordX)
{
return i;
}
}
} else
{
return -1;
}
}
function swap(position) //moves the puzzle piece by switching position with an empty space
{
var temp = gamePiece[position].style.top;
gamePiece[position].style.top = spaceY;
spaceY = temp;
temp = gamePiece[position].style.left;
gamePiece[position].style.left = spaceX;
spaceX = temp;
}
function start() //starts the move counter when the button is pressed
{
totalMoves = 0;
hasStopped = false
ticker = document.getElementById("Moves");
}
function display() //helps update the display when a move is successfully made
{
ticker.innerHTML = totalMoves;
}
function reset() {
hasStopped = true
}
body {
background-color: white;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
}
#controls,
#overall,
#puzzlearea {
width: 400px;
}
#controls {
padding-top: 10px;
text-align: center;
}
h1 {
margin: 10px 0px;
text-align: center;
}
/* Used to center the puzzle. */
#overall {
margin-left: auto;
margin-right: auto;
}
/* The area that holds the 15 puzzle pieces. */
#puzzlearea {
font-size: 32px;
height: 400px;
padding: 0px;
position: relative;
}
/* This class should be applied to each of the 15 puzzle pieces. */
.puzzlepiece {
border: 2px solid black;
height: 96px;
line-height: 96px;
position: absolute;
text-align: center;
vertical-align: middle;
width: 96px;
}
/* This class should be applied to a puzzle piece that can be moved. */
.movablepiece:hover {
border-color: red;
color: #006600;
text-decoration: underline;
}
<!DOCTYPE HTML>
<html>
<title> 15 Slider Puzzle</title>
<link rel="stylesheet" type="text/css" href="15 Slider.css" />
<script src="15 Slider.js" type="text/javascript"></script>
<head>
<body onload="initialize()">
<h1>Slider Puzzle</h1>
<div id="overall">
<div id="puzzlearea">
<!-- the following are the fifteen puzzle pieces -->
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
</div>
<div id="controls"></div>
<button onclick="start();">Start</button>
<button onclick="reset();">Reset</button>
<br> Number Of Moves: <span id="Moves">0</span>
</div>
<!--content-->
<br>
</head>
</html>
Use this as a demo https://jsfiddle.net/ugonnaezema/0gpeo1sj/2/
Initialize a new variable to check if the reset button has been pressed
var isResetPressed = false;
Set isResetPressed to false when initialize is called, then check if the reset button is pressed
function initialize() {
var puzzleArea = document.getElementById("puzzlearea");
gamePiece = puzzleArea.getElementsByTagName("div"); //retrieve element within puzzlearea
isResetPressed = false;
for (var i = 0; i < gamePiece.length; i++) //applies features to each puzzle piece
{
...
gamePiece[i].onclick = function () //activates when mouse clicks on a puzzle piece
{
if (checkMove(parseInt(this.innerHTML))) //checks whether or not the puzzle piece can move into an empty space
{
swap(this.innerHTML - 1); //moves into an empty space if true
if (isResetPressed)
{
totalMoves = totalMoves;
}
else
{
totalMoves++;
}
display();
if (finish()) //checks when the all the 15 pieces are in its right space
{
win(); //alerts the player that they have won the game
}
return;
}
}
...
Set up the reset function as follows
function reset()
{
display();
isResetPressed = true;
}
Ok, in your reset function, pop the current moves into a temp variable and display that, then totalMovves = 0;
You could either manually change the display to use the old value:
ticker.innerHTML = totalMoves;
totalMoves = 0;
But I would do this by altering the Display function to look like below:
function display(var moves = totalMoves) //helps update the display when a move is successfully made
{
ticker.innerHTML = moves;
}
Or you could simply change the order of your commands
function reset(){
display();
totalMoves = 0;
}
I have a setInterval function that wont execute if the increment is less than 101ms. The timing will go any number above 100ms. I want to be able to increment the function by 10ms. offY and strtPos also become undefined when the timing goes below 101ms. How do I make it work the same as it is, but instead, have it incremented by 10ms?
var strtPos;
var offY;
var offX;
var hold = true;
var obj = document.getElementById('obj');
var st = function() {
offY = obj.offsetTop;
}
var init = setInterval(function() {
other()
}, 101); //<-- When I change that value to below 101, it prevents the code from working
var other = function() {
if (hold) {
strt();
hold = false
};
console.log(offY)
console.log(strtPos)
if (strtPos - 100 <= offY) {
obj.style.top = (offY - 11) + "px";
} else {
clearInterval(init);
hold = true;
}
}
var strt = function() {
strtPos = offY
}
setInterval(st, 100)
body {
margin: 0;
}
#obj {
width: 50px;
height: 100px;
background-color: red;
position: fixed;
}
<div id="obj"></div>
The short answer is you need to give offY a value that is not undefined initially, so I've rearranged the variables at the top of your code.
Originally, offY only gets a value after ~100ms (setInterval(st, 100)), and without a value that is not undefined the otherfunction's calculations won't work. So you needed the st function to execute first, hence requiring a value > 100.
var strtPos;
var offX;
var hold = true;
var obj = document.getElementById('obj');
var offY = obj.offsetTop;
var st = function() {
offY = obj.offsetTop;
}
var init = setInterval(function() {
other()
}, 10);
var other = function() {
if (hold) {
strt();
hold = false
};
console.log(offY)
console.log(strtPos)
if (strtPos - 100 <= offY) {
obj.style.top = (offY - 11) + "px";
} else {
clearInterval(init);
hold = true;
}
}
var strt = function() {
strtPos = offY
}
setInterval(st, 100)
body {
margin: 0;
}
#obj {
width: 50px;
height: 100px;
background-color: red;
position: fixed;
}
<div id="obj"></div>
I volunteered to develop this script for a small organisation (as part of my self-training in programming). It randomly selects a seat in a room (spending a few seconds keeping viewers guessing which seat was selected). Since I use a Mac, I tested mainly with Firefox, where it works like a charm. Turns out that the computer in their room runs Internet Explorer 6 on Windows XP (and they had to enable active content in local files).
They called me to inform me of an error and based on the information they gave, the guilty line is either RowNumberDisplay.style = "color: #FF0000"; or var RowNumberDisplay = document.getElementById("RowNumber");. Quick searches on Google and Stack Overflow for getElementById and .style problems in IE6 were fruitless (a common problem is false matches due to name attributes, but the div in question has no name attribute). Thanks in advance for any answers helping identify and address this error.
<!doctype html>
<html>
<head>
<title>The Lucky Person</title>
<style type="text/css">
input#SelectLuckyPerson
{
height: 150px;
font-size: 60px;
}
p#RowDetails, p#SeatDetails, div#RowNumber, div#SeatNumber
{
font-size: 100px;
display: inline;
}
div#RowNumber, div#SeatNumber
{
color: #0000FF;
}
</style>
</head>
<body>
<div id="LuckyPersonIs"><input type="button" id="SelectLuckyPerson" value="And the lucky person is..." onClick="GetResults();"></div>
<p id="RowDetails">Row number: <div id="RowNumber">0</div></p>
<p id="SeatDetails">Seat number: <div id="SeatNumber">0</div></p>
<script>
var MinRow = 2;
var MaxRow = 8;
var SeatsInRow = new Array();
SeatsInRow[1] = 25;
SeatsInRow[2] = 25;
SeatsInRow[3] = 27;
SeatsInRow[4] = 27;
SeatsInRow[5] = 27;
SeatsInRow[6] = 27;
SeatsInRow[7] = 29;
SeatsInRow[8] = 31;
SeatsInRow[9] = 31;
SeatsInRow[10] = 31;
SeatsInRow[11] = 31;
SeatsInRow[12] = 33;
SeatsInRow[13] = 33;
SeatsInRow[14] = 33;
var ShuffleSpeed = 200;
var RowNumberDisplay = document.getElementById("RowNumber");
var SeatNumberDisplay = document.getElementById("SeatNumber");
var ChosenRow, ChosenSeat
function GetResults()
{
var IsRunning = CheckStatus();
if (IsRunning)
{
ChosenRow = ChooseRow();
ChosenSeat = ChooseSeat();
RowNumberDisplay.style = "color: #FF0000";
SeatNumberDisplay.style = "color: #FF0000";
ShowRowResult = window.setInterval("TryRowResult()", ShuffleSpeed);
if (DelaySeats == false)
{
ShowSeatResult = window.setInterval("TrySeatResult()", ShuffleSpeed);
}
}
}
function ChooseRow()
{
return Math.floor(Math.random() * (MaxRow - MinRow)) + MinRow;
}
function ChooseSeat()
{
return Math.ceil(Math.random() * SeatsInRow[ChosenRow]);
}
function TryRowResult()
{
TryRow = ChooseRow();
RowNumberDisplay.innerHTML = TryRow;
if (TryRow == ChosenRow)
{
window.clearInterval(ShowRowResult);
document.getElementById("RowNumber").style = "color: #0000FF";
if (DelaySeats == true)
{
ShowSeatResult = window.setInterval("TrySeatResult()", ShuffleSpeed);
}
}
}
function TrySeatResult()
{
TrySeat = ChooseSeat();
SeatNumberDisplay.innerHTML = TrySeat;
if (TrySeat == ChosenSeat)
{
window.clearInterval(ShowSeatResult);
document.getElementById("SeatNumber").style = "color: #0000FF";
}
}
function CheckStatus()
{
if (RowNumberDisplay.style.color == "rgb(255, 0, 0)" || SeatNumberDisplay.style.color == "rgb(255, 0, 0)")
{
return false;
}
return true;
}
</script>
</body>
</html>
An element's style property is an object, not a string. To assign text to it like you would a CSS attribute, you should assign to element.style.cssText, this will parse out the string for you, and acts as a shortcut to defining multiple styles.
In this case, though, you can just use this:
ChosenRow.style.color = ChosenSeat.style.color = "#f00";