JQuery snake game score board disappearing after game over - html

I've developed a snake game in jQuery and HTML. I'm displaying score on top of the gameboard. It's all going well but when the game is over and need to restart it again, the score is disappearing and it's not being displayed again. When I reload the page, It's showing again.
Since I can't post this question with less text, I'm typing all this random passage. Sorry for this.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
var score;
init();
});
var score=0;
var move;
function init() {
board.initBoard();
createSnake();
food.createFood();
}
function play() {
$('.newGame').hide();
$('.playgame').hide();
moveSnake();
getSnakeDir();
}
function gameover() {
console.log(score);
clearTimeout(move);
$('.newGame').show();
}
function playGame() {
score=0;
$('#gameboard').empty();
$('.newGame').hide();
init();
play();
}
var board = {
DIM: 20,
initBoard: function() {
for (var i = 0; i < board.DIM; i++) {
var row = $('<div class="row-' + i + '"></div>');
for (var j = 0; j < board.DIM; j++) {
var col = ('<div class="col-' + j + '-' + i + '"></div>');
$(row).append(col);
}
$("#gameboard").append(row);
}
}
}
var snake = {
position: ['10-10', '10-11', '10-12'],
direction: 'r',
speed: 200,
};
function createSnake() {
$('.col-10-10').addClass('snake');
$('.col-11-10').addClass('snake');
snake.position = ['10-10', '10-11', '10-12'];
}
function getSnakeDir() {
$(document).keydown(function(event) {
//event.preventDefault();
if (event.which == 38) {
snake.direction = 'u';
} else if (event.which == 39) {
snake.direction = 'r';
} else if (event.which == 40) {
snake.direction = 'd';
} else if (event.which == 37) {
snake.direction = 'l';
}
});
}
function moveSnake() {
var tail = snake.position.pop();
$('.col-' + tail).removeClass('snake');
var coords = snake.position[0].split('-');
var x = parseInt(coords[0]);
var y = parseInt(coords[1]);
if (snake.direction == 'r') {
x = x + 1;
} else if (snake.direction == 'd') {
y = y + 1;
} else if (snake.direction == 'l') {
x = x - 1;
} else if (snake.direction == 'u') {
y = y - 1;
}
var currentcoords = x + '-' + y;
snake.position.unshift(currentcoords);
$('.col-' + currentcoords).addClass('snake');
//when snake eats food
if (currentcoords == food.coords) {
console.log('true');
score= score+10;
$('#scoreb').html("Score :" +score);
$('.col-' + food.coords).removeClass('food');
snake.position.push(tail);
food.createFood();
}
//game over
if (x < 0 || y < 0 || x > board.DIM || y > board.DIM) {
gameover();
$('#scoreb').show();
return;
}
//if snake touch itself
if (hitItself(snake.position) == true) {
gameover();
return;
}
move=setTimeout(moveSnake, 200);
}
var food = {
coords: "",
createFood: function() {
var x = Math.floor(Math.random() * (board.DIM-1)) + 1;
var y = Math.floor(Math.random() * (board.DIM-1)) + 1;
var fruitCoords = x + '-' + y;
$('.col-' + fruitCoords).addClass('food');
food.coords = fruitCoords;
},
}
function hitItself(array) {
var valuesSoFar = Object.create(null);
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (value in valuesSoFar) {
return true;
}
valuesSoFar[value] = true;
}
return false;
}
</script>
<style>
.buttonnewgame {
position: relative;
}
.newGame {
position: absolute;
top: 45%;
left: 20%;
padding: 15px;
font-size: 1em;
font: normal;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 1em;
background-color: #FF69B4;
}
.instructions
{
margin-left: 5px;
float: left;
position : relative;
color: #c603fc;
font: normal;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: 15px;
font-weight: bold;
}
.gameContainer{
width:100%;
}
#scoreb
{
z-index: 999;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
}
#gameboard {
background-color:#eee;
padding:3px;
}
.playgame {
position: absolute;
top: 45%;
left: 20%;
padding: 15px;
font: normal;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 1em;
background-color: #FF69B4;
}
/* styling the board */
div[class^='row'] {
height: 15px;
text-align: center;
}
div[class*='col']{
display: inline-block;
border: 1px solid grey;
width: 15px;
height: 15px;
}
/*display the snake*/
.snake {
background-color: blue;
z-index: 99;
}
.food {
background: red;
z-index: 99;
}
</style>
<table>
<tr>
<td><div class="game">
<div class="buttonnewgame">
<center><input type="button" name="New game" value="Game over! New game" class="newGame" style="display:none;" onclick="playGame()" />
<button class="playgame" onclick="play()">Play Game</button></center>
<div class="gameContainer">
<div id="gameboard">
<div id="scoreb"> Score : </div>
<!-- snake game in here -->
</div>
</div>
</div></div></td>
<td width="150">
<div class="instructions" >
OBJECT: Get as many pieces of "food" as possible using your arrow keys. Each time you do this, you will grow. You want to try to get as big as possible without crashing into a wall or back onto yourself. Good Luck!!
</div></td></tr></table>

You empty all tag inside #gameboard but you need to empty all except scoreb.
So instead of $('#gameboard').empty(); use $('#gameboard').find('*').not('#scoreb').remove();
And note that you must reset the value of score by: $('#scoreb').text("Score :0")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
var score;
init();
});
var score=0;
var move;
function init() {
board.initBoard();
createSnake();
food.createFood();
}
function play() {
$('.newGame').hide();
$('.playgame').hide();
moveSnake();
getSnakeDir();
}
function gameover() {
console.log(score);
clearTimeout(move);
$('.newGame').show();
}
function playGame() {
score=0;
//$('#gameboard').empty();
$('#gameboard').find('*').not('#scoreb').remove();
$('#scoreb').text("Score :0")
$('.newGame').hide();
init();
play();
}
var board = {
DIM: 20,
initBoard: function() {
for (var i = 0; i < board.DIM; i++) {
var row = $('<div class="row-' + i + '"></div>');
for (var j = 0; j < board.DIM; j++) {
var col = ('<div class="col-' + j + '-' + i + '"></div>');
$(row).append(col);
}
$("#gameboard").append(row);
}
}
}
var snake = {
position: ['10-10', '10-11', '10-12'],
direction: 'r',
speed: 200,
};
function createSnake() {
$('.col-10-10').addClass('snake');
$('.col-11-10').addClass('snake');
snake.position = ['10-10', '10-11', '10-12'];
}
function getSnakeDir() {
$(document).keydown(function(event) {
//event.preventDefault();
if (event.which == 38) {
snake.direction = 'u';
} else if (event.which == 39) {
snake.direction = 'r';
} else if (event.which == 40) {
snake.direction = 'd';
} else if (event.which == 37) {
snake.direction = 'l';
}
});
}
function moveSnake() {
var tail = snake.position.pop();
$('.col-' + tail).removeClass('snake');
var coords = snake.position[0].split('-');
var x = parseInt(coords[0]);
var y = parseInt(coords[1]);
if (snake.direction == 'r') {
x = x + 1;
} else if (snake.direction == 'd') {
y = y + 1;
} else if (snake.direction == 'l') {
x = x - 1;
} else if (snake.direction == 'u') {
y = y - 1;
}
var currentcoords = x + '-' + y;
snake.position.unshift(currentcoords);
$('.col-' + currentcoords).addClass('snake');
//when snake eats food
if (currentcoords == food.coords) {
console.log('true');
score= score+10;
$('#scoreb').html("Score :" +score);
$('.col-' + food.coords).removeClass('food');
snake.position.push(tail);
food.createFood();
}
//game over
if (x < 0 || y < 0 || x > board.DIM || y > board.DIM) {
gameover();
$('#scoreb').show();
return;
}
//if snake touch itself
if (hitItself(snake.position) == true) {
gameover();
return;
}
move=setTimeout(moveSnake, 200);
}
var food = {
coords: "",
createFood: function() {
var x = Math.floor(Math.random() * (board.DIM-1)) + 1;
var y = Math.floor(Math.random() * (board.DIM-1)) + 1;
var fruitCoords = x + '-' + y;
$('.col-' + fruitCoords).addClass('food');
food.coords = fruitCoords;
},
}
function hitItself(array) {
var valuesSoFar = Object.create(null);
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (value in valuesSoFar) {
return true;
}
valuesSoFar[value] = true;
}
return false;
}
</script>
<style>
.buttonnewgame {
position: relative;
}
.newGame {
position: absolute;
top: 45%;
left: 20%;
padding: 15px;
font-size: 1em;
font: normal;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 1em;
background-color: #FF69B4;
}
.instructions
{
margin-left: 5px;
float: left;
position : relative;
color: #c603fc;
font: normal;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: 15px;
font-weight: bold;
}
.gameContainer{
width:100%;
}
#scoreb
{
z-index: 999;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
}
#gameboard {
background-color:#eee;
padding:3px;
}
.playgame {
position: absolute;
top: 45%;
left: 20%;
padding: 15px;
font: normal;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 1em;
background-color: #FF69B4;
}
/* styling the board */
div[class^='row'] {
height: 15px;
text-align: center;
}
div[class*='col']{
display: inline-block;
border: 1px solid grey;
width: 15px;
height: 15px;
}
/*display the snake*/
.snake {
background-color: blue;
z-index: 99;
}
.food {
background: red;
z-index: 99;
}
</style>
<table>
<tr>
<td><div class="game">
<div class="buttonnewgame">
<center><input type="button" name="New game" value="Game over! New game" class="newGame" style="display:none;" onclick="playGame()" />
<button class="playgame" onclick="play()">Play Game</button></center>
<div class="gameContainer">
<div id="gameboard">
<div id="scoreb"> Score : </div>
<!-- snake game in here -->
</div>
</div>
</div></div></td>
<td width="150">
<div class="instructions" >
OBJECT: Get as many pieces of "food" as possible using your arrow keys. Each time you do this, you will grow. You want to try to get as big as possible without crashing into a wall or back onto yourself. Good Luck!!
</div></td></tr></table>

