I am during writing game. When condition (playerlife < 1) is meet, game should stop. Whole game is in singlePlayer function. The problem is, I don't know how to end this function. Simple placing condition inside singlePlayer function doesn't work because it is checked only once during starting a game.
if (playerlife < 1) {
return;
}
I also tried to put this condition in interval and check if condition is meet continously but I doesn't work and anyway it doesn't looks like a good idea.
Below is part of code where after moving player there are checked some conditions. Game is similar to old school "Frogger". When player jump in to the water then he lost 1 life. After loosing 3 lives game should be over.
$(function() {
function singlePlayer() {
checkPosition(x, y) {
for (var i = 0; i < raftsTab.length; i++) {
if (x == raftsTab[i].PosX && y == raftsTab[i].PosY) {
let thisRaft = raftsTab[i];
console.log(x, y);
console.log(thisRaft);
clearInterval(MoveToPlayer);
movePlayer(thisRaft);
return;
}
}
for (var i = 0; i < raftsTab.length; i++) {
if (x !== raftsTab[i].PosX && y !== raftsTab[i].PosY && y !== 0 && y !== 5 && y !== 10) {
player1.lifes = player1.lifes - 1;
//player dead after loosing 3 lives - it would be perfect if game could be ended from here
$('.lifes').text("Player lifes: " + player1.lifes);
for (var i = 0; i < trophiesTab.length; i++) {
if (player1.trophie - 1 == i) {
trophiesTab[i].show();
player1.trophie = -1;
}
}
player1.PosX = 5;
player1.PosY = 10;
clearInterval(MoveToPlayer);
changePosition();
return;
}
}
for (var i = 0; i < trophiesTab.length; i++) {
if (x == trophiesTab[i].PosX && y == trophiesTab[i].PosY && player1.trophie == -1) {
trophiesTab[i].hide();
}
}
if (x == 5 && y == 0 && player1.trophie !== -1) {
tresure1 = tresure1 + player1.trophie;
player1.items = player1.items + 1;
$('.items').text("Gathered items: " + player1.items + "/3");
player1.trophie = -1;
console.log(tresure1);
}
clearInterval(MoveToPlayer);
}
}
});
Related
When running this code I currently getting the error "TypeError: Invalid value for y-coordinate. Make sure you are passing finite numbers to setPosition(x, y)." all of my functions do work are are declared properly. When I use a println and print out letYPos it prints out "NaN" but when I call the function again it prints out the correct value. Does anyone know how I can fix this or if there even is a way to fix this?
var count = 0;
var letYPos = 0;
var y = 3;
function testing()
{
var letXPos = 25;
letYPos += 75;
if (count == 6)
{
println("You have ran out of guesses, the correct anwser was: " + secretWord);
return;
}
var input = readLine("Enter your word: ");
if (input == null)
{
println("You have to enter a word! ");
return;
}
if (input.length != 5)
{
println("That is not a five letter word, please try again.");
return;
}
var x = 3;
for (var i = 0; i < input.length; i++)
{
if (input.includes(secretWord.charAt(i)))
{
var index = input.indexOf(secretWord.charAt(i));
}
if (index == 0) { yellow(3, y ) }
if (index == 1) { yellow(83, y ) }
if (index == 2) { yellow(163, y) }
if (index == 3) { yellow(243, y) }
if (index == 4) { yellow(323, y) } index = null;
}
for (var i = 0; i < input.length; i++)
{
if (input.charAt(i) == secretWord.charAt(i))
{
green(x, y);
}
x += 80;
}
y += 80;
for (var i = 0; i < input.length; i++)
{
for (var a = 0; a <= 5; a++)
{
var txt = new Text(input.charAt(a), font);
txt.setPosition(letXPos, letYPos);
add(txt);
letXPos += 80;
}
}
if (input == secretWord)
{
println("That's Correct, Congratulations!");
return;
}
count++;
setTimeout(testing, 100);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Code bellow works fine, though as u can see, everything is hand wrote and if i want to push something to that arrays i will have to change whole code.
working example:
for (var s = 0; s < myButtons.length; s++) {
if (
(myButtons[s].className == "1" && colorIndex[0] > 1)
||
(myButtons[s].className == "2" && colorIndex[1] > 1)
||
(myButtons[s].className == "3" && colorIndex[2] > 1)
||
(myButtons[s].className == "4" && colorIndex[3] > 1)
||
(myButtons[s].className == "5" && colorIndex[4] > 1)
||
(myButtons[s].className == "6" && colorIndex[5] > 1)
) {continue;}
alert("things need to be done")
}
the best solution came to my mind(not working one):
for (var s = 0; s < myButtons.length; s++) {
for (var i = 0; i < colorIndex.length; i++) {
if ((myButtons[s].className == (i + 1) && colorIndex[i] > 1)) {
continue;
}
alert("things need to be done")
}
}
So what i want is: to check if all elements of array myButtons.classname==variable from cycle && colorIndex[variable from cycle]>1 OR same thing again but on next step
working code for the first algorithm
const colorIndex = []
colorIndex[0] = 201
colorIndex[1] = 30002
colorIndex[19] = -25
colorIndex[3] = 89
colorIndex[-7] = 89
colorIndex[-9] = -26
const myButtons = [...document.querySelectorAll("button")]
for (var s = 0; s < myButtons.length; s++)
{
if ( (myButtons[s].className == "1" && colorIndex[0] > 1)
|| (myButtons[s].className == "2" && colorIndex[1] > 1)
|| (myButtons[s].className == "3" && colorIndex[2] > 1)
|| (myButtons[s].className == "4" && colorIndex[3] > 1)
|| (myButtons[s].className == "5" && colorIndex[4] > 1)
|| (myButtons[s].className == "6" && colorIndex[5] > 1)
)
{ continue }
alert("things need to be done")
}
console.log('test ending')
<button class="1">1</button>
<button class="2">2</button>
<button class="4">3</button>
<button class="4">4</button>
<button class="4">5</button>
<button class="4">6</button>
<button class="4">7</button>
<button class="2">8</button>
<button class="4">9</button>
Here a pretty short and less hard coded version of the original code
var myButtons = document.querySelectorAll("button");
var colorIndex = [0, 1, 2, 0, 2, 1];
for (var index = 0; index < myButtons.length; index++) {
if (myButtons[index].className == String(index + 1)
&& colorIndex[myButtons[index].className - 1] > 1) continue;
console.log("Button at index '" + index + "' needs to get fixed");
}
<button class="1">1</button>
<button class="2">2</button>
<button class="3">3</button>
<button class="4">4</button>
<button class="5">5</button>
<button class="6">6</button>
Full code attempt:
// Create Buttons Start
var buttonDom = document.getElementById("a1");
var buttonList = [],
buttonCount = 12;
while (buttonList.length < buttonCount) {
var newInput = document.createElement("input");
newInput.type = "button";
buttonList.push(newInput);
buttonDom.appendChild(newInput);
}
var randomList1 = [];
while (randomList1.length < buttonCount / 2) {
var random = Math.floor(Math.random() * buttonCount / 2) + 1;
if (randomList1.indexOf(random) === -1) randomList1.push(random);
}
var randomList2 = [];
while (randomList2.length < buttonCount / 2) {
var random = Math.floor(Math.random() * buttonCount / 2) + 1;
if (randomList2.indexOf(random) === -1) randomList2.push(random);
}
randomList1.forEach((random, index) => buttonList[index].setAttribute("class", random));
randomList2.forEach((random, index) => buttonList[index + buttonCount / 2].setAttribute("class", random));
// Game Start
var myButtons = document.querySelectorAll("input[type='button']");
var click = 1;
var colorIndex = "0".repeat(6).split("").map(Number);
var color = ["red", "blue", "green", "black", "gold", "grey"];
myButtons.forEach(button => button.addEventListener("click", game));
function clickTrun() {
click = !click | 0;
}
function win() {
if (colorIndex.every(i => i == 2)) {
alert("YOU WON mdfker!");
location.reload();
}
}
function resetColorIndex() {
if (click === 1) {
colorIndex = colorIndex.map(function(colorValue) {
return colorValue < 2 ? 0 : colorValue;
});
}
}
function mainGameRules() {
setTimeout(function() {
resetColorIndex();
if (click === 1) {
myButtons.forEach(function(button) {
if (colorIndex[button.className - 1] > 1) return;
button.setAttribute("style", "background-color: none;");
button.disabled = false;
});
}
}, 700);
}
function game() {
this.disabled = true;
var index = this.className - 1;
if (index in colorIndex) {
this.setAttribute("style", "background-color:" + color[index]);
colorIndex[index]++;
mainGameRules();
clickTrun();
}
win();
}
<div id="a1">
</div>
You just need to formulate what you want to do and express it in code. Without sticking to concrete index, try to figure out how any possible index corresponds to particular color. Looking at your example you want to take className for every button, subtract 1 and take color from colorIndex and do something if that color is less than or equal to 1
for (let i = 0; i < myButtons.length; i++) {
// className for current button
const className = myButtons[i].className
// parse it into number
const num = Number(className)
// if number is valid, take element from colorIndex at number-1 position
// and see if that's not bigger than 1
if (num && colorIndex[num - 1] <= 1) {
console.log('things need to be done for index ' + i)
}
}
but my suggestion would be to reconsider your existing setup with myButtons and colorIndex into something more sophisticated
setInterval "MoveToPlayer" should start after meeting first condition from "checkPosition" method and it should run(this works). After meeting the same condition again it should stop and start again with different parameter. I through that simple placing clearInterval(MoveToPlayer) will do the job but it doesn't work.
Second issue is how to stop this interval for example from "checkPosition" method?
class player {
constructor(name, PosY) {
this.name = name;
this.PosX = 5;
this.PosY = PosY;
this.object = $('.' + name);
this.speed = 0;
this.direction = "";
this.lifes = 3;
}
playerMove(thisRaft) {
var MoveToPlayer = setInterval(() => {
clearInterval(MoveToPlayer)
$('.player1').css('left', thisRaft.PosX * 50);
$('.player1').css('bottom', thisRaft.PosY * 50);
}, 1);
}
checkPosition(x, y) {
for (var i = 0; i < raftsTab.length; i++) {
if (x == raftsTab[i].PosX && y == raftsTab[i].PosY) {
let thisRaft = raftsTab[i];
this.playerMove(thisRaft);
return;
}
}
for (var i = 0; i < raftsTab.length; i++) {
if (x !== raftsTab[i].PosX && y !== raftsTab[i].PosY && y !== 0 && y !== 5 && y !== 10) {
console.log("Dead");
player1.PosX = 5;
player1.PosY = 0;
changePosition();
return;
}
}
}
}
Regarding your first issue you are clearing the interval immediately after it starts, so it won't continue.
In order to make the interval more dynamic you should have a function that returns an interval within checkPosition.
Wasn't able to understand how your game should actually work, but I am posting an alteration to your script where I modified PlayerMove and checkPosition in away that gives you a better control of the interval in question.
Hope it is clear and helpful for you
class player {
constructor(name, PosY) {
this.name = name;
this.PosX = 5;
this.PosY = PosY;
this.object = $('.' + name);
this.speed = 0;
this.direction = "";
this.lifes = 3;
}
playerMove(thisRaft) {
return setInterval(() => {
$('.player1').css('left', thisRaft.PosX * 50);
$('.player1').css('bottom', thisRaft.PosY * 50);
}, 1);
}
checkPosition(x, y) {
if (someCondition && this.currentPlayerMove) {
clearInterval(this.currentPlayerMove)
}
for (var i = 0; i < raftsTab.length; i++) {
if (x == raftsTab[i].PosX && y == raftsTab[i].PosY) {
let thisRaft = raftsTab[i];
this.currentPlayerMove = this.playerMove(thisRaft);
return;
}
}
for (var i = 0; i < raftsTab.length; i++) {
if (x !== raftsTab[i].PosX && y !== raftsTab[i].PosY && y !== 0 && y !== 5 && y !== 10) {
console.log("Dead");
player1.PosX = 5;
player1.PosY = 0;
changePosition();
return;
}
}
}
Just assign your handler at such scope, that would make it accessible to all functions that could clear it.
var handler;
function movePlayer(text){
clearInterval(handler); // stop execution before assigning new handler
handler = setInterval(()=>{
/* do your stuff */
console.log(text);
}, 100)
}
movePlayer("I'm moving")
setTimeout(()=>{
clearInterval(handler)
}, 500)
setTimeout(()=>{
movePlayer("I'm moving again")
}, 1500)
setTimeout(()=>{
clearInterval(handler)
}, 2000)
I am learning JavaScript by programming my first game (a simple laser-mirror-type game). The game operates in a grid and I want to determine if a cell holds an obstacle or not. So I call this function:
function updateGrid () {
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
for (let o = 0; o < obstacles.length; o++) {
if (grid[i][j].x === obstacles[o].x && grid[i][j].y === obstacles[o].y) {
grid[i][j].obstacle = true;
} else if (grid[i][j].x != obstacles[o].x && grid[i][j].y != obstacles[o].y) {
//grid[i][j].obstacle = false;
}
}
for (let m = mirrors.length - 1; m >= 0; m--) {
if (grid[i][j].x + cellOffset.x== mirrors[m].x && grid[i][j].y + cellOffset.y == mirrors[m].y) {
grid[i][j].mirror = true;
} else {
grid[i][j].mirror = false;
}
}
if (grid[i][j].x + cellOffset.x == target.x && grid[i][j].y + cellOffset.y == target.y) {
grid[i][j].target = true;
} else {
grid[i][j].target = false;
}
if (grid[i][j].x == laserPen.x && grid[i][j].y + (rowH / 2) - (cellOffset.y / 4) == laserPen.y) {
grid[i][j].pen = true;
} else {
grid[i][j].pen = false;
}
}
}
}
However the if-statement that determines if the cell contains an obstacle, seems to not work.
This works (sets grid[ i ][ j ].obstacle to true):
for (let o = 0; o < obstacles.length; o++) {
if (grid[i][j].x === obstacles[o].x && grid[i][j].y === obstacles[o].y) {
grid[i][j].obstacle = true;
} else if (grid[i][j].x != obstacles[o].x && grid[i][j].y != obstacles[o].y) {
//grid[i][j].obstacle = false;
}
}
This does not (sets grid[ i ][ j ].obstacle to false):
for (let o = 0; o < obstacles.length; o++) {
if (grid[i][j].x === obstacles[o].x && grid[i][j].y === obstacles[o].y) {
grid[i][j].obstacle = true;
} else if (grid[i][j].x != obstacles[o].x && grid[i][j].y != obstacles[o].y) {
grid[i][j].obstacle = false;
}
}
I actually added the else-if just for safety, but it failed to work with a simple else-statement as well.
I am using the p5.js library and any insight into what is happening here would be greatly appreciated. Thanks!
Found the bug after some testing. I was iterating through all the obstacles on the same grid cell (i.e. test obstacles[0] for grid[2][2], test obstacles[1] for grid[2][2]). This meant that if the first obstacle in the array proved true, but the others proved false, the overall grid[2][2].obstacle would become false. Or to map it visually:
grid[2][1] ...
grid[2][2].obstacle = true!
grid[2][2].obstacle = false.
grid[2][2].obstacle = false.
grid[2][3] ...
Output:
grid[2][2].obstacle is false :(
I have a 2d array called 'map.curCellMap' storing 1's and 0's. I am using the function 'cells.getNeighbourCount' (below) to reference cells in this map.
Within the context of the 'cells.update' function (below) this is returning an undefined error. In firefox it reads 'TypeError: map.curCellMap[nextY] is undefined'. However, if I call 'cells.getNeighbourCount' with hardcoded values it does work.
What gives?
var cells = {
getNeighbourCount: function(x, y) {
/*
/* [y][x]
/* Start a top and move clockwise
*/
var neighbours = [[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1]],
count = 0;
for(i = 0; i < neighbours.length; i++) {
var curNeighbour = neighbours[i];
//Skip this iteration if neighbour is out of bounds
if((y + curNeighbour[0] < 0) || (y + curNeighbour[0] > ROWS) || (x + curNeighbour[1] < 0) || (x + curNeighbour[1] > COLS)) {
continue;
}
var nextY = y+curNeighbour[0],
nextX = x+curNeighbour[1];
if(map.curCellMap[nextY][nextX] == 1) {
count++;
}
}
return count;
},
update: function() {
for(y = 0; y < ROWS; y++) {
for(x = 0; x < COLS; x++) {
var numNeighbours = this.getNeighbourCount(x, y),
newCellState;
if(numNeighbours >= 2 && numNeighbours <= 3) {
newCellState = 1;
} else {
newCellState = 0;
}
map.nextCellMap[y][x] = newCellState;
}
}
map.curCellMap = map.nextCellMap;
}
}
var map = {
curCellMap: null,
nextCellMap: null,
//Map functions
init: function() {
this.curCellMap = this.generateRandomMap(0.05);
this.nextCellMap = this.curCellMap;
},
generateRandomMap: function(density) {
/*
/* Generates a random cell map
/* density = 0.00 -> No live cells, density = 1.00 -> All cells live
*/
var map = helpers.create2DArray(ROWS, COLS);
for(y = 0; y < ROWS; y++) {
for(x = 0; x < COLS; x++) {
var rand = helpers.getRandomNum(0, 1);
map[y][x] = (rand <= density) ? 1 : 0;
}
}
return map;
}
}
The problem was
if((y + curNeighbour[0] < 0) || (y + curNeighbour[0] > ROWS) || (x + curNeighbour[1] < 0) || (x + curNeighbour[1] > COLS)) {
Needed to read
if((y + curNeighbour[0] < 0) || (y + curNeighbour[0] > ROWS-1) || (x + curNeighbour[1] < 0) || (x + curNeighbour[1] > COLS-1)) {
OOPS!