Unexpected Javascript Behavior - javascript

I tried making the classic game of snake and walls using table only (contrary to canvas). Everything worked fine and there are no errors or bugs in the initial run.
The first problem is that when the snake collects second golden block, it leaves a fragment, but as per code, that color should become black after the snake leaves the cell.
Second, The golden dots stop appearing on the screen even when their locations are set and accessible.
Line 257 : showSnakeHead() --> Shows the snake
Line 205 : checkCollision() --> checks collisions
Javascript Code
engine.js
// <div id="output"></div>
// <div id="display"></div>
// bind things together
function startEngine(){
// SIZE OF GAME
SETTING__rows = 22;
SETTING__cols = 40;
GAME__START = 0;
GAME__PAUSE = 0;
GAME_SPEED = 350;
GAME_END = 0;
GAME_SCORE = 0;
// For Enhanced Testing
// SETTING__rows = 200;
// SETTING__cols = 200;
GAME_SPEED = 50;
// APPEARANCE
COLOR__border = "#696969";
COLOR__snake = "#FF6347";
COLOR__target = "#FFDF00";
COLOR__default = "black";
// CONTROL
SNAKE_DIR = "UP";
SNAKE_X = 0;
SNAKE_Y = 0;
SNAKE_LENGTH = 0;
SNAKE_PATH = [];
SNAKE_TARGET = 0;
SNAKE_TARGET_X = 0;
SNAKE_TARGET_Y = 0;
SNAKE_TMP = [0,0];
// FUNCTIONS
makeGrid();
paintGrid();
makeSnake();
// Game function
setInterval(runGame, GAME_SPEED);
}
// main functions
function makeGrid(){
var x = "<table >";
for(var i=0; i<SETTING__rows; i++){
x+= "<tr>";
for(var j=0; j<SETTING__cols; j++){
x+= "<td class='gameBox' id='__"+j+"-"+i+"'>";
x+= "</td>";
}
x+= "</tr>";
}
x+= "</table>";
$("#output").html(x);
// console.log();
}
function paintGrid(){
for(i=0; i<SETTING__rows; i++){
for(j=0; j<SETTING__cols; j++){
if(j==0 || j==SETTING__cols-1){
$("#__"+j+"-"+i).css("background-color",COLOR__border);
}
if(i==0 || i==SETTING__rows-1){
$("#__"+j+"-"+i).css("background-color",COLOR__border);
}
}
}
}
function makeSnake(){
// calculate the mid
var midCol = parseInt(SETTING__cols)/2;
var midRow = parseInt(SETTING__rows)/2;
// Store Location
SNAKE_X = midCol;
SNAKE_Y = midRow;
// paint the snake
$("#__"+midCol+"-"+midRow).css("background-color",COLOR__snake);
// Create Head of snake
SNAKE_PATH.push([midCol, midRow]);
SNAKE_LENGTH ++;
}
function startGame(){
GAME__START = 1;
console.log("start");
console.log(GAME__START);
}
function pauseGame(){
GAME__PAUSE = 1;
console.log("pause");
console.log(GAME__PAUSE);
}
function resumeGame(){
GAME__PAUSE = 0;
console.log("resume");
console.log(GAME__PAUSE);
}
function runPauseResume(){
// GAME__START
if(GAME__START == 0){
// start game
startGame();
}
else if(GAME__PAUSE == 0){
pauseGame();
}
else if(GAME__PAUSE == 1){
resumeGame();
}
}
// Bindings
$("#output").on('click', function(){
runPauseResume();
});
// Key Bindings
$(document).keydown(function(e){
// space
if(e.keyCode == 32){
runPauseResume();
}
// left
if(e.keyCode==37){
SNAKE_DIR = "LEFT";
console.log("LEFT");
}
// right
if(e.keyCode==38){
SNAKE_DIR = "UP";
console.log("UP");
}
// up
if(e.keyCode==39){
SNAKE_DIR = "RIGHT";
console.log("RIGHT");
}
// down
if(e.keyCode==40){
SNAKE_DIR = "DOWN";
console.log("DOWN");
}
// Prefect Default action of keys
e.preventDefault();
});
// FINAL GAME FUNCTIONS
function runGame(){
if(GAME__START == 1 && GAME__PAUSE == 0 && GAME_END == 0){
// move in direction
direction = SNAKE_DIR;
if(direction == "DOWN"){
SNAKE_X = SNAKE_X;
SNAKE_Y = SNAKE_Y+1;
checkCollision();
// showSnakeHead();
}
else if(direction == "UP"){
SNAKE_X = SNAKE_X;
SNAKE_Y = SNAKE_Y-1;
checkCollision();
// showSnakeHead();
}
else if(direction == "RIGHT"){
SNAKE_X = SNAKE_X+1;
SNAKE_Y = SNAKE_Y;
checkCollision();
// showSnakeHead();
}
else if(direction == "LEFT"){
SNAKE_X = SNAKE_X-1;
SNAKE_Y = SNAKE_Y;
checkCollision();
// showSnakeHead();
}
showSnakeHead();
console.log(direction);
console.log("New Head = " + SNAKE_X + ", " + SNAKE_Y);
}
}
function checkCollision(){
if(SNAKE_X == 0 || SNAKE_X == SETTING__cols-1 ){
alert("GAME OVER !");
GAME_END = 1;
}
if(SNAKE_Y == 0 || SNAKE_Y == SETTING__rows-1 ){
alert("GAME OVER !");
GAME_END = 1;
}
// if get the target
if(SNAKE_TARGET_X == SNAKE_X && SNAKE_TARGET_Y == SNAKE_Y){
// disappear the target
$("#__"+SNAKE_TARGET_X+"-"+SNAKE_TARGET_Y).css("background-color",COLOR__default);
// create new target
SNAKE_TARGET = 0;
// increment Score
GAME_SCORE ++;
// Increase Snake Length
SNAKE_LENGTH ++;
// Increase length of stored locations
SNAKE_PATH.push([SNAKE_TARGET_X, SNAKE_TARGET_Y]);
console.log("Score : " + GAME_SCORE);
$("title").text("Score - " + GAME_SCORE);
}
if(SNAKE_TARGET == 0){
// Create target to eat
SNAKE_TARGET_X = getRandomInclusive(2,SETTING__cols-2);
SNAKE_TARGET_Y = getRandomInclusive(2,SETTING__rows-2);
// paint target
$("#__"+SNAKE_TARGET_X+"-"+SNAKE_TARGET_Y).css("background-color",COLOR__target);
// mark that target now exist
SNAKE_TARGET = 1;
}
}
// most complicated function
function moveSnake(){
}
// shows movement of snake
function showSnakeHead(){
// shift array by one
for (var i = SNAKE_PATH.length-1 ; i >= 0; i--) {
// disappear the tale
$("#__"+SNAKE_PATH[SNAKE_PATH.length-1][0] +"-"+SNAKE_PATH[SNAKE_PATH.length-1][1]).css("background-color",COLOR__default);
console.log("DSIAPPEARING TALE");
// shift array by one
SNAKE_PATH[i] = SNAKE_PATH[i-1];
// new head
SNAKE_PATH[0] = [SNAKE_X,SNAKE_Y];
}
// show rest of snake
for(var j=0; j < SNAKE_PATH.length; j++){
// console.log(SNAKE_PATH[i][0],SNAKE_PATH[i][1]);
console.log("DISPLAY !---------------------------------------------------");
console.log(SNAKE_PATH[j]);
$("#__"+SNAKE_PATH[j][0] +"-"+SNAKE_PATH[j][1]).css("background-color",COLOR__snake);
// console.log(SNAKE_PATH[i]);
}
// $("#__"+SNAKE_X+"-"+SNAKE_Y).css("background-color",COLOR__snake);
}
function getRandomInclusive(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
HTML
(nothing cool here)
<!DOCTYPE html>
<html>
<head>
<title>Coding Playground</title>
<link rel="stylesheet" type="text/css" href="assets/bootstrap.css">
<link rel="stylesheet" type="text/css" href="assets/game.css">
</head>
<body>
<div class="jumbotron">
<h1 class="display-3">Snake game !</h1>
<p class="lead">This is a simple hero unit, a simple snake game .</p>
<hr class="my-4">
<p>Contribute to the development on github</p>
</div>
<div class="container">
<div id="output" class="style0"></div>
</div>
<div id="display">
</div>
</body>
<script type="text/javascript" src="assets/popper.js"></script>
<script type="text/javascript" src="assets/jquery.js"></script>
<script type="text/javascript" src="assets/bootstrap.js"></script>
<script type="text/javascript" src="assets/engine.js"></script>
<script type="text/javascript">
$(document).ready(function(){
startEngine();
});
</script>
</html>
images of bugs

The first problem is that when the snake collects second golden block, it leaves a fragment, but as per code, that color should become black after the snake leaves the cell.
Not sure, but I expect the problem is in showSnakeHead:
// shift array by one
for (var i = SNAKE_PATH.length-1 ; i >= 0; i--) {
You shouldn't need an entire loop like this to shift the array by one. Use shift / unshift.
Second, The golden dots stop appearing on the screen even when their locations are set and accessible.
Your code to generate a new target doesn't check to see if that cell is already occupied by the snake! When that happens, it will be invisible because its immediately overwritten by the snake drawing code, and nothing sets it back to the correct color.

Related

HTML DOM id Array Property & Adding to Stage JavaScript (Array)

I am trying to create an array of values using a for loop in JavaScript with multiple div id's with successive numbers (i.e. their values) denoting depth. The issue that I am running into is that I can't add the DOM element, i.e. 'text by ship here' successfully to the stage. I added // to show different sections where I am stuck. In particular, I believe I am stuck on the for loop part of the code below //Trying to create a div array here with id's q0, q1, q2, ..., q3 and have used different functions such as for div[0].setAttribute("id", "q0") to be able to connect it with the create.jsDOMElement to add this text to the stage. Any help would be extremely appreciated! My apologies in advance if the code is too long. I have tried to express it succinctly.
<html>
<script type="text/javascript" src="//code.createjs.com/createjs-2013.09.25.combined.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#gameCanvas {
background-color: lightblue;
}
</style>
<div class="canvasHolder1">
<div id="ship">⛵ </div>
<script>
</script>
<canvas id="gameCanvas" width="300" height="300">Not supported</canvas>
<script type="text/javascript">
var stage = new createjs.Stage("gameCanvas");
//Trying to create a div array here with id's q0, q1, q2, ..., q3
var div = [];
for(i=0; i<=3; i++){
div[i] = document.createElement("type");
div[i].id = `q${i}`;
div[i].innerHTML = 'text by ship here';
document.body.appendChild(div[i]);
}
//Creating an object array of div elements to add to the stage
var objectArray = [];
objectArray[0] = new createjs.DOMElement(document.getElementById("q0"));
var object = new createjs.DOMElement(document.getElementById("ship"));
can = document.getElementById("gameCanvas");
object.x = can.width/3;
object.y = 50;
//Adding First Value to the Stage
objectArray[0].x= can.width/3;
objectArray[0].y = 55;
function startGame() {
stage.addChild(object);
stage.addChild(objectArray[0]);
createjs.Ticker.addEventListener("tick", handleTick);
function handleTick(event) {
drop();
stage.update();
}
}
function drop(){
if ( object.y>=can.height){
object.x += 0;
object.y +=5;
}
}
</script>
<body onload="startGame();">
<div >
<canvas>This browser or document mode doesn't support canvas object.</canvas>
</div>
</body>
</html>
I have been able to make some progress on this. I am now running into the issue with the numbers needing to appear relative to the pixel 0, 0 on the Canvas/screen now, i.e. see the word relative.
<h1> I have some text here, and I need the numbers to appear relative to the Canvas/screen. </h1>
</br> </br>
<script type="text/javascript" src="//code.createjs.com/createjs-2013.09.25.combined.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#gameCanvas {
background-color: LightCyan;
}
</style>
<div class="canvasHolder1">
<div id="alien"> |- - - - -| (1.5 mph)</div>
<div id="alien1"> 🎐</div>
<div id="alien2"> 🦑 </div>
<div id="alien3">🦈</div>
<div id="alien4"> 🐬 </div>
<script>
</script>
<canvas id="gameCanvas" width="300" height="300">Not supported</canvas>
<script type="text/javascript">
var stage = new createjs.Stage("gameCanvas");
//Trying to create a div array here with id's q0, q1, q2, ..., q3 k is number of numbers
var k=10;
var div = [];
for(i=0; i<=k; i++){
div[i] = document.createElement('div');
div[i].id = `q${i}`;
div[i].style.position = "relative";
div[i].innerHTML = i;
div[i].style.top = 0;
div[i].style.left = 0;
document.body.appendChild(div[i]);
}
//Creating an object array of div elements to add to the stage
var objectArray = [];
for(j=0; j<=k; j++){
objectArray[j] = new createjs.DOMElement(document.getElementById(`q${j}`));
}
var object = new createjs.DOMElement(document.getElementById("alien"));
var object1 = new createjs.DOMElement(document.getElementById("alien1"));
var object2 = new createjs.DOMElement(document.getElementById("alien2"));
var object3 = new createjs.DOMElement(document.getElementById("alien3"));
var object4 = new createjs.DOMElement(document.getElementById("alien4"));
can = document.getElementById("gameCanvas");
for(l=0; l<=k; l++){
objectArray[l].x= 50;
objectArray[l].y = can.height/10*l;
}
object1.x = can.width/3;
object1.y = 1;
object2.x = can.width/5;
object2.y = 1;
object3.x = can.width/10;
object3.y = 1;
object4.x = can.width/2.5;
object4.y = 1;
object.x = can.width/2;
object.y = 1;
var speedY=5;
var speedX=5;
var speedY1=5;
var speedX1=5;
var speedY2=5;
var speedX2=5;
var speedY3=5;
var speedX3=5;
var speedY4=5;
var speedX4=5;
var line = new createjs.Shape();
stage.addChild(line);
line.graphics.setStrokeStyle(3).beginStroke("rgba(0,0,0,9)");
line.graphics.moveTo(30, 0);
line.graphics.lineTo(35, 0);
line.graphics.lineTo(30, 0);
for( let n=0; n<=k; n++){
var j=5;
line.graphics.lineTo(30, can.height/10*n);
line.graphics.lineTo(30+j, can.height/10*n);
line.graphics.lineTo(30, can.height/10*n);
}
line.graphics.endStroke();
function startGame() {
stage.addChild(object);
stage.addChild(object1);
stage.addChild(object2);
stage.addChild(object3);
stage.addChild(object4);
for(i=0; i<=k; i++){
stage.addChild(objectArray[i]);
}
createjs.Ticker.addEventListener("tick", handleTick);
function handleTick(event) {
drop();
bottom();
right();
left();
drop1();
bottom1();
right1();
left1();
drop2();
bottom2();
right2();
left2();
drop3();
bottom3();
right3();
left3();
drop4();
bottom4();
right4();
left4();
stage.update();
}
}
function drop(){
if ( object.y>=can.height|| speedY==5|| object.y<=0){
object.x += 0;
object.y +=1;
speedY=5;
}
}
function bottom(){
if (object.y>=can.height|| speedY==-5){ // <----- here
speedY=5;
object.y =0.5;
object.x +=0.5;
document.getElementById("object").textContent = "3k";
}
}
function right(){
if (object.x>=can.width ||speedY==10 ){ // <----- here
speedY=10;
object.y -=1;
object.x -=1;
}
}
function left(){
if (0>=object.x ||speedY==30 ){ // <----- here
speedY=30;
object.y -=0.5;
object.x +=0.5;
}
}
function drop1(){
if ( object1.y>=can.height|| speedY1==5|| object1.y<=0){
object1.x -= 0.5;
object1.y +=2;
speedY1=5;
}
}
function bottom1(){
if (object1.y>=can.height|| speedY1==-5){ // <----- here
speedY1=-5;
object1.y -=2;
object1.x -=0.5;
}
}
function right1(){
if (object1.x>=can.width ||speedY1==10 ){ // <----- here
speedY1=10;
object1.y -=1;
object1.x -=1.5;
}
}
function left1(){
if (0>=object1.x ||speedY1==30 ){ // <----- here
speedY1=30;
object1.y -=1.5;
object1.x +=1;
}
}
function drop2(){
if ( object2.y>=can.height|| speedY2==5|| object2.y<=0){
object2.x += 0;
object2.y +=1;
speedY2=5;
}
}
function bottom2(){
if (object2.y>=can.height|| speedY2==-5){ // <----- here
speedY2=-5;
object2.y -=1;
object2.x +=5;
}
}
function right2(){
if (object2.x>=can.width ||speedY2==10 ){ // <----- here
speedY2=10;
object2.y -=6;
object2.x -=5;
}
}
function left2(){
if (0>=object2.x ||speedY2==30 ){ // <----- here
speedY2=30;
object2.y -=6;
object2.x +=5;
}
}
function drop3(){
if ( object3.y>=can.height|| speedY3==5|| object3.y<=0){
object3.x += 0.5;
object3.y +=0.2;
speedY3=5;
}
}
function bottom3(){
if (object3.y>=can.height|| speedY3==-5){ // <----- here
speedY3=-5;
object3.y -=4;
object3.x -=2;
}
}
function right3(){
if (object3.x>=can.width ||speedY3==10 ){ // <----- here
speedY3=10;
object3.y -=0.5;
object3.x -=0.5;
}
}
function left3(){
if (0>=object3.x ||speedY3==30 ){ // <----- here
speedY3=30;
object3.y -=0.5;
object3.x +=0.5;
}
}
function drop4(){
if ( object4.y>=can.height|| speedY4==5|| object4.y<=0){
object4.x += 0;
object4.y +=0.25;
speedY4=5;
}
}
function bottom4(){
if (object4.y>=can.height|| speedY4==-5){ // <----- here
speedY4=-5;
object4.y -=0.3;
object4.x +=1;
}
}
function right4(){
if (object4.x>=can.width ||speedY4==10 ){ // <----- here
speedY4=10;
object4.y -=0.5;
object4.x -=1;
}
}
function left4(){
if (0>=object4.x ||speedY4==30 ){ // <----- here
speedY4=30;
object4.y -=0.5;
object4.x +=1;
}
}
</script>
<body onload="startGame();">
<div >
<canvas>This browser or document mode doesn't support canvas object.</canvas>
</div>
</body>
Does this work for you?
<html>
<script type="text/javascript" src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
body { margin: 0; }
#gameCanvas { background-color: lightblue; }
.canvasHolder1 { position: relative; }
.ui { position: absolute; top: 0; left: 0; pointer-events: none;}
.ui-element { position: relative; display: inline-block; margin-left: 4px; }
</style>
<body onload="startGame();">
<div class="canvasHolder1">
<div id="ship">⛵ </div>
<div class="ui"></div>
<canvas id="gameCanvas" width="300" height="300">Not supported</canvas>
</div>
<script type="text/javascript">
const stage = new createjs.Stage("gameCanvas");
const ship = document.getElementById("ship");
const ui = document.querySelector(".ui");
const canvas = document.getElementById("gameCanvas");
const canvasHolder = document.querySelector('.canvasHolder1');
var divs = [];
const texts = [ 'My Ship', 'Pos X', 'Pos Y', 'Other' ];
for (i = 0; i <= 3; i++) {
const newDiv = document.createElement("type");
newDiv.id = `q${i}`;
newDiv.className = `ui-element`;
newDiv.innerHTML = texts[i];
ui.appendChild(newDiv);
divs.push(newDiv);
}
const textXPosition = divs[1];
const textYPosition = divs[2];
const textProgress = divs[3];
canvas.addEventListener('mousemove', (evt) => {
textXPosition.innerHTML = evt.pageX;
textYPosition.innerHTML = evt.pageY;
});
var objectArray = [];
objectArray.push(new createjs.DOMElement(divs[0]));
const myFirstText = objectArray[0];
const myFirstTextWidth = parseInt(myFirstText.htmlElement.offsetWidth);
var shipJS = new createjs.DOMElement(ship);
function applyPosition(posObject) {
shipJS.x = posObject.x;
shipJS.y = posObject.y;
myFirstText.x = posObject.x - (myFirstTextWidth / 2);
myFirstText.y = posObject.y - 15;
}
const shipPosition = {
x: canvas.width / 3,
y: 50
};
applyPosition(shipPosition);
let looperCount = -1;
const step = 0.02;
const distance = canvas.width / 3;
function handleTick(event) {
if (looperCount >= 1) { looperCount = -1; }
looperCount += step;
const progress = Math.PI * looperCount;
textProgress.innerHTML = parseInt(((looperCount + 1) / 2) * 100 )+'%';
applyPosition({
x: (Math.cos(progress) * distance) + (distance * 1.5),
y: (Math.sin(progress) * distance) + (distance * 1.5)
});
stage.update();
}
function startGame() {
stage.addChild(shipJS);
stage.addChild(myFirstText);
createjs.Ticker.addEventListener("tick", handleTick);
}
</script>
</body>
</html>