Your scoreboard is in the #gameboard. When the line $('#gameboard').empty(); is executed, the scoreboard is removed.
Move the line <div id="scoreb"> Score : </div> to out of #gameboard.
jQuery(document).ready(function($) {
var score;
init();
});
var score = 0;
var move;
function init() {
board.initBoard();
createSnake();
food.createFood();
}
function play() {
$('.newGame').hide();
$('.playgame').hide();
moveSnake();
getSnakeDir();
}
function gameover() {
console.log(score);
clearTimeout(move);
$('.newGame').show();
}
function playGame() {
score = 0;
$('#gameboard').empty();
$('.newGame').hide();
init();
play();
}
var board = {
DIM: 20,
initBoard: function() {
for (var i = 0; i < board.DIM; i++) {
var row = $('<div class="row-' + i + '"></div>');
for (var j = 0; j < board.DIM; j++) {
var col = ('<div class="col-' + j + '-' + i + '"></div>');
$(row).append(col);
}
$("#gameboard").append(row);
}
}
}
var snake = {
position: ['10-10', '10-11', '10-12'],
direction: 'r',
speed: 200,
};
function createSnake() {
$('.col-10-10').addClass('snake');
$('.col-11-10').addClass('snake');
snake.position = ['10-10', '10-11', '10-12'];
}
function getSnakeDir() {
$(document).keydown(function(event) {
//event.preventDefault();
if (event.which == 38) {
snake.direction = 'u';
} else if (event.which == 39) {
snake.direction = 'r';
} else if (event.which == 40) {
snake.direction = 'd';
} else if (event.which == 37) {
snake.direction = 'l';
}
});
}
function moveSnake() {
var tail = snake.position.pop();
$('.col-' + tail).removeClass('snake');
var coords = snake.position[0].split('-');
var x = parseInt(coords[0]);
var y = parseInt(coords[1]);
if (snake.direction == 'r') {
x = x + 1;
} else if (snake.direction == 'd') {
y = y + 1;
} else if (snake.direction == 'l') {
x = x - 1;
} else if (snake.direction == 'u') {
y = y - 1;
}
var currentcoords = x + '-' + y;
snake.position.unshift(currentcoords);
$('.col-' + currentcoords).addClass('snake');
//when snake eats food
if (currentcoords == food.coords) {
console.log('true');
score = score + 10;
$('#scoreb').html("Score :" + score);
$('.col-' + food.coords).removeClass('food');
snake.position.push(tail);
food.createFood();
}
//game over
if (x < 0 || y < 0 || x > board.DIM || y > board.DIM) {
gameover();
$('#scoreb').show();
return;
}
//if snake touch itself
if (hitItself(snake.position) == true) {
gameover();
return;
}
move = setTimeout(moveSnake, 200);
}
var food = {
coords: "",
createFood: function() {
var x = Math.floor(Math.random() * (board.DIM - 1)) + 1;
var y = Math.floor(Math.random() * (board.DIM - 1)) + 1;
var fruitCoords = x + '-' + y;
$('.col-' + fruitCoords).addClass('food');
food.coords = fruitCoords;
},
}
function hitItself(array) {
var valuesSoFar = Object.create(null);
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (value in valuesSoFar) {
return true;
}
valuesSoFar[value] = true;
}
return false;
}
.buttonnewgame {
position: relative;
}
.newGame {
position: absolute;
top: 45%;
left: 20%;
padding: 15px;
font-size: 1em;
font: normal;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 1em;
background-color: #FF69B4;
}
.instructions {
margin-left: 5px;
float: left;
position: relative;
color: #c603fc;
font: normal;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: 15px;
font-weight: bold;
}
.gameContainer {
width: 100%;
}
#scoreb {
z-index: 999;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
}
#gameboard {
background-color: #eee;
padding: 3px;
}
.playgame {
position: absolute;
top: 45%;
left: 20%;
padding: 15px;
font: normal;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-weight: bold;
font-size: 1em;
background-color: #FF69B4;
}
/* styling the board */
div[class^='row'] {
height: 15px;
text-align: center;
}
div[class*='col'] {
display: inline-block;
border: 1px solid grey;
width: 15px;
height: 15px;
}
/*display the snake*/
.snake {
background-color: blue;
z-index: 99;
}
.food {
background: red;
z-index: 99;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<div class="game">
<div class="buttonnewgame">
<center><input type="button" name="New game" value="Game over! New game" class="newGame" style="display:none;" onclick="playGame()" />
<button class="playgame" onclick="play()">Play Game</button></center>
<div class="gameContainer">
<div id="scoreb"> Score : </div>
<div id="gameboard">
<!-- snake game in here -->
</div>
</div>
</div>
</div>
</td>
<td width="150">
<div class="instructions">
OBJECT: Get as many pieces of "food" as possible using your arrow keys. Each time you do this, you will grow. You want to try to get as big as possible without crashing into a wall or back onto yourself. Good Luck!!
</div>
</td>
</tr>
</table>

Related

How to add start button and password protection for quizzes on the web?

I found the following code at codepen.io
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var questions = [{
question: "1. How do you write 'Hello World' in an alert box?",
choices: ["('Hello World')", "msgBox('Hello World');", "alertBox('Hello World');", "alert('Hello World');"],
correctAnswer: 3
}, {
question: "2. How to empty an array in JavaScript?",
choices: ["arrayList[]", "arrayList(0)", "arrayList.length=0", "arrayList.len(0)"],
correctAnswer: 2
}, {
question: "3. What function to add an element at the begining of an array and one at the end?",
choices: ["push,unshift", "unshift,push", "first,push", "unshift,last"],
correctAnswer: 1
}, {
question: "4. What will this output? var a = [1, 2, 3]; console.log(a[6]);",
choices: ["undefined", "0", "prints nothing", "Syntax error"],
correctAnswer: 0
}, {
question: "5. What would following code return? console.log(typeof typeof 1);",
choices: ["string", "number", "Syntax error", "undefined"],
correctAnswer: 0
},{
question: "6. Which software company developed JavaScript?",
choices: ["Mozilla", "Netscape", "Sun Microsystems", "Oracle"],
correctAnswer: 1
},{
question: "7. What would be the result of 3+2+'7'?",
choices: ["327", "12", "14", "57"],
correctAnswer: 3
},{
question: "8. Look at the following selector: $('div'). What does it select?",
choices: ["The first div element", "The last div element", "All div elements", "Current div element"],
correctAnswer: 2
},{
question: "9. How can a value be appended to an array?",
choices: ["arr(length).value;", "arr[arr.length]=value;", "arr[]=add(value);", "None of these"],
correctAnswer: 1
},{
question: "10. What will the code below output to the console? console.log(1 + +'2' + '2');",
choices: ["'32'", "'122'", "'13'", "'14'"],
correctAnswer: 0
}];
var currentQuestion = 0;
var viewingAns = 0;
var correctAnswers = 0;
var quizOver = false;
var iSelectedAnswer = [];
var c=10;
var t;
$(document).ready(function ()
{
// Display the first question
displayCurrentQuestion();
$(this).find(".quizMessage").hide();
$(this).find(".preButton").attr('disabled', 'disabled');
timedCount();
$(this).find(".preButton").on("click", function ()
{
if (!quizOver)
{
if(currentQuestion == 0) { return false; }
if(currentQuestion == 1) {
$(".preButton").attr('disabled', 'disabled');
}
currentQuestion--; // Since we have already displayed the first question on DOM ready
if (currentQuestion < questions.length)
{
displayCurrentQuestion();
}
} else {
if(viewingAns == 3) { return false; }
currentQuestion = 0; viewingAns = 3;
viewResults();
}
});
// On clicking next, display the next question
$(this).find(".nextButton").on("click", function ()
{
if (!quizOver)
{
var val = $("input[type='radio']:checked").val();
if (val == undefined)
{
$(document).find(".quizMessage").text("Please select an answer");
$(document).find(".quizMessage").show();
}
else
{
// TODO: Remove any message -> not sure if this is efficient to call this each time....
$(document).find(".quizMessage").hide();
if (val == questions[currentQuestion].correctAnswer)
{
correctAnswers++;
}
iSelectedAnswer[currentQuestion] = val;
currentQuestion++; // Since we have already displayed the first question on DOM ready
if(currentQuestion >= 1) {
$('.preButton').prop("disabled", false);
}
if (currentQuestion < questions.length)
{
displayCurrentQuestion();
}
else
{
displayScore();
$('#iTimeShow').html('Time is Over!!!!');
$('#timer').html("You scored: " + correctAnswers + " out of: " + questions.length);
c=185;
$(document).find(".preButton").text("View Answer");
$(document).find(".nextButton").text("Play Again?");
quizOver = true;
return false;
}
}
}
else
{ // quiz is over and clicked the next button (which now displays 'Play Again?'
quizOver = false; $('#iTimeShow').html('Time Remaining:'); iSelectedAnswer = [];
$(document).find(".nextButton").text("Next Question");
$(document).find(".preButton").text("Previous Question");
$(".preButton").attr('disabled', 'disabled');
resetQuiz();
viewingAns = 1;
displayCurrentQuestion();
hideScore();
}
});
});
function timedCount()
{
if(c == 15)
{
return false;
}
var hours = parseInt( c / 3600 ) % 24;
var minutes = parseInt( c / 60 ) % 60;
var seconds = c % 60;
var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
$('#timer').html(result);
if(c == 0 )
{
displayScore();
$('#iTimeShow').html('Time is Over!!!');
$('#timer').html("You scored: " + correctAnswers + " out of: " + questions.length);
c=185;
$(document).find(".preButton").text("View Answer");
$(document).find(".nextButton").text("Play Again?");
quizOver = true;
return false;
}
if(c == 0 )
{
if (!quizOver)
{
var val = $("input[type='radio']:checked").val();
if (val == questions[currentQuestion].correctAnswer)
{
correctAnswers++;
}
currentQuestion++; // Since we have already displayed the first question on DOM ready
if (currentQuestion < questions.length)
{
displayCurrentQuestion();
c=15;
}
else
{
displayScore();
$('#timer').html('');
c=16;
$(document).find(".nextButton").text("Play Again?");
quizOver = true;
return false;
}
}
else
{ // quiz is over and clicked the next button (which now displays 'Play Again?'
quizOver = false;
$(document).find(".nextButton").text("Next Question");
resetQuiz();
displayCurrentQuestion();
hideScore();
}
}
c = c - 1;
t = setTimeout(function()
{
timedCount()
},1000);
}
// This displays the current question AND the choices
function displayCurrentQuestion()
{
if(c == 15) { c = 10; timedCount(); }
//console.log("In display current Question");
var question = questions[currentQuestion].question;
var questionClass = $(document).find(".quizContainer > .question");
var choiceList = $(document).find(".quizContainer > .choiceList");
var numChoices = questions[currentQuestion].choices.length;
// Set the questionClass text to the current question
$(questionClass).text(question);
// Remove all current <li> elements (if any)
$(choiceList).find("li").remove();
var choice;
for (i = 0; i < numChoices; i++)
{
choice = questions[currentQuestion].choices[i];
if(iSelectedAnswer[currentQuestion] == i) {
$('<li><input type="radio" class="radio-inline" checked="checked" value=' + i + ' name="dynradio" />' + ' ' + choice + '</li>').appendTo(choiceList);
} else {
$('<li><input type="radio" class="radio-inline" value=' + i + ' name="dynradio" />' + ' ' + choice + '</li>').appendTo(choiceList);
}
}
}
function resetQuiz()
{
currentQuestion = 0;
correctAnswers = 0;
hideScore();
}
function displayScore()
{
$(document).find(".quizContainer > .result").text("You scored: " + correctAnswers + " out of: " + questions.length);
$(document).find(".quizContainer > .result").show();
}
function hideScore()
{
$(document).find(".result").hide();
}
// This displays the current question AND the choices
function viewResults()
{
if(currentQuestion == 10) { currentQuestion = 0;return false; }
if(viewingAns == 1) { return false; }
hideScore();
var question = questions[currentQuestion].question;
var questionClass = $(document).find(".quizContainer > .question");
var choiceList = $(document).find(".quizContainer > .choiceList");
var numChoices = questions[currentQuestion].choices.length;
// Set the questionClass text to the current question
$(questionClass).text(question);
// Remove all current <li> elements (if any)
$(choiceList).find("li").remove();
var choice;
for (i = 0; i < numChoices; i++)
{
choice = questions[currentQuestion].choices[i];
if(iSelectedAnswer[currentQuestion] == i) {
if(questions[currentQuestion].correctAnswer == i) {
$('<li style="border:2px solid green;margin-top:10px;"><input type="radio" class="radio-inline" checked="checked" value=' + i + ' name="dynradio" />' + ' ' + choice + '</li>').appendTo(choiceList);
} else {
$('<li style="border:2px solid red;margin-top:10px;"><input type="radio" class="radio-inline" checked="checked" value=' + i + ' name="dynradio" />' + ' ' + choice + '</li>').appendTo(choiceList);
}
} else {
if(questions[currentQuestion].correctAnswer == i) {
$('<li style="border:2px solid green;margin-top:10px;"><input type="radio" class="radio-inline" value=' + i + ' name="dynradio" />' + ' ' + choice + '</li>').appendTo(choiceList);
} else {
$('<li><input type="radio" class="radio-inline" value=' + i + ' name="dynradio" />' + ' ' + choice + '</li>').appendTo(choiceList);
}
}
}
currentQuestion++;
setTimeout(function()
{
viewResults();
},3000);
}
</script>
<div class="quizContainer container-fluid well well-lg">
<div id="quiz1" class="text-center">
<h3>Test</h3>
<center><img class="img-responsive" height="180" width="100" src="http://res.cloudinary.com/dwjej2tbp/image/upload/v1523002021/KGCAS_SK_eyehy9.jpg"></center>
<h4 style="color:#FF0000;position:absolute;left:70%;top:30%;" align="center" ><span id="iTimeShow">Time Remaining: </span><br/><span id='timer' style="font-size:25px;"></span></h4>
<h2>Exercise 1</h2>
</div>
<div class="question"></div>
<ul class="choiceList"></ul>
<div class="quizMessage"></div>
<div class="result"></div>
<button class="preButton">Previous</button>
<button class="nextButton">Next</button>
</div>
with CSS as follows
h1 {
font-family:'Gabriola', serif;
text-align: center;
}
ul {
list-style: none;
}
li {
font-family:'Cambria', serif;
font-size: 1.5em;
}
input[type=radio] {
border: 0px;
width: 20px;
height: 2em;
}
p {
font-family:'Gabriola', serif;
}
/* Quiz Classes */
.quizContainer {
background-color: white;
border-radius: 6px;
width: 75%;
margin: auto;
padding-top: 5px;
/*-moz-box-shadow: 10px 10px 5px #888;
-webkit-box-shadow: 10px 10px 5px #888;
box-shadow: 10px 10px 5px #888;*/
position: relative;
}
.quizcontainer #quiz1
{
text-shadow:1px 1px 2px orange;
font-family:"Georgia", Arial, sans-serif;
}
.nextButton {
box-shadow: 3px 3px 5px #888;
border-radius: 6px;
/* width: 150px;*/
height: 40px;
text-align: center;
background-color: lightgrey;
/*clear: both;*/
color: red;
font-family:'Gabriola', serif;
position: relative;
margin: auto;
font-size:25px;
font-weight:bold;
padding-top: 5px;
float:right;
right:30%;
}
.preButton {
box-shadow: 3px 3px 5px #888;
border-radius: 6px;
/*width: 150px;*/
height: 40px;
text-align: center;
background-color: lightgrey;
/*clear: both;*/
color: red;
font-family:'Gabriola', serif;
position: relative;
margin: auto;
font-size:25px;
font-weight:bold;
padding-top: 5px;
float:left;
left:30%;
}
.question {
font-family:'Century', serif;
font-size: 1.5em;
font-weight:bold;
width: 100%;
height: auto;
margin: auto;
border-radius: 6px;
background-color: #f3dc45;
text-align: center;
}
.quizMessage {
background-color: peachpuff;
border-radius: 6px;
width: 20%;
margin: auto;
text-align: center;
padding: 5px;
font-size:20px;
font-weight:bold;
font-family:'Gabriola', serif;
color: red;
position:absolute;
top:80%;
left:40%;
}
.choiceList {
font-family: 'Arial', serif;
color: #ed12cd;
font-size:15px;
font-weight:bold;
}
.result {
width: 40%;
height: auto;
border-radius: 6px;
background-color: linen;
margin: auto;
color:green;
text-align: center;
font-size:25px;
font-family:'Verdana', serif;
font-weight:bold;
position:absolute;
top:80%;
left:30%;
}
/* End of Quiz Classes */
I want to give some pointers before doing the quiz. And this quiz is only done by certain people. Therefore, I think it is better not to immediately display the first question (because when the link is opened, this quiz will immediately display question number one and running time).
I think changes should be made to the code below. I've tried removing displayCurrentQuestion (); , but the quis didn't work. I've also tried to replace it with a button but it doesn't work.
(document).ready(function ()
{
// Display the first question
displayCurrentQuestion();
$(this).find(".quizMessage").hide();
$(this).find(".preButton").attr('disabled', 'disabled');
timedCount();
$(this).find(".preButton").on("click", function ()
{
if (!quizOver)
{
if(currentQuestion == 0) { return false; }
if(currentQuestion == 1) {
$(".preButton").attr('disabled', 'disabled');
}
currentQuestion--; // Since we have already displayed the first question on DOM ready
if (currentQuestion < questions.length)
{
displayCurrentQuestion();
}
} else {
if(viewingAns == 3) { return false; }
currentQuestion = 0; viewingAns = 3;
viewResults();
}
});
// On clicking next, display the next question
$(this).find(".nextButton").on("click", function ()
{
if (!quizOver)
{
var val = $("input[type='radio']:checked").val();
if (val == undefined)
{
$(document).find(".quizMessage").text("Please select an answer");
$(document).find(".quizMessage").show();
}
else
{
// TODO: Remove any message -> not sure if this is efficient to call this each time....
$(document).find(".quizMessage").hide();
if (val == questions[currentQuestion].correctAnswer)
{
correctAnswers++;
}
iSelectedAnswer[currentQuestion] = val;
currentQuestion++; // Since we have already displayed the first question on DOM ready
if(currentQuestion >= 1) {
$('.preButton').prop("disabled", false);
}
if (currentQuestion < questions.length)
{
displayCurrentQuestion();
}
else
{
displayScore();
$('#iTimeShow').html('Time is Over!!!!');
$('#timer').html("You scored: " + correctAnswers + " out of: " + questions.length);
c=115;
$(document).find(".preButton").text("View Answer");
$(document).find(".nextButton").text("Play Again?");
quizOver = true;
return false;
}
}
}
else
{ // quiz is over and clicked the next button (which now displays 'Play Again?'
quizOver = false; $('#iTimeShow').html('Time Remaining:'); iSelectedAnswer = [];
$(document).find(".nextButton").text("Next");
$(document).find(".preButton").text("Previous");
$(".preButton").attr('disabled', 'disabled');
resetQuiz();
viewingAns = 1;
displayCurrentQuestion();
hideScore();
}
});
});
How do you make the initial quiz display display the password form and start button? of course if the password is wrong then the question will not appear.

table with height 100% doesn't fit parent size

I've a table inside a div inside the main.
all of this have width = 100% but when i make the window smaller just the div ant the main gets smaller but the table dosent resize. all other elements below the table change position and size and starts lay over it. the table has 25 records and if the window is full-size everything matches perfect.
The div im talkin about has the id home
The html:
<DOCTYPE! html>
<html>
<head>
<meta charset="UTF-8">
<title>Admin Panel | Please Login</title>
<link href='../css/admin.css' type='text/css' rel='stylesheet'>
<meta http-equiv="refresh" content="60">
</head>
<body>
<main>
<div id='container'>
<img src="../img/ipw_quer_rgb.jpg" alt="IPW Logo" id="logo" width="15%">
<header>
<ul id='menu'>
<div id="links">
<li>Home</li>
<li>Schüler verwalten</li>
<li>History</li>
</div>
</ul>
</header>
<div id="home">
<h2 id="date"></h2>
<table id="table">
</table>
</div>
<div id="dropdown" class="dropdown">
<select id="select">
<option value="Nothing">Nichts ausgewählt</option>
<option value="Extern">Extern</option>
<option value="Termin">Termin</option>
<option value="Schule">Schule</option>
</select>
</div>
<div id="legend" class="legend">
<svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" style="fill:#D3D3D3;" />
</svg>
<a>Extern</a>
<br>
<svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" style="fill:#FFAEB9;" />
</svg>
<a>Termin</a>
<br>
<svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" style="fill:#FFFF00;" />
</svg>
<a>Schule</a>
<br>
<svg width="10" height="10">
<rect x="0" y="0" width="10" height="10" style="fill:#00FF00;" />
</svg>
<a>Visiert</a>
<br>
<button id="edit">Editieren</button>
</div>
</div>
</main>
the css:
*{
margin: 0;
padding: 0;
font-family: monospace;
box-sizing: border-box;
}
main{
height: 100%;
width: 100%;
}
label{
font: 13px Helvetica, Arial, sans-serif;
}
html, body{
background-color: #006975;
overflow-y:auto;
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
h3{
margin-right:50%;
}
table{
width:100%;
height:calc(100% -50px);
}
ul {
width:100%;
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #006975;
}
li {
width:25%;
float: left;
}
h1{
text-align:center;
}
li a {
display: block;
color: white;
font-size: 120%;
text-align: center;
padding: 14px 16px;
border-left: 2px solid #fff;
border-right: 2px solid #fff;
text-decoration: none;
}
/* Change the link color to #111 (black) on hover */
li a:hover {
color: #006975;
background-color: #fff;
}
button:hover{
color:#fff;
background-color:#84afb8;
}
#container{
position:absolute;
margin: 4% 4% 4% 4%;
padding: 2%;
width: 90%;
height: 90%;
background-color: #fff;
}
#home{
height:60%;
}
#dropdown{
width:100%;
height:2%;
visibility:hidden;
}
.cell {
height: 4%;
width:10%;
text-align: center;
background-color: #D3D3D3;
}
.cell.on {
height: 4%;
width: 10%;
background-color: #00FF00;
}
.cell.les {
height: 4%;
width: 10%;
background-color: #FFFF00;
}
.cell.term {
height: 4%;
width: 10%;
background-color: #FFAEB9;
}
.cell.ext{
height: 4%;
width: 10%;
background-color: #D3D3D3;
}
.cell.spacer {
height: 4%;
width: 10%;
background-color:white;
}
.name {
border: 1px solid black;
}
if you also need the javascript please ask
EDIT:
javascript:
getDataUser('logGLAUSB');
var names = ["Zebra","Benj", "Nico", "Timon","Miro", "Leo"];
var longpresstimer = null;
getData();
window.addEventListener('click', function(){
});
window.addEventListener('load', function () {
var clickcount = 0;
var singleClickTimer;
document.getElementById('table').addEventListener('click', function (event) {
clickcount++;
if(clickcount==1){
if(event.target.tagName != "INPUT" && event.target.classList != 'cell spacer'){
singleClickTimer = setTimeout(function() {
clickcount = 0;
var cell = event.target;
var selected = getSelected();
if(selected == 3){
cell.classList.remove("ext");
cell.classList.remove("term");
cell.classList.remove("les");
cell.classList.add("on");
}else{
cell.classList.remove("ext");
cell.classList.remove("term");
cell.classList.remove("les");
cell.classList.remove("on");
switch(selected){
case 0: cell.classList.add("ext"); break;
case 1: cell.classList.add("les"); break;
case 2: cell.classList.add("term"); break;
}
}
var x = "get";
x += getString(event.target.parentNode.cells[0].childNodes[0].innerHTML);
getData(x);
}, 300);
}
}else if (clickcount == 2){
if(event.target.classList != "name"){
clearTimeout(singleClickTimer);
clickcount = 0;
toInput(event.target);
}
}
});
});
document.getElementById("edit").addEventListener('click', function(){
var legend = document.getElementById("legend");
var dropdown = document.getElementById('dropdown');
var select = document.getElementById('select');
legend.style.visibility = 'hidden';
dropdown.style.visibility = 'visible';
var button = document.createElement('button');
button.innerHTML= "Fertig";
dropdown.appendChild(button);
button.onclick = function(){
legend.style.visibility = 'visible';
dropdown.style.visibility = 'hidden';
dropdown.removeChild(button);
select.value = "Nothing";
}
});
function reset(){
var rows = Array.from(document.getElementsByClassName('row'));
var table = document.getElementById('table');
rows.forEach(function (row){
var cells = Array.from(document.getElementsByClassName('cell'));
for(var i = 0;i< cells.length;i++){
var cell = cells[i]
cell.classList.remove('on');
cell.classList.remove('les');
cell.classList.remove('term');
cell.classList.remove('ext');
}
});
var x = "rep";
x += getResetString();
getData(x);
}
function clearSelection() {
if(document.selection && document.selection.empty) {
document.selection.empty();
} else if(window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
}
}
function getData(str) {
var requestURL = "http://adopraesenz.ipwin.ch/data/students.php?q=" +str;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
loadJson(request);
}
};
request.open("GET", requestURL, true);
request.send();
}
function getDataHistory(str) {
var requestURL = "http://adopraesenz.ipwin.ch/data/history.php?q=" +str;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
if(request.responseText != ""){
loadDate(request);
}
}
};
request.open("GET", requestURL, true);
request.send();
}
function getDataUser(str){
var requestURL = "http://adopraesenz.ipwin.ch/data/login.php?q=" +str;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
if(request.responseText != ""){
loadDate(request);
} }
};
request.open("GET", requestURL, true);
request.send();
}
function getSelected(cell) {
var value = document.getElementById("select").value;
switch(value){
case "Extern": return 0; break;
case "Schule": return 1; break;
case "Termin": return 2; break;
default: return 3;
}
}
function loadDate(request){
var newDate = new Date();
newDate.setDate(newDate.getDate() -1);
newDate.setHours(0,0,0,0);
var days = request.responseText.split(".");
var oldDate = new Date(days[1]+"."+days[0]+"."+days[2]);
if(newDate > oldDate){
var date = new Date();
date.setDate(date.getDate() - 1);
var dd = date.getDate();
var mm = date.getMonth() + 1;
var yyyy = date.getFullYear();
if(dd < 10) {
dd = '0' +dd;
}
if(mm < 10) {
mm = '0' +mm;
}
var yesterday = dd+"."+mm+"."+yyyy;
getDataHistory('add' + yesterday);
reset();
}
newDate = new Date().toLocaleDateString('de-CH', {
weekday: 'long',
day: '2-digit',
month: '2-digit',
year: 'numeric'
});
document.getElementById('date').innerHTML = newDate;
}
getDataHistory('new');
function loadJson(request){
createTable(request.responseText);
}
function createHeader(array){
var header = document.createElement("thead");
var hRow = document.createElement('tr');
hRow.classList.add('header');
for(var i = 0; i < array.length; i++){
var div = document.createElement('div');
var th = document.createElement('th');
div.innerHTML = array[i];
th.appendChild(div);
hRow.appendChild(th);
}
header.appendChild(hRow);
return header;
}
function createTable(json){
var obj = JSON.parse(json);
var oldBody = document.getElementsByTagName('tbody')[0];
console.log(oldBody);
var oldHeader = document.getElementsByTagName('thead')[0];
var body = document.createElement('tbody');
var header = createHeader(["Name","09:00 – 09:45","10:15 – 11:00","11:00 – 11:45"," ","14:00 – 14:45","15:00 - 15:45","16:00 – 16:45"]);
for (var j = 0; j < obj.length; j++) {
var row = addRow(obj[j],body);
row.classList.add('row');
}
console.log(body);
replaceTable(body, oldBody, header ,oldHeader);
if(obj.length > 25){
var view = document.getElementById('home');
view.setAttribute("style", "overflow-y:scroll");
}
}
function toInput(cell){
var input = document.createElement('input');
setTimeout(function() { input.focus(); }, 200);
cell.appendChild(input);
window.addEventListener('keypress', function(e){
if(e.keyCode == '13'){
var text = input.value;
if(input.parentNode != null){
input.parentNode.removeChild(input);
}
cell.innerHTML = text;
getData("get"+getString(cell.parentNode.cells[0].childNodes[0].innerHTML));
}
}, false);
}
function replaceTable(body, oldBody, header, oldHeader){
if(typeof oldHeader == 'undefined'){
table.appendChild(header);
}else if(oldHeader.parentNode == table){
table.replaceChild(header, oldHeader);
}else{
table.appendChild(header);
}
if(typeof oldBody == 'undefined'){
table.appendChild(body);
}else if(oldBody.parentNode == table){
table.removeChild(oldBody);
table.appendChild(body);
//table.replaceChild(body, oldBody);
}else{
table.appendChild(body);
}
}
function addRow(val,body) {
var rest = val.split(";");
var tr = document.createElement('tr');
for( var i = 0; i < 8; i++){
if(i==0){
var name = rest[0];
addCell(tr, null,name);
}else{
var value = rest[i];
addCell(tr, value, name);
}
}
body.appendChild(tr);
return tr;
}
function addCell(tr, val, name) {
var name;
var cell = document.createElement('td');
var value = "get";
if(val == null){
var input = document.createElement('label');
cell.classList.add("name")
input.innerHTML = name;
input.readOnly = true;
cell.appendChild(input);
}else{
cell = document.createElement('td');
cell.classList.add('cell');
var content = val.split(":");
switch(content[0]){
case '0': cell.classList.add('ext'); break;
case '1': cell.classList.add('les'); break;
case '2': cell.classList.add('term'); break;
case '3': cell.classList.add('on'); break;
case '4': cell.classList.add('spacer'); break;
}
if(val.length > 1){
cell.innerHTML = content[1];
}
}
tr.appendChild(cell);
}
window.onclick = function(event) {
if (!event.target.matches('.dropA')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
function getString(name){
var x = "";
var names = document.getElementsByClassName('name');
var values = document.getElementsByClassName('cell');
for(var i = 0;i<names.length;i++){
if(names[i].childNodes[0].innerHTML == name){
x+= names[i].childNodes[0].innerHTML + ";";
for(var j = (7 * i); j < (7 * i) + 7 ; j++){
switch(""+values[j].classList){
case 'cell': x += "0"; break;
case 'cell ext': x += "0"; break;
case 'cell les': x += "1"; break;
case 'cell term': x += "2"; break;
case 'cell on': x += "3"; break;
case 'cell spacer': x += "4"; break;
}
if(values[j].innerHTML != "" && values[j].innerHTML != null){
x+= ":" + values[j].innerHTML
}
x += ";";
}
}
}
return x;
}
function getResetString(){
var names = document.getElementsByClassName('name');
var x = "";
for(var i = 0; i < names.length; i++){
x += names[i].value +";";
for (var j = 0; j < 7 ; j++){
if(j == 3){
x += "4";
}else{
x += "0";
}
x += ";";
}
if(i < names.length-1){
x+="|";
}
}
return x;
}
it seems a tiny problem. on your css, you have to add an space on the calc statement:
height:calc(100% - 50px);
I was able to make it work in here
https://codesandbox.io/s/vibrant-http-ty85k
You can add display: table; to #container
and add:
#legend {
display: table-row;
}
This should work, but I think you should refactor (simplify) the whole page and styles.

I want my Game to be at the bottom not at the top?

I have a school project where i want to programm a Gaming site but the game i copied from another website is always at the top can you help me to bring it down ?
I want the Game to be in the Center of the Website under the Hotbar :)
HTML CODE:
<!DOCTYPE html>
<html>
<head>
<title>Games</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="css/nav.css">
<style>
canvas {
border:1px solid #d3d3d3;
background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<div class="nav">
<ul>
<li>Aventure Games</li>
<li>1vs1 Games</li>
<li id="logo"><img src="src/logogif.gif" style="width:300px;"></li>
<li>Other Categories</li>
<li>About us</li>
</ul>
</div>
<article>
<h1>Games</h1>
<p>content bla bla</p>
</article>
<p class="flappybird">
<script>
var myGamePiece;
var myObstacles = [];
var myScore;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
myGamePiece.gravity = 0.05;
myScore = new component("30px", "Consolas", "black", 280, 40, "text");
myGameArea.start();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.frameNo = 0;
this.interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
this.score = 0;
this.width = width;
this.height = height;
this.speedX = 0;
this.speedY = 0;
this.x = x;
this.y = y;
this.gravity = 0;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
if (this.type == "text") {
ctx.font = this.width + " " + this.height;
ctx.fillStyle = color;
ctx.fillText(this.text, this.x, this.y);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
this.gravitySpeed = 0;
}
}
this.crashWith = function(otherobj) {
var myleft = this.x;
var myright = this.x + (this.width);
var mytop = this.y;
var mybottom = this.y + (this.height);
var otherleft = otherobj.x;
var otherright = otherobj.x + (otherobj.width);
var othertop = otherobj.y;
var otherbottom = otherobj.y + (otherobj.height);
var crash = true;
if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
crash = false;
}
return crash;
}
}
function updateGameArea() {
var x, height, gap, minHeight, maxHeight, minGap, maxGap;
for (i = 0; i < myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
return;
}
}
myGameArea.clear();
myGameArea.frameNo += 1;
if (myGameArea.frameNo == 1 || everyinterval(150)) {
x = myGameArea.canvas.width;
minHeight = 20;
maxHeight = 200;
height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
minGap = 50;
maxGap = 200;
gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
myObstacles.push(new component(10, height, "green", x, 0));
myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
}
for (i = 0; i < myObstacles.length; i += 1) {
myObstacles[i].x += -1;
myObstacles[i].update();
}
myScore.text="SCORE: " + myGameArea.frameNo;
myScore.update();
myGamePiece.newPos();
myGamePiece.update();
}
function everyinterval(n) {
if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
return false;
}
function accelerate(n) {
myGamePiece.gravity = n;
}
</script>
<br>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Use the ACCELERATE button to stay in the air</p>
<p>How long can you stay alive?</p>
</body>
</html>
CSS CODE:
*{
margin: 0px;
background-color:darkred;
}
.nav{
height: 100px;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
text-align: center;
/*padding-left: 30%;
padding-right: 30%;*/
/*overflow: hidden;*/
background-color: gray;
height:70px;
}
li {
/*float: left;*/
display: inline-block;
vertical-align: top;
margin: 0 -2px;
}
li a {
display: block;
font-family: Verdana, Helvetica, sans-serif;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
background-color: darkred;
}
#logo {
/*display: block;*/
font-family: Verdana, Helvetica, sans-serif;
background-color: black;
text-align: center;
padding: 10px;
text-decoration: none;
}
#logo img{
display: block;
}
li a:hover {
background-color: black;
color: white;
}
}
p{font-family:Tahoma;}
article {
padding-left: 12px;
}
You've got to define the correct place you want to insert your new element, in your case the canvas.
In your code snippet below, you tell the canvas to be placed before the first child node of the document body.
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
You need to specify an element to place it before, below it's looking for the first element with the class name flappybird.
document.body.insertBefore(this.canvas, document.getElementsByClassName("flappybird")[0]);

