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 :(
Related
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);
}
}
});
We encountered a problem with the minification provided by the NuGet package Microsoft.AspNet.Web.Optimization, as it seems to have problems with let. Somehow the minifier sets the name of the variables bookingDefaultIndex and i to the same name (i). This makes Firefox and IE 11 report a scope problem (Firefox reports SyntaxError: redeclaration of let i, IE 11 reports Let/Const redeclaration), because the variable was already defined. Without minification, the code works just fine in IE and FF. Chrome reports no problems with the minified code.
In the following code snippets, I marked the relevant lines with a comment that starts with // [SO-COMMENT], so you can search for that to see the problematic lines.
This is the unminified function that causes problems:
_handleDDLValuesByContext: function () {
if (this.options.isCreate) {
if (this.options.isChildCreation) {
//If we are creating a child ->
this.$ddlBookingType.val(this.options.data.BookingTypeID);
this.$ddlAllocationUnit.val(this.options.data.AllocationUnitID);
this.$ddlEffortAllocationUnit.val(this.options.data.AllocationUnitID);
if (this.options.data.ServiceCategoryID == null) {
this.$ddlServiceCategory.val('-1').trigger('change');
if (this.options.data.PricePerUnit != null) {
this.$structureRate.val(GetFormat(this.options.data.PricePerUnit));
}
} else {
this.$ddlServiceCategory.val(this.options.data.ServiceCategoryID).trigger('change');
}
//If we are creating a child, prefill his accounting type with the parent accounting type
if (this.options.data.AccountingTypeID == null) {
this.$ddlAccountingType.val('-1').trigger('change');
} else {
this.$ddlAccountingType.val(this.options.data.AccountingTypeID).trigger('change');
}
} else {
//If it's parent creation ->
let bookingTypes = this.options.structureSpecificData.BookingTypes;
let bookingDefaultID = null;
// [SO-COMMENT] the following variable is minified to 'i'
let bookingDefaultIndex = null;
for (let i = 0, len = bookingTypes.length; i < len; i++) {
if (bookingTypes[i].IsDefault) {
bookingDefaultID = bookingTypes[i].ID;
bookingDefaultIndex = i;
}
}
let allocationTypes = this.options.structureSpecificData.AllocationUnitTypes;
if (bookingDefaultID == null) {
//In case there's no default booking type id, we set the booking types, allocations and effort allocations to their first available value
this.$ddlBookingType.val(bookingTypes[0].ID);
this.$ddlAllocationUnit.val(allocationTypes[0].ID);
this.$ddlEffortAllocationUnit.val(allocationTypes[0].ID);
} else {
let allocationDefaultID = null;
this.$ddlBookingType.val(bookingDefaultID).trigger('change');
allocationTypes = [];
let bookings = this.options.structureSpecificData.BookingTypes;
let allocations = this.options.structureSpecificData.AllocationUnitTypes;
// [SO-COMMENT] this is the 'original' i
for (let i = 0, len = allocations.length; i < len; i++) {
if (allocations[i].BaseUnitID == bookings[bookingDefaultIndex].BaseUnitID) {
allocationTypes.push(allocations[i]);
}
}
for (let i = 0, len = allocationTypes.length; i < len; i++) {
if (allocationTypes[i].IsDefault) {
allocationDefaultID = allocationTypes[i].ID;
}
}
if (allocationDefaultID == null) {
this.$ddlAllocationUnit.val(allocationTypes[0].ID);
this.$ddlEffortAllocationUnit.val(allocationTypes[0].ID);
} else {
this.$ddlAllocationUnit.val(allocationDefaultID);
this.$ddlEffortAllocationUnit.val(allocationDefaultID);
}
}
this.$ddlServiceCategory.val('-1');
}
} else {
//If we are edditing ->
this.$ddlBookingType.val(this.options.data.BookingTypeID);
this.$ddlAllocationUnit.val(this.options.data.AllocationUnitID);
this.$ddlEffortAllocationUnit.val(this.options.data.AllocationUnitID);
if (this.options.data.IsParentElement) {
this.$ddlServiceCategory.val('-1').trigger('change');
//We have to check against a NaN type since the effort and the total cost can be of that type
//in case we have a structure hierarchy with an accounting type of fixed price and therefore no effort and cost
if (isNaN(this.options.structureTotalCost)) {
this.$structureTotalCost.val('');
} else {
this.$structureTotalCost.val(GetFormat(this.options.structureTotalCost));
}
if (isNaN(this.options.structureEffort)) {
this.$structureEffortUnits.val('');
} else {
this.$structureEffortUnits.val(GetFormat(this.options.structureEffort));
}
} else {
if (this.options.data.ServiceCategoryID == null) {
this.$ddlServiceCategory.val('-1').trigger('change');
if (this.options.data.PricePerUnit != null) {
this.$structureRate.val(GetFormat(this.options.data.PricePerUnit));
this._checkTotalCostCalculation();
}
} else {
if (this.options.data.PricePerUnit !== null) {
this.$structureRate.val(GetFormat(this.options.data.PricePerUnit));
this.$ddlServiceCategory.val(this.options.data.ServiceCategoryID);
this._checkTotalCostCalculation();
} else {
this.$ddlServiceCategory.val(this.options.data.ServiceCategoryID).trigger('change');
}
}
}
//Since we are editing we should prefill the accounting type with the accounting id and the fixed price too if it exists
//And not trigger anything
if (this.options.data.AccountingTypeID == null) {
this.$ddlAccountingType.val('-1').trigger('change');
} else {
this.$ddlAccountingType.val(this.options.data.AccountingTypeID).trigger('change');
}
if (isNaN(this.options.totalFixedPrice)) {
this.$fixedPrice.val('');
} else {
this.$fixedPrice.val(GetFormat(this.options.totalFixedPrice));
}
}
}
And this is the minified version:
_handleDDLValuesByContext: function() {
if (this.options.isCreate)
if (this.options.isChildCreation) this.$ddlBookingType.val(this.options.data.BookingTypeID), this.$ddlAllocationUnit.val(this.options.data.AllocationUnitID), this.$ddlEffortAllocationUnit.val(this.options.data.AllocationUnitID), this.options.data.ServiceCategoryID == null ? (this.$ddlServiceCategory.val("-1").trigger("change"), this.options.data.PricePerUnit != null && this.$structureRate.val(GetFormat(this.options.data.PricePerUnit))) : this.$ddlServiceCategory.val(this.options.data.ServiceCategoryID).trigger("change"), this.options.data.AccountingTypeID == null ? this.$ddlAccountingType.val("-1").trigger("change") : this.$ddlAccountingType.val(this.options.data.AccountingTypeID).trigger("change");
else {
let t = this.options.structureSpecificData.BookingTypes,
i = null, // [SO-COMMENT] this shouldn't be named i
r = null;
for (let n = 0, u = t.length; n < u; n++) t[n].IsDefault && (i = t[n].ID, r = n);
let n = this.options.structureSpecificData.AllocationUnitTypes;
if (i == null) this.$ddlBookingType.val(t[0].ID), this.$ddlAllocationUnit.val(n[0].ID), this.$ddlEffortAllocationUnit.val(n[0].ID);
else {
let t = null;
this.$ddlBookingType.val(i).trigger("change");
n = [];
let f = this.options.structureSpecificData.BookingTypes,
u = this.options.structureSpecificData.AllocationUnitTypes;
for (let t = 0, i = u.length; t < i; t++) u[t].BaseUnitID == f[r].BaseUnitID && n.push(u[t]);
// [SO-COMMENT] here there is a second i that causes the problem
for (let i = 0, r = n.length; i < r; i++) n[i].IsDefault && (t = n[i].ID);
t == null ? (this.$ddlAllocationUnit.val(n[0].ID), this.$ddlEffortAllocationUnit.val(n[0].ID)) : (this.$ddlAllocationUnit.val(t), this.$ddlEffortAllocationUnit.val(t))
}
this.$ddlServiceCategory.val("-1")
} else this.$ddlBookingType.val(this.options.data.BookingTypeID), this.$ddlAllocationUnit.val(this.options.data.AllocationUnitID), this.$ddlEffortAllocationUnit.val(this.options.data.AllocationUnitID), this.options.data.IsParentElement ? (this.$ddlServiceCategory.val("-1").trigger("change"), isNaN(this.options.structureTotalCost) ? this.$structureTotalCost.val("") : this.$structureTotalCost.val(GetFormat(this.options.structureTotalCost)), isNaN(this.options.structureEffort) ? this.$structureEffortUnits.val("") : this.$structureEffortUnits.val(GetFormat(this.options.structureEffort))) : this.options.data.ServiceCategoryID == null ? (this.$ddlServiceCategory.val("-1").trigger("change"), this.options.data.PricePerUnit != null && (this.$structureRate.val(GetFormat(this.options.data.PricePerUnit)), this._checkTotalCostCalculation())) : this.options.data.PricePerUnit !== null ? (this.$structureRate.val(GetFormat(this.options.data.PricePerUnit)), this.$ddlServiceCategory.val(this.options.data.ServiceCategoryID), this._checkTotalCostCalculation()) : this.$ddlServiceCategory.val(this.options.data.ServiceCategoryID).trigger("change"), this.options.data.AccountingTypeID == null ? this.$ddlAccountingType.val("-1").trigger("change") : this.$ddlAccountingType.val(this.options.data.AccountingTypeID).trigger("change"), isNaN(this.options.totalFixedPrice) ? this.$fixedPrice.val("") : this.$fixedPrice.val(GetFormat(this.options.totalFixedPrice))
}
My google searches for IIS minification scope problems didn't show any useful results. What could we try to investigate and fix this problem, other than not to use let?
Can anyone explain the meaning behind the "[0]" after the arguments list here?
let value = this.recurseMinimax(board, !player)[0];
function:
recurseMinimax(board: boolean[][], player: boolean): any {
this.numNodes++;
let winner = this.getWinner(board);
if (winner != null) {
switch (winner) {
case 1:
return [1, board];
case 0:
return [-1, board];
case -1:
return [0, board];
}
} else {
let nextVal = null;
let nextBoard = null;
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (board[i][j] == null) {
board[i][j] = player;
let value = this.recurseMinimax(board, !player)[0];
if ((player && (nextVal == null || value > nextVal)) || (!player && (nextVal == null || value < nextVal))) {
nextBoard = board.map(function (arr) {
return arr.slice();
});
nextVal = value;
}
board[i][j] = null;
}
}
}
return [nextVal, nextBoard];
}
}
And the "[1]" here:
return this.recurseMinimax(board, true)[1];
function:
minimaxMove(board: boolean[][]): any {
this.numNodes = 0;
return this.recurseMinimax(board, true)[1];
}
It Means the index of the Array (that is returning from your functions) are you accessing ... be carefully to do this without do a check maybe before, for example:
minimaxMove(board: boolean[][]): any {
this.numNodes = 0;
return this.recurseMinimax(board, true) && this.recurseMinimax(board, true).lenght>=1 ? this.recurseMinimax(board, true)[1] : {} ;
}
Trying to check possible combos in this sort of array:
[ ["X","X","X"], ["","",""], ["","",""] ]
Combos include:
tic tac toe logic
So, these are true:
[ ["X","",""], ["","X",""], ["","","X"] ]
[ ["","","X"], ["","X",""], ["X","",""] ]
[ ["","X",""], ["","X",""], ["","X",""] ]
So far, I have it working as long as my array[0][0] is the one of the selected choices, but I feel I'm moving towards a stack of code.
function testWin(){
var cs=b.length, ph=0, pv=0, pd=0;
for(var i=0;i<cs;i++){
if(b[0][i]==="X"){ ph++; }
if(b[i][0]==="X"){ pv++; }
if(b[i][i]==="X"){ pd++; }
}
if(ph===cs || pv===cs || pd===cs){ alert("YOU WIN!"); }
}
Fiddle here: http://jsfiddle.net/z4XLj/
Been trying another for loop to no success to identify 0
Tried a while loop, but it crashed and I don't think that is the most effective anyway.
Need to find if...
ANY array[i][this] contains nothing but X
ANY array[this][i] contains nothing but X
I now this looks like black magic, but here you have:
function testWin(){
var cs = b.length, I = [], J = [], d = [0, 0];
for(var i=0; i<cs; i++){
for(var j=0; j<cs; j++){
if(b[i][j] != 'X') continue;
I[i] = (I[i] || 0) + 1;
J[j] = (J[j] || 0) + 1;
if(i == j) d[0]++; //Diagonal \
if(i == cs-j-1) d[1]++; //Diagonal /
}
}
if(d.concat(I).concat(J).indexOf(cs) >=0) alert("You win");
}
jsfiddle: http://jsfiddle.net/edgarinvillegas/z4XLj/3/
It considers any horizontal, vertical or diagonal victory for board of any size
:O It works! :)
Cheers, from La Paz, Bolivia
function testWin() {
var xCount;
var rowsCount = b.length;
// First check rows
for (var row = 0; row < rowsCount; row++) {
xCount = 0;
colsCount = b[row].length;
for (var col = 0; col < colsCount; col++) {
if (b[row][col] == "X") {
xCount++;
} else {
break;
}
}
if (xCount == colsCount) {
alert ("YOU WIN!");
return true;
}
}
// Now check columns -- just invert the above nested loops
colsCount = b[0].length;
for (var col = 0; col < colsCount; col++) {
xCount = 0;
for (var row = 0; row < rowsCount; row++) {
if (b[row][col] == "X") {
xCount++;
} else {
break;
}
}
if (xCount == rowsCount) {
alert ("YOU WIN!");
return true;
}
}
// Check diagonals
if (b[1][1] == "X" &&
((b[0][0] == "X" && b[2][2] == "X") || (b[0][2] == "X" && b[2][0] == "X"))) {
alert ("YOU WIN!");
return true;
}
return false;
}
I'm creating a simple tic-tac-toe game and I have a boolean called winAlert that if it is true it should alert the player that they have won. This works correctly for the most part, but there is one instance where it does not. If the game is won and all of the cells are filled, the console logs that winAlert's value is false, but it still alerts the player that they have won, as if it were true. Could someone look over this code and see why this is behaving in this way? http://jsfiddle.net/Z5c9P/3/
This function is where I think the problem lies, but I don't know for sure.
var determineWin = function (pMoves) {
for (var i = 0; i < winConditions.length; i++) {
if (winConditions[i].length > pMoves.length) {
continue;
}
for (var j = 0; j < winConditions[i].length; j++) {
winAlert = false;
for (var k = 0; k < pMoves.length; k++) {
if (pMoves[k] === winConditions[i][j]) {
winAlert = true;
break;
}
}
if (!winAlert) break;
}
if (winAlert) {
alert(currentPlayer + " wins!");
break;
}
}
};
Here's the code that calls this function:
$('td').one('click', function () {
turnCount += 1;
setCurrentPlayer();
$(this).text(currentPlayer);
cellTracker = $(this).attr('id');
storeMoves();
determineWin(xMoves);
determineWin(oMoves);
if(turnCount === 9 && winAlert === false) {
alert("Tie game!");
}
console.log(turnCount, xMoves, oMoves, winAlert);
});
This is happening because your code does the following:
storeMoves();
determineWin(xMoves);
determineWin(oMoves);
if(turnCount === 9 && winAlert === false) {
alert("Tie game!");
}
console.log(turnCount, xMoves, oMoves, winAlert);
So if X ever wins the game, determineWin(xMoves) will set the variable to true, and determinWin(oMoves) will set it back to false, all before the console.log()
One way to solve this would be to only check for a win for the current player's moves:
storeMoves();
determineWin(currentPlayer == 'X' ? xMoves : yMoves);
if(turnCount === 9 && winAlert === false) {
alert("Tie game!");
}
console.log(turnCount, xMoves, oMoves, winAlert);
You have called determineWin on each player. so if x wins, determineWin(oMoves); will make winAlert false. Is this the problem?
Maybe you should create a new determineWin which only called once to determine who is the winner.
this code will just skip another user(so winAlert is still true) when his cell is less than 3, so this problem doesn't need fill all cells but just each player has more than 3 cells.
if (winConditions[i].length > pMoves.length) {
continue;
}
i change a little your code Fiddle
var determineWin = function (pMoves) {
for (var i = 0; i < winConditions.length; i++) {
if (winConditions[i].length > pMoves.length) {
continue;
}
winAlert = false;
matches = 0;
for (var j = 0; j < winConditions[i].length; j++) {
for (var k = 0; k < pMoves.length; k++) {
if (pMoves[k] === winConditions[i][j]) {
matches++;
}
}
}
if (matches == 3) return true;
}
return false;
};
and then
$('td').one('click', function () {
turnCount += 1;
setCurrentPlayer();
$(this).text(currentPlayer);
cellTracker = $(this).attr('id');
storeMoves();
if (determineWin(xMoves)){ // this is changed
alert("X Win")
return;
};
if (determineWin(oMoves)){
alert("O Win")
return;
};
if(turnCount === 9 && winAlert === false) {
alert("Tie game!");
}
console.log(turnCount, xMoves, oMoves, winAlert);
});
** Updated to clarify