javascript random gen nr + loops

I'm trying to make an program where it randomly picks 10 questions out of X questions(got 14 random ones written at the moment) without it picking the same questions again but i've been stuck for 4 hours on this junk.
My problem is with "randomNumbers()" function. This function generates random number (which marks the question respectively) and then checks if the numberArray already has generated number. If it doesnt, the number is supposed to be pushed to array.
I think I figured out the problem to be ## VERSION 1 ## for-loops if/else conditions. Any help ? :(
//edit, is while (true) correct way to handle this?
// dont mind ##VERSION 2## it was the first way I tried solving the problem.
(a lot of console logs to determine the bug :P )
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8"/>
<title>Testimiskeskkond</title>
<!--<link rel="stylesheet" type="text/css" href="style.css"/> -->
<script src="scripts/jquery-2.1.4.min.js"></script>
<script src="scripts/js.js"></script>
</head>
<body>
<button onclick="startQuiz()">Alusta testimist</button>
<div id="question1"></div>
<div id=questions></div>
</body>
JAVASCRIPT
var amountOfQuestions = 11;
var questionCounter = 0;
var numberArray = new Array();
var questions = new Array();
questions[0] = 'Mitu kassi elab P2rnus?',
questions[1] = 'Mis on kassi nimi?',
questions[2] = 'Mida kass teeb?',
questions[3] = 'Millal kass syndis?',
questions[4] = 'Mitu hammast kassil on?',
questions[5] = 'Mitu kyynt on kassil?',
questions[6] = 'Mitu k6rva on kassil?',
questions[7] = 'Mis v2rvi on kass?',
questions[8] = 'Tooli v2rvus?',
questions[9] = 'Laua suurus?',
questions[10] = 'Lemmik jook?',
questions[11] = 'Lemmik s88k?',
questions[12] = 'Raamatupoe nimi?',
questions[13] = 'Viinapoe nimi?';
function startQuiz() {
var setQuestions = "";
while (questionCounter < amountOfQuestions) {
var random = randomNumbers();
console.log(random + "appppppi");
if (questionCounter < amountOfQuestions) {
setQuestions += questions[random] + "<br>";
questionCounter += 1;
} else {
setQuestions += questions[random];
questionCounter += 1;
}
}
$('#questions').html(setQuestions);
}
function randomNumbers() {
var arrLength = numberArray.length;
while (true) {
console.log(arrLength);
var randomNr = Math.floor(Math.random() * 14);
console.log(randomNr + " tereeeeeeeeee");
/*
######################
########### VERSION 1
######################*/
if (arrLength == 0) {
console.log("pppppppppppp");
numberArray.push(randomNr);
break;
} else if (arrLength == 1) {
console.log("oooooooooooo");
if (numberArray[0] == randomNr) {
console.log("xxxxxxxxxxxxx");
break;
} else {
console.log("rrrrrrrrrrrrrrr");
numberArray.push(randomNr);
break;
}
} else {
for (var i = 0; i < arrLength-1; i++) {
console.log("yyyyyyyyyyyyyyyyyyyy");
if (numberArray[i] == randomNr) {
console.log("qqqqqqqqqqqqqqqqqqqq");
continue;
} else {
console.log("zzzzzzzzzzzzzz")
numberArray.push(randomNr);
break;
}
}
}
/*
######################
########### VERSION 2
######################
if (arrLength > 0) {
console.log("oooooooooooo");
for (var i = 0; i < arrLength; i++) {
console.log("yyyyyyyyyyyyyyyyyyyy");
if (numberArray[i] == randomNr) {
console.log("qqqqqqqqqqqqqqqqqqqq");
continue;
} else {
console.log("zzzzzzzzzzzzzz")
numberArray.push(randomNr);
break;
}
}
} else {
console.log("pppppppppppp");
numberArray.push(randomNr);
break;
} */
}
return randomNr;
}
let selectionCount = 10;
let randomQuestions = [];
while(randomQuestions.length < selectionCount) {
let randomNr = Math.floor(Math.random() * questionList.length);
if(!randomQuestions.includes(randomNr)) {
randomQuestions.push(randomNbr);
}
}