Fix div position with respect to another div when zoom

I have the following HTML. The problem is that I can not make the div with id="ladder" have the same position with respect to its parent div with id="grid" when I zoom in or out. here is the code snakes and Ladders
var gameBoard = {
createBoard: function(dimension, mount) {
var mount = document.querySelector(mount);
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
mount.appendChild(table);
output = gameBoard.enumerateBoard(table);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
cells,
cellsLength,
cellNumber,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
cellsLength = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < cellsLength; i++) {
if (odd == true) {
cellNumber = --size + rowCounter - i;
} else {
cellNumber = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].id = cellNumber;
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = cellNumber;
rowCounter++;
}
}
var lastRow = rows[0].getElementsByTagName('td');
lastRow[0].id = '100';
var firstRow = rows[9].getElementsByTagName('td');
firstRow[0].id = '1';
return gameBoard;
}
};
gameBoard.createBoard(10, "#grid");
function intialPosition() {
$("#1").append($("#player1"));
$("#1").append($("#player2"));
var currentPosition = parseInt($("#1").attr('id'));
return currentPosition;
}
var start = intialPosition();
var face1 = new Image();
face1.src = "http://s19.postimg.org/fa5etrfy7/image.gif";
var face2 = new Image();
face2.src = "http://s19.postimg.org/qb0jys873/image.gif";
var face3 = new Image();
face3.src = "http://s19.postimg.org/fpgoms1vj/image.gif";
var face4 = new Image();
face4.src = "http://s19.postimg.org/xgsb18ha7/image.gif";
var face5 = new Image();
face5.src = "http://s19.postimg.org/lsy96os5b/image.gif";
var face6 = new Image();
face6.src = "http://s19.postimg.org/4gxwl8ynz/image.gif";
function rollDice() {
var status = document.getElementById("status");
var random = Math.floor(Math.random() * 6) + 1;
document.images["mydice"].src = eval("face" + random + ".src")
status.innerHTML = "You rolled " + random;
//if (random == 6) {
// status.innerHTML += "! You get a free turn!!";
//}
return random;
}
var currentPosition = start;
var random1;
function move() {
var m = 1;
random1 = rollDice();
destination = currentPosition + random1;
$('#' + destination).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
$('#' + destination).append($('#player' + m));
if (destination == 36) {
destination = 55;
$('#' + destination).append($('#' + "player" + m));
}
if (destination == 96) {
destination = 57;
$('#' + destination).append($('#' + "player" + m));
}
if (destination >= 100) {
destination = 100;
$('#' + destination).append($('#' + "player" + m));
alert("You Won!!!!!!!");
}
currentPosition = parseInt($('#' + destination).attr('id'));
return currentPosition;
}
/*body {
background-image: url('snakesandladder2.png');
background-repeat: no-repeat;
background-size: 100%;
background-color: #4f96cb;
}*/
#game {
width: 80%;
margin-left: auto;
margin-right: auto;
display: table;
}
#gameBoardSection {
border: 3px inset #0FF;
border-radius: 10px;
width: 65%;
display: table-cell;
position: relative;
/*margin: 5px;*/
/*margin: auto;*/
}
/*#grid{
position:relative;
}*/
table {
width: 100%;
position: relative;
}
td {
border-radius: 10px;
width: 60px;
height: 60px;
line-height: normal;
vertical-align: bottom;
text-align: left;
border: 0px solid #FFFFFF;
position: relative;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
/*color: #FF0000 ;*/
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
#100 {
background-image: url('rotstar2_e0.gif');
background-repeat: no-repeat;
background-size: 100%;
}
#ladder {
position: absolute;
top: 300px;
left: 470px;
-webkit-transform: rotate(30deg);
z-index: 1;
opacity: 0.7;
}
#bigSnake {
position: absolute;
top: 20px;
left: 200px;
opacity: 0.7;
z-index: 1;
}
#playerAndDiceSection {
background-color: lightpink;
border: 1px;
border-style: solid;
display: table-cell;
/*margin: 2px;*/
border-radius: 10px;
border: 3px inset #0FF;
width: 35%;
margin: 2%;
}
<body>
<div id="game">
<div id="gameBoardSection">
<div id="grid"></div>
<div id="ladder">
<img src="http://s19.postimg.org/otai9he2n/oie_e_RDOY2iqd5o_Q.gif" />
</div>
<div id="bigSnake">
<img src="http://s19.postimg.org/hrcknaagz/oie_485727s_RN4_KKBG.png" />
</div>
<div id="player1" style="position:absolute; top:10px; left:10px;">
<!--style="position: absolute; top: 597px; z-index: 1;"-->
<img src="http://s19.postimg.org/t108l496n/human_Piece.png" />
</div>
<div id="player2" style="position:absolute; top:15px; left:5px;">
<img src="http://s19.postimg.org/l6zmzq1dr/computer_Piece.png" />
</div>
</div>
<div id="playerAndDiceSection">
<div id="playerSection">
<div id="player1">
<img src="http://s19.postimg.org/t108l496n/human_Piece.png" />Player1
<!--<p>Player1</p>-->
</div>
<div id="player2">
<img src="http://s19.postimg.org/l6zmzq1dr/computer_Piece.png" />Player2
</div>
</div>
<div id="diceSection">
<img src="http://s19.postimg.org/fa5etrfy7/image.gif" name="mydice" onclick="move()" style="background-color: white;">
<h2 id="status"></h2>
</div>
</div>
</div>
</body>

Auto size fixed text to fill dynamic size container

I'm trying to recreate this game in JavaScript. For this game, I need cells with numbers in them.
I want the game to size to the available space in the browser. I've managed to do this by using vw and vh in combination with width and min-width (and height) as you can see in the example. If you size the viewport in which the cells are shown, the cells size along.
The problem
And now, I want the text in it to size along too. The container (the cell) resizes, and the font of the digit should size accordingly. I now used vmax as a unit, but this doesn't take the horizontal sizing into account. And since there is no min-font-size, I cannot do the same trick I used for the cells themselves.
No jQuery please
I've tried and searched. Most notably, I found Auto-size dynamic text to fill fixed size container, however I think my question is reversed. The text is fixed, and I could set an initial font-size. I just need the font to scale along with the size of the element, so maybe this can be done through CSS after all.
Besides, most questions about this subject suggest using one of the various jQuery plugins and I'm not looking for a jQuery solution. I'm trying to make this game just for fun and practice, and I've set a goal to create it without jQuery. Actually I'm not even looking for a vanilla JavaScript solution. In the end it may boil down to that, but I haven't tried building it myself yet, so I don't want to ask for JavaScript here now. No, I'm looking for a pure CSS solution, if any.
The snippet
The dressed down snippet works best in full page mode. Nevermind the inline styling. These elements are actually generated by JavaScript and need be moved around. And sorry for the chunk of HTML. I brought it down to two cells at first, but that looked confusing, because they only filled a small part of the screen, and you couldn't see what was going on.
.game11,
.game11 .cell,
.game11 .cell .digit {
box-sizing: border-box;
}
.game11 {
width: 90vw;
height: 90vw;
max-width: 90vh;
max-height: 90vh;
box-sizing: border-box;
position: relative;
}
.game11 .cell {
width: 20%;
height: 20%;
position: absolute;
font-size: 7vmax; /* Font size. This obviously doesn't work */
}
.game11 .cell .digit {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
border: 3px solid #666633;
text-align: center;
padding-top: 13%;
font-family: Impact, Charcoal, sans-serif;
color: #111111;
}
<div class="game11">
<div class="cell" style="left: 0%; top: 0%;">
<div class="digit digit2" style="top: 0px;">2</div>
</div>
<div class="cell" style="left: 20%; top: 0%;">
<div class="digit digit2" style="top: 0px;">2</div>
</div>
<div class="cell" style="left: 40%; top: 0%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 60%; top: 0%;">
<div class="digit digit1" style="top: 0px;">1</div>
</div>
<div class="cell" style="left: 80%; top: 0%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 0%; top: 20%;">
<div class="digit digit1" style="top: 0px;">1</div>
</div>
<div class="cell" style="left: 20%; top: 20%;">
<div class="digit digit1" style="top: 0px;">1</div>
</div>
<div class="cell" style="left: 40%; top: 20%;">
<div class="digit digit4" style="top: 0px;">4</div>
</div>
<div class="cell" style="left: 60%; top: 20%;">
<div class="digit digit1" style="top: 0px;">1</div>
</div>
<div class="cell" style="left: 80%; top: 20%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 0%; top: 40%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 20%; top: 40%;">
<div class="digit digit2" style="top: 0px;">2</div>
</div>
<div class="cell" style="left: 40%; top: 40%;">
<div class="digit digit4" style="top: 0px;">4</div>
</div>
<div class="cell" style="left: 60%; top: 40%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 80%; top: 40%;">
<div class="digit digit4" style="top: 0px;">4</div>
</div>
<div class="cell" style="left: 0%; top: 60%;">
<div class="digit digit2" style="top: 0px;">2</div>
</div>
<div class="cell" style="left: 20%; top: 60%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 40%; top: 60%;">
<div class="digit digit5" style="top: 0px;">5</div>
</div>
<div class="cell" style="left: 60%; top: 60%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
<div class="cell" style="left: 80%; top: 60%;">
<div class="digit digit1" style="top: 0px;">1</div>
</div>
<div class="cell" style="left: 0%; top: 80%;">
<div class="digit digit4">4</div>
</div>
<div class="cell" style="left: 20%; top: 80%;">
<div class="digit digit1" style="top: 0px;">1</div>
</div>
<div class="cell" style="left: 40%; top: 80%;">
<div class="digit digit2" style="top: 0px;">2</div>
</div>
<div class="cell" style="left: 60%; top: 80%;">
<div class="digit digit5">5</div>
</div>
<div class="cell" style="left: 80%; top: 80%;">
<div class="digit digit3" style="top: 0px;">3</div>
</div>
</div>
Updated: The 'full' (still unfinished) game, including the fix suggested by Pangloss
In the snippet below, you can find the game as I have it so far. It's working for the largest part, so if it's not helpful for the question, at least it may be fun or helpful to future visitors.
/**
* Game11 class
*/
function Game11(container) {
var game = this;
game.element = container;
game.cells = [];
game.highestValue = 4;
game.animations = [];
game.animating = false;
var four = this.random(25);
for (var i = 0; i < 25; i++) {
var cell = new Cell(game, i);
var value = this.random(3) + 1;
if (i == four)
value = 4;
cell.setValue(value);
game.cells[i] = cell;
}
}
Game11.prototype.random = function(to) {
return Math.floor(Math.random() * to);
}
Game11.prototype.cellClicked = function(cell) {
if (cell.selected) {
this.collapse(cell);
} else {
this.select(cell);
}
}
Game11.prototype.collapse = function(cell) {
var newValue = cell.value + 1;
if (newValue > this.highestValue) {
this.highestValue = newValue;
}
cell.setValue(newValue);
for (var i = 24; i >= 0; i--) {
if (this.cells[i].selected) {
if (i !== cell.index) {
this.cells[i].setValue(null);
}
this.cells[i].select(false);
}
}
for (var i = 24; i >= 0; i--) {
if (this.cells[i].value == null) {
this.cells[i].collapse();
}
}
this.animate();
}
Game11.prototype.select = function(cell) {
for (var i = 0; i < 25; i++) {
this.cells[i].select(false);
}
var selectCount = 0;
var stack = [];
stack.push(cell);
while (stack.length > 0) {
var c = stack.pop();
c.select(true);
selectCount++;
var ac = this.getAdjacentCells(c);
for (var i = 0; i < ac.length; i++) {
if (ac[i].selected == false && ac[i].value == cell.value) {
stack.push(ac[i]);
}
}
}
if (selectCount == 1)
cell.select(false);
}
Game11.prototype.getAdjacentCells = function(cell) {
var result = [];
if (cell.x > 0) result.push(this.cells[cell.index - 1]);
if (cell.x < 4) result.push(this.cells[cell.index + 1]);
if (cell.y > 0) result.push(this.cells[cell.index - 5]);
if (cell.y < 4) result.push(this.cells[cell.index + 5]);
return result;
}
Game11.prototype.registerAnimation = function(animation) {
this.animations.push(animation);
}
Game11.prototype.animate = function() {
this.animating = true;
var maxTicks = 300;
var start = new Date().valueOf();
var timer = setInterval(function(){
var tick = new Date().valueOf() - start;
if (tick >= maxTicks) {
tick = maxTicks;
this.animating = false;
}
var percentage = 100 / maxTicks * tick;
for (a = 0; a < this.animations.length; a++) {
this.animations[a].step(percentage);
}
if (this.animating === false) {
clearInterval(timer);
this.animations.length = 0;
console.log('x');
}
}.bind(this), 1);
}
/**
* A single cell
*/
function Cell(game, index) {
var cell = this;
cell.game = game;
cell.index = index;
cell.selected = false;
cell.element = document.createElement('div');
cell.element.className = 'cell';
cell.digit = document.createElement('div');
cell.digit.className = 'digit';
cell.element.appendChild(cell.digit);
cell.element.addEventListener('click', cell.clicked.bind(cell));
game.element.appendChild(cell.element);
cell.x = index % 5;
cell.y = Math.floor((index - cell.x) / 5);
cell.element.style.left = (cell.x * 20) + '%';
cell.element.style.top = (cell.y * 20) + '%';
}
Cell.prototype.clicked = function() {
this.game.cellClicked(this);
}
Cell.prototype.setValue = function(value) {
this.digit.classList.remove('digit' + this.value);
this.value = value;
if (value === null) {
this.digit.innerText = '';
} else {
this.digit.classList.add('digit' + value);
this.digit.innerText = value;
}
}
Cell.prototype.select = function(selected) {
this.element.classList.toggle('selected', selected);
this.selected = selected;
}
Cell.prototype.collapse = function() {
var value, y, cellHere, cellAbove;
var n = this.y;
var offset = 0;
do {
cellHere = this.game.cells[this.x + 5*n];
y = n - offset;
value = null;
do {
if (--y >= 0) {
cellAbove = this.game.cells[this.x + 5*y];
value = cellAbove.value;
cellAbove.setValue(null);
if (value !== null) {
console.log('Value ' + value + ' for cell (' + this.x+','+n+') taken from cell ' + y);
}
} else {
offset++;
value = this.game.random(Math.max(3, this.game.highestValue - 2)) + 1;
console.log('New value ' + value + ' for cell (' + this.x+','+n+')');
}
} while (value === null);
cellHere.animateDrop(value, n-y);
} while (--n >= 0)
}
Cell.prototype.animateDrop = function(value, distance) {
this.setValue(value);
new Animation(this.game, -distance, this.index, value);
}
/**
* A cell animation
*/
function Animation(game, from, to, value) {
this.toCell = game.cells[to];
var cellBounds = this.toCell.element.getBoundingClientRect();
var fromX = toX = cellBounds.left;
var fromY = toY = cellBounds.top;
if (from < 0) {
fromY += cellBounds.height * from;
} else {
// To do: Moving from one cell to another needs an extra sprite.
this.fromCell = game.cells[from];
cellBounds = this.fromCell.element.getBoundingClientRect();
var fromX = cellBounds.left;
var fromY = cellBounds.top;
}
this.fromX = fromX;
this.fromY = fromY;
this.toX = toX;
this.toY = toY;
this.to = to;
game.registerAnimation(this);
}
Animation.prototype.step = function(percentage) {
var distance = this.toY - this.fromY;
var step = (100-percentage) / 100;
var Y = step * distance;
this.toCell.digit.style.top = '' + (-Y) + 'px';
}
// Start the game
new Game11(document.querySelector('.game11'));
.game11,
.game11 .cell,
.game11 .cell .digit {
box-sizing: border-box;
}
.game11 {
width: 90vmin;
height: 90vmin;
box-sizing: border-box;
position: relative;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.game11 .cell {
width: 20%;
height: 20%;
border: 2px solid #ffffff;
position: absolute;
font-size: 10vmin;
}
.game11 .cell .digit {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
border: 3px solid #666633;
text-align: center;
padding-top: 13%;
font-family: Impact, Charcoal, sans-serif;
color: #111111;
}
.game11 .cell.selected .digit {
color: white;
}
.game11 .digit.digit1 {
background-color: #CC66FF;
}
.game11 .digit.digit2 {
background-color: #FFCC66;
}
.game11 .digit.digit3 {
background-color: #3366FF;
}
.game11 .digit.digit4 {
background-color: #99CCFF;
}
.game11 .digit.digit5 {
background-color: #19D119;
}
.game11 .digit.digit6 {
background-color: #009999;
}
.game11 .digit.digit7 {
background-color: #996600;
}
.game11 .digit.digit8 {
background-color: #009933;
}
.game11 .digit.digit9 {
background-color: #666699;
}
.game11 .digit.digit10 {
background-color: #CC66FF;
}
.game11 .digit.digit11,
.game11 .digit.digitmax {
background-color: #FF0066;
}
<div class="game11">
</div>
You could set font size to vmin value.
.game11 .cell {
font-size: 10vmin;
}
http://jsfiddle.net/a21s77c8/
If there is no CSS solution, you can do it by JavaScript. This is quite easy, since all the game's cells are squared and the same size, so you can just get the font size as a factor of the game width. Because of these boundaries, there is no need for a complex library.
All you need to do is remove the font-size from the CSS and add this piece of code to the constructor of Game11:
// Function that calculates font size based on width of the game itself.
var updateFontSize = function() {
var bounds = game.element.getBoundingClientRect(); // Game
var size = bounds.width / 5; // Cell
size *= 0.6; // Font a bit smaller
game.element.style.fontSize = size + 'px';
};
// Attach to resize event.
window.addEventListener('resize', updateFontSize);
// Initial font size calculation.
updateFontSize();
Updated game:
/**
* Game11 class
*/
function Game11(container) {
var game = this;
game.element = container;
game.cells = [];
game.highestValue = 4;
game.animations = [];
game.animating = false;
var four = this.random(25);
// Function that calculates font size based on width of the game itself.
var updateFontSize = function() {
var bounds = game.element.getBoundingClientRect(); // Game
var size = bounds.width / 5; // Cell
size *= 0.6; // Font a bit smaller
game.element.style.fontSize = size + 'px';
};
// Attach to resize event.
window.addEventListener('resize', updateFontSize);
// Initial font size calculation.
updateFontSize();
for (var i = 0; i < 25; i++) {
var cell = new Cell(game, i);
var value = this.random(3) + 1;
if (i == four)
value = 4;
cell.setValue(value);
game.cells[i] = cell;
}
}
Game11.prototype.random = function(to) {
return Math.floor(Math.random() * to);
}
Game11.prototype.cellClicked = function(cell) {
if (cell.selected) {
this.collapse(cell);
} else {
this.select(cell);
}
}
Game11.prototype.collapse = function(cell) {
var newValue = cell.value + 1;
if (newValue > this.highestValue) {
this.highestValue = newValue;
}
cell.setValue(newValue);
for (var i = 24; i >= 0; i--) {
if (this.cells[i].selected) {
if (i !== cell.index) {
this.cells[i].setValue(null);
}
this.cells[i].select(false);
}
}
for (var i = 24; i >= 0; i--) {
if (this.cells[i].value == null) {
this.cells[i].collapse();
}
}
this.animate();
}
Game11.prototype.select = function(cell) {
for (var i = 0; i < 25; i++) {
this.cells[i].select(false);
}
var selectCount = 0;
var stack = [];
stack.push(cell);
while (stack.length > 0) {
var c = stack.pop();
c.select(true);
selectCount++;
var ac = this.getAdjacentCells(c);
for (var i = 0; i < ac.length; i++) {
if (ac[i].selected == false && ac[i].value == cell.value) {
stack.push(ac[i]);
}
}
}
if (selectCount == 1)
cell.select(false);
}
Game11.prototype.getAdjacentCells = function(cell) {
var result = [];
if (cell.x > 0) result.push(this.cells[cell.index - 1]);
if (cell.x < 4) result.push(this.cells[cell.index + 1]);
if (cell.y > 0) result.push(this.cells[cell.index - 5]);
if (cell.y < 4) result.push(this.cells[cell.index + 5]);
return result;
}
Game11.prototype.registerAnimation = function(animation) {
this.animations.push(animation);
}
Game11.prototype.animate = function() {
this.animating = true;
var maxTicks = 300;
var start = new Date().valueOf();
var timer = setInterval(function(){
var tick = new Date().valueOf() - start;
if (tick >= maxTicks) {
tick = maxTicks;
this.animating = false;
}
var percentage = 100 / maxTicks * tick;
for (a = 0; a < this.animations.length; a++) {
this.animations[a].step(percentage);
}
if (this.animating === false) {
clearInterval(timer);
this.animations.length = 0;
console.log('x');
}
}.bind(this), 1);
}
/**
* A single cell
*/
function Cell(game, index) {
var cell = this;
cell.game = game;
cell.index = index;
cell.selected = false;
cell.element = document.createElement('div');
cell.element.className = 'cell';
cell.digit = document.createElement('div');
cell.digit.className = 'digit';
cell.element.appendChild(cell.digit);
cell.element.addEventListener('click', cell.clicked.bind(cell));
game.element.appendChild(cell.element);
cell.x = index % 5;
cell.y = Math.floor((index - cell.x) / 5);
cell.element.style.left = (cell.x * 20) + '%';
cell.element.style.top = (cell.y * 20) + '%';
}
Cell.prototype.clicked = function() {
this.game.cellClicked(this);
}
Cell.prototype.setValue = function(value) {
this.digit.classList.remove('digit' + this.value);
this.value = value;
if (value === null) {
this.digit.innerText = '';
} else {
this.digit.classList.add('digit' + value);
this.digit.innerText = value;
}
}
Cell.prototype.select = function(selected) {
this.element.classList.toggle('selected', selected);
this.selected = selected;
}
Cell.prototype.collapse = function() {
var value, y, cellHere, cellAbove;
var n = this.y;
var offset = 0;
do {
cellHere = this.game.cells[this.x + 5*n];
y = n - offset;
value = null;
do {
if (--y >= 0) {
cellAbove = this.game.cells[this.x + 5*y];
value = cellAbove.value;
cellAbove.setValue(null);
if (value !== null) {
console.log('Value ' + value + ' for cell (' + this.x+','+n+') taken from cell ' + y);
}
} else {
offset++;
value = this.game.random(Math.max(3, this.game.highestValue - 2)) + 1;
console.log('New value ' + value + ' for cell (' + this.x+','+n+')');
}
} while (value === null);
cellHere.animateDrop(value, n-y);
} while (--n >= 0)
}
Cell.prototype.animateDrop = function(value, distance) {
this.setValue(value);
new Animation(this.game, -distance, this.index, value);
}
/**
* A cell animation
*/
function Animation(game, from, to, value) {
this.toCell = game.cells[to];
var cellBounds = this.toCell.element.getBoundingClientRect();
var fromX = toX = cellBounds.left;
var fromY = toY = cellBounds.top;
if (from < 0) {
fromY += cellBounds.height * from;
} else {
// To do: Moving from one cell to another needs an extra sprite.
this.fromCell = game.cells[from];
cellBounds = this.fromCell.element.getBoundingClientRect();
var fromX = cellBounds.left;
var fromY = cellBounds.top;
}
this.fromX = fromX;
this.fromY = fromY;
this.toX = toX;
this.toY = toY;
this.to = to;
game.registerAnimation(this);
}
Animation.prototype.step = function(percentage) {
var distance = this.toY - this.fromY;
var step = (100-percentage) / 100;
var Y = step * distance;
this.toCell.digit.style.top = '' + (-Y) + 'px';
}
// Start the game
new Game11(document.querySelector('.game11'));
.game11,
.game11 .cell,
.game11 .cell .digit {
box-sizing: border-box;
}
.game11 {
width: 90vw;
height: 90vw;
max-width: 90vh;
max-height: 90vh;
box-sizing: border-box;
position: relative;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.game11 .cell {
width: 20%;
height: 20%;
border: 2px solid #ffffff;
position: absolute;
}
.game11 .cell .digit {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
border: 3px solid #666633;
text-align: center;
padding-top: 13%;
font-family: Impact, Charcoal, sans-serif;
color: #111111;
}
.game11 .cell.selected .digit {
color: white;
}
.game11 .digit.digit1 {
background-color: #CC66FF;
}
.game11 .digit.digit2 {
background-color: #FFCC66;
}
.game11 .digit.digit3 {
background-color: #3366FF;
}
.game11 .digit.digit4 {
background-color: #99CCFF;
}
.game11 .digit.digit5 {
background-color: #19D119;
}
.game11 .digit.digit6 {
background-color: #009999;
}
.game11 .digit.digit7 {
background-color: #996600;
}
.game11 .digit.digit8 {
background-color: #009933;
}
.game11 .digit.digit9 {
background-color: #666699;
}
.game11 .digit.digit10 {
background-color: #CC66FF;
}
.game11 .digit.digit11,
.game11 .digit.digitmax {
background-color: #FF0066;
}
<div class="game11">
</div>
Still, if it could be done through CSS, that'd be great.