Tracking time and display it at next game

I have an assignment and I am a bit stuck. The assignment states:
Modify the game so that the time is tracked and a best time (or time to beat) is stored and displayed at the end of the game and at the beginning of the next game that is played. This functionality assumes the browser is not closed and that each successive game is begun through the "Play Again?" link. The display of the time to beat is shown below.
I have all files necessary, but I am stuck in this part. Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var placementArray = [];
var tileClicked;
var timeAllowable;
var totalMatchesPossible;
var matchesFound;
var txt;
var matchesFoundText;
var tileHeight = 30;
var tileWidth = 45;
var border = 1;
var globalPadding = 10;
var margin = 10;
var padding = 5;
var textTiles;
var flashcards = [
["a", "\u3042"],
["i", "\u3044"],
["u", "\u3046"],
["e", "\u3048"],
["o", "\u304A"],
["ka", "\u304B"],
["ki", "\u304D"],
["ku", "\u304F"],
["ke", "\u3051"],
["ko", "\u3053"],
["sa", "\u3055"],
["shi", "\u3057"],
["su", "\u3059"],
["se", "\u305B"],
["so", "\u305D"],
["ta", "\u305F"],
["chi", "\u3061"],
["tsu", "\u3064"],
["te", "\u3066"],
["to", "\u3068"],
["na", "\u306A"],
["ni", "\u306B"],
["nu", "\u306C"],
["ne", "\u306D"],
["no", "\u306E"],
["ha", "\u306F"],
["hi", "\u3072"],
["fu", "\u3075"],
["he", "\u3078"],
["ho", "\u307B"],
["ma", "\u307E"],
["mi", "\u307F"],
["mu", "\u3080"],
["me", "\u3081"],
["mo", "\u3082"],
["ya", "\u3084"],
["yu", "\u3086"],
["yo", "\u3088"],
["ra", "\u3089"],
["ri", "\u308A"],
["ru", "\u308B"],
["re", "\u308C"],
["ro", "\u308D"],
["wa", "\u308F"],
["wo", "\u3092"],
["n", "\u3093"]
];
function init() {
canvas = document.getElementById('myCanvas');
stage = new Stage(canvas);
totalMatchesPossible = flashcards.length;
var numberOfTiles = totalMatchesPossible * 2;
matchesFound = 0;
var columns = 12;
timeAllowable = 500;
txt = new Text(timeAllowable, "30px Monospace", "#000");
txt.textBaseline = "top";
txt.x = 700;
txt.y = 0;
stage.addChild(txt);
textTiles = [];
matchesFoundText = new Text(matchesFound + "/" + totalMatchesPossible, "30px Monospace", "#000");
matchesFoundText.textBaseline = "top";
matchesFoundText.x = 700;
matchesFoundText.y = 40;
stage.addChild(matchesFoundText);
Ticker.init();
Ticker.addListener(window);
Ticker.setPaused(false);
setPlacementArray(numberOfTiles);
for (var i = 0; i < numberOfTiles; i++) {
var placement = getRandomPlacement(placementArray);
var pairIndex = Math.floor(i / 2);
text = flashcards[pairIndex][i % 2];
var textTile = drawTextTile(text, pairIndex);
textTile.x = (tileWidth + margin) * (placement % columns) + globalPadding;
textTile.y = (tileHeight + margin) * Math.floor(placement / columns) + globalPadding;
stage.addChild(textTile);
background = new Shape();
background.x = textTile.x - padding;
background.y = textTile.y - padding;
background.graphics.setStrokeStyle(border).beginStroke("#000").beginFill('#eee').drawRect(0, 0, tileWidth, tileHeight);
textTiles.push(background);
stage.addChildAt(background);
background.text = textTile;
background.onPress = handleOnPress;
stage.update();
};
}
function drawTextTile(text, pairIndex) {
textTile = new Text(text, "20px Monospace", "#000");
textTile.pairIndex = pairIndex;
textTile.textBaseline = "top";
return textTile;
}
function randomColor() {
var color = Math.floor(Math.random() * 255);
var color2 = Math.floor(Math.random() * 255);
var color3 = Math.floor(Math.random() * 255);
return Graphics.getRGB(color, color2, color3)
}
function setPlacementArray(numberOfTiles) {
for (var i = 0; i < numberOfTiles; i++) {
placementArray.push(i);
}
}
function getRandomPlacement(placementArray) {
randomNumber = Math.floor(Math.random() * placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event) {
var tile = event.target;
if (!!tileClicked === false || tileClicked === tile) {
tileClicked = tile;
} else {
tileClicked.graphics.beginFill('#eee').drawRect(0, 0, tileWidth, tileHeight);
tile.graphics.beginFill('#aae').drawRect(0, 0, tileWidth, tileHeight);
if (tileClicked.text.pairIndex === tile.text.pairIndex && tileClicked.id != tile.id) {
tileClicked.visible = false;
tile.visible = false;
matchesFound++;
matchesFoundText.text = matchesFound + "/" + totalMatchesPossible;
if (matchesFound === totalMatchesPossible) {
gameOver(true);
}
}
tileClicked = tile;
}
stage.update();
}
function tick() {
secondsLeft = Math.floor((timeAllowable - Ticker.getTime() / 1000));
txt.text = secondsLeft;
if (secondsLeft <= 0) {
gameOver(false);
}
stage.update();
}
function gameOver(win) {
Ticker.setPaused(true);
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play Again?</a>";
for (var i = 0; i < textTiles.length; i++) {
textTiles[i].onPress = null;
}
if (win === true) {
matchesFoundText.text = "You win!"
} else {
txt.text = secondsLeft + "... Game Over";
}
}
function replay() {
init();
}
</script>
</head>
<body onload="init()">
<header id="header">
<p id="replay"></p>
</header>
<canvas id="myCanvas" width="960" height="400"></canvas>
</body>
</html>
I give you 1 option for this, though you can do it also in other ways,
we declare global variables which are
var prev_time;
var best_time;
add that to your global variable declarations, then give it a value when you compute the time i guess we had that here:
function tick() {
secondsLeft = Math.floor((timeAllowable - Ticker.getTime() / 1000));
txt.text = secondsLeft;
if (secondsLeft <= 0) {
gameOver(false);
}
//compute here the total time player had and give it to prev_time
//var totalTimePlayerplayed = some computation here which should be allowed time per player - secondsLeft
prev_time = totalTimePlayerplayed;
stage.update();
}
function gameOver(win) {
Ticker.setPaused(true);
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play A
gain?</a>";
for (var i = 0; i < textTiles.length; i++) {
textTiles[i].onPress = null;
}
if (win === true) {
matchesFoundText.text = "You win!"
if(best_time !== NULL){
best_time = prev_time;
//WE assume that the last player is the best scorer
}
} else {
//if there is already existing top scorer
if(best_time < prev_time){
best_time = prev_time
}
txt.text = secondsLeft + "... Game Over";
}
}
then give that time of the first player to the prev_time. Upon Game over or Game ended we validate here if the best_time has a value if not, then we give it a value of the value of prev_time, else we validate if the score is higher that the previous best_time and here's a tip, now when the player would trigger the "Play again" which I can't seem find right now, you get the variable best_time's value and display it as the score to beat. Hope you get the concept and somehow it helped you accomplished what you're intended to do, but like i said before you also have some other options to do this.

Displaying buttons and printing a variable in javascript

I'm fairly new to JavaScript, but I have some experience in other languages. I've been working on making my own small project, and I'm still figuring out how some things work. I have two problems that I need help solving. The first one, is that I have a button that should appear after you get 100 points, and click the button. This is at the if (buyupgrade == 1) and the following parts of that. I want the button to appear after the conditions are met (buy the first upgrade after getting 100 points). I also want to be printing the text part of a button, but in the text, I need it to display a variable, So my button text will display some words and a variable. Thanks for the help!
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost 200</button>
<script>
var points = 98;
var pointMulti = 1;
var buyupgrade = 0;
var currentpoints = setInterval(pointupdate, 1000);
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + points + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
}
}
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti + "!";
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
}
}
if (buyupgrade == 1) {
document.getElementById("firstbuild");
firstbuild.style.display = "inline";
function build1() {
}
}
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + points + " points!";
}
</script>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
</body>
</html>
Your code that is supposed to make the third button visible is by itself outside any function. This seems like a typo:
if (buyupgrade == 1) {
document.getElementById("firstbuild");
firstbuild.style.display = "inline";
function build1() {
}
This only gets called the first time through the program when buyupgrade == 0
I think you meant for this to be inside the function:
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti + "!";
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
}
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
// add some text to the button
firstbuild.innerText = "buyupgrade: " + buyupgrade
}
}
Also, there's a typo:
document.getElementById("firstbuild");
should probably be:
var firstbuild = document.getElementById("firstbuild");

Error code JS with my function Game Over

I am making a game and I encounter a problem.
When I click on the hammer, the game must show a "Game Over".
However, when a hammer appear, that I don't click on the case where it was and later I click again on this same case, "Game Over" is still displayed.
var temps = 50;
var compte = temps;
var pointCounter=0;
//ONLY SELECTOR FOR DOM
var $contener = document.querySelector(".contener");
var $bestscore = document.querySelector("#bestscore");
var $compt = document.querySelector("#compt");
var $score = document.querySelector("#score");
var $button = document.querySelector('.resetBouton');
for( var i = 0; i <= 8; i++){
$contener.innerHTML += "<div class='case case" + i + "'></div>";
}
if(localStorage.getItem('score')){
$bestscore.textContent = 'Score : ' + localStorage.getItem('score');
}
else{
localStorage.setItem('score', 0);
$bestscore.textContent = 'Score : 0';
}
function decompte(){
if(compte <= 1) {
pluriel = "";
} else {
pluriel = "s";
}
$compt.innerHTML = compte + " seconde" + pluriel;
if(!compte || compte < 0) {
reset();
if(pointCounter > localStorage.getItem('score')){
localStorage.setItem('score', pointCounter);
$bestscore.textContent = 'Score : ' + pointCounter;
}
}
//decrease 1 point
compte--;
}
let timer = setInterval(decompte,1000);
let taupe = setInterval(randomPosition,1000);
//RANDOM POSITION
function randomPosition() {
var $cases = document.querySelectorAll('.case');
// cannot click 2 times
for (var i =0; i< $cases.length; i++){
$cases[i].removeEventListener('click', losePoints);
$cases[i].removeEventListener('click', earnPoints);
$cases[i].innerHTML = '';
}
var x = Math.floor(Math.random() * 9);
var min = 1;
var max = 7;
var nbrRandom = min + Math.floor(Math.random() * max);
if (nbrRandom === 2) {
$cases[x].innerHTML = '<div id="darktaupe"><img src="images/darkTaupiqueur.png" alt="darktopiqueur"/></div>';
$cases[x].addEventListener('click', losePoints);
} else if(nbrRandom ===6) {
$cases[x].innerHTML = '<div id="darktaupe"><img src="images/Marteau_TFH.png" alt="marteau"/></div>';
$cases[x].addEventListener('click', gameOver);
}
else
{
$cases[x].innerHTML = '<div id="taupe"><img src="images/Taupiqueur.png" alt="t opiqueur"/></div>';
$cases[x].addEventListener('click', earnPoints);
}
}
function losePoints(event){
/* JouerSon(); */
pointCounter -=10;
if(pointCounter <0){
pointCounter =0
}
$score.textContent = pointCounter;
event.currentTarget.removeEventListener('click', losePoints);
}
function earnPoints(event){
/* JouerSon(); */
pointCounter ++;
$score.textContent = pointCounter;
event.currentTarget.removeEventListener('click', earnPoints);
}
/*function JouerSon() {
var sound = document.getElementById("beep");
sound.play();
} */
// RESET BUTTON
function reset(){
$button.classList.remove("reset");
$button.addEventListener('click', resetGame);
clearInterval(timer);
clearInterval(taupe);
}
function resetGame(){
pointCounter = 0;
compte = temps;
$score.textContent = pointCounter;
timer = setInterval(decompte,1000);
taupe = setInterval(randomPosition,1000);
$button.removeEventListener('click', resetGame);
$button.classList.add('reset');
}
function gameOver(event){
event.currentTarget.removeEventListener('click', gameOver);
alert("GAME OVER");
reset();
}
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles/style.css">
<meta charset="utf-8"/>
</head>
<body>
<span id="compt"></span>
<span id="score">Score : </span> <span id="bestscore"></span>
<div class="contener"></div>
<button class="resetBouton reset"> reset </button>
<button class="resetBouton jouer"> Jouer </button>
<audio id="beep" src="test1.wav">
<script type='text/javascript' src="script/main.js"></script>
</body>
</html>
From a quick examination of your game, it looks like you are calling randomPosition every second, selecting a random element and then attaching one of three event handlers to it.
It looks like you are removing your losePoints and earnPoints handlers on each call to randomPosition, but never removing gameOver.

Categories