Related
I'm writing an algorithm to solve a sudoku puzzle and I'm getting some weird behavior. My first draft below did not give me an error, but it was modifying the array. Then I realized (because I am new to JavaScript) that I have to put let before the var in the for loop, so I changed it.
The weird behavior is that when I change it to let row and let col in the for loop it no longer modifies the puzzle param array. I do not understand how adding the let word to the for loop changes this?
test = [
[8, 0, 6, 0, 1, 0, 0, 0, 0],
[0, 0, 3, 0, 6, 4, 0, 9, 0],
[9, 0, 0, 0, 0, 0, 8, 1, 6],
[0, 8, 0, 3, 9, 6, 0, 0, 0],
[7, 0, 2, 0, 4, 0, 3, 0, 9],
[0, 0, 0, 5, 7, 2, 0, 8, 0],
[5, 2, 1, 0, 0, 0, 0, 0, 4],
[0, 3, 0, 7, 5, 0, 2, 0, 0],
[0, 0, 0, 0, 2, 0, 1, 0, 5]
]
let result = solve(test)
console.log(result)
printPuzzle(test)
function solve(puzzle) {
for (row = 0; row < 9; row++) {
for (col = 0; col < 9; col++) {
if (puzzle[row][col] === 0) {
for (number = 1; number < 9; number++) {
if (isValidPlacement(puzzle, number, row, col)) {
puzzle[row][col] = number
if (solve(puzzle)) {
return true
} else {
puzzle[row][col] = 0
}
}
}
return false
}
}
}
return true
}
:) I'm creating a maze using JS and P5, with a two dimensional array filled with numbers 0-8. 0 are empty spots, 1 are walls, 2 is the character you walk with, 3 is the exit and 4-8 are items that randomly spawn. In order to exit the maze (through 3, which is set on a fixed spot), all items need to be collected (if you walk over an item, the value of this spot changes back to 0), so every value in the array should be below 4 in order to exit. Now I need a way to check if this is the case.
I tried it with every() but I guess this only works for regular arrays. I suppose I need a for loop but I don't know this should look. So that's where I need help!
My maze consists of 18 rows and columns, like so (but then 15 more rows)
let maze = [
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,2,0,0,0,0,1,0,1,0,0,0,0,1,0,0,1,0,1,0,0,0,3],
[1,1,1,1,1,0,1,0,0,0,1,1,0,0,0,0,1,0,1,0,1,0,1]
]
The items spawn randomly, this already works. Now I tried checking if every value is <= 3, with the every, like so
function checkBoard(mazenumbers){
return mazenumbers <= 3;
}
function alertMazenumbers() {
alert(maze.every(checkBoard));
}
And want this to display through an alert, once you walk into the exit location, like this
else if(direction === 'right') {
if(maze[playerPos.y][playerPos.x + 1] == 3) {
alertMazenumbers();
}
I want to get an alert with true if every value is <= 3, and false if not.
Currently, with this every(), I do get the alert but it only returns false, even when all items are cleared and it should return true.
You are on the right track using every!
The maze is an array of arrays (as Denys mentioned in his comment), so you have to use every twice, like so:
function canExitMaze(maze) {
return maze.every(row => row.every(cell => cell <= 3))
}
If you don't recognize the arrow function syntax (=>) this article explains it.
Hope this helps!
You can check if every point in the maze is <=3 by doing this
const isTrue = num => num <= 3; // is a single cell true
const isRowTrue = row => row.every(isTrue); // are all cells in a row true
const isMazeTrue = rows => rows.every(isTrue); // are all cells in all rows true
const maze = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 2, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 3],
[1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1]
];
console.log(isMazeTrue(maze));
Method 1: Check if every array only contains numbers that are <= 3
let maze = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 2, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 3],
[1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1]
];
function testMaze(maze) {
return maze.every(row => row.every(itemIsValid));
}
function itemIsValid(item) {
return item <= 3;
}
console.log(testMaze(maze));
maze[2][4] = 4;
console.log(testMaze(maze));
Method 2: Merge the arrays and search the numbers
var maze = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 2, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 3],
[1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1]
];
function testMaze(maze) {
return [].concat(...maze).every(itemIsValid);
}
function itemIsValid(item) {
return item <= 3;
}
console.log(testMaze(maze));
maze[2][4] = 4;
console.log(testMaze(maze));
Method 3: Convert the maze to a string and use regex
var maze = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 2, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 3],
[1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1]
];
function testMaze(maze) {
//or maze.toString().match(/\d+/g).every(x => itemIsValid(+x));
return !/[4-8]/g.test(`${maze}`);
}
function itemIsValid(item) {
return item <= 3;
}
console.log(testMaze(maze));
maze[2][4] = 4;
console.log(testMaze(maze));
I have the following array:
arr = [
[ 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 1, 0, 0, 1, 1, 0 ],
[ 1, 0, 0, 0, 1, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 1, 0, 1, 0, 0, 2 ],
[ 1, 0, 0, 1, 0, 2, 4 ],
[ 0, 0, 0, 0, 2, 4, 4 ],
[ 0, 0, 0, 0, 4, 4, 0 ],
[ 1, 1, 1, 0, 0, 0, 0 ],
[ 1, 1, 0, 2, 0, 0, 2 ],
[ 1, 0, 0, 4, 0, 2, 0 ],
[ 0, 0, 0, 4, 2, 0, 0 ],
[ 0, 0, 2, 0, 0, 0, 1 ],
[ 0, 2, 4, 0, 0, 1, 2 ],
[ 2, 4, 4, 2, 1, 2, 4 ],
[ 4, 4, 0, 0, 2, 4, 0 ]
]
Currently, I'm getting the max array sum in arr i.e 19 like this
function getMaxSum(arr) {
return arr.map(e => e.reduce((a, b) => a + b, 0)).sort((a,b) => a - b)[arr.length - 1];
}
I need to know is there any better way to achieve this?
I'm using array length of the original array to get the last element of resulting array because in this case, length of original array and resulting array is same. If the scenario is different then how can I use the length of the resulting array here:
return arr.map(e => e.reduce((a, b) => a + b, 0)).sort((a,b) => a - b)[HERE - 1];
Not a huge improvement, but it seems a little more literal to spread the values into Math.max
const data = [
[ 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 1, 0, 0, 1, 1, 0 ],
[ 1, 0, 0, 0, 1, 0, 0 ],
[ 0, 0, 0, 0, 0, 0, 0 ],
[ 0, 1, 0, 1, 0, 0, 2 ],
[ 1, 0, 0, 1, 0, 2, 4 ],
[ 0, 0, 0, 0, 2, 4, 4 ],
[ 0, 0, 0, 0, 4, 4, 0 ],
[ 1, 1, 1, 0, 0, 0, 0 ],
[ 1, 1, 0, 2, 0, 0, 2 ],
[ 1, 0, 0, 4, 0, 2, 0 ],
[ 0, 0, 0, 4, 2, 0, 0 ],
[ 0, 0, 2, 0, 0, 0, 1 ],
[ 0, 2, 4, 0, 0, 1, 2 ],
[ 2, 4, 4, 2, 1, 2, 4 ],
[ 4, 4, 0, 0, 2, 4, 0 ]
]
function getMaxSum(arr) {
return Math.max(...arr.map(e => e.reduce((a, b) => a + b, 0)))
}
console.log(getMaxSum(data))
As #Rajesh points out, Math.max is faster that a sort:
const numbers = Array(10000).fill().map((x,i)=>i);
const max = numbersIn => Math.max(...numbersIn);
const getMaxViaSort = numbersIn => numbersIn
.sort((a, b) => a > b ? -1 : 1)[0]
console.time('max');
max(numbers);
console.timeEnd('max');
console.time('max via sort');
getMaxViaSort(numbers);
console.timeEnd('max via sort');
The optimal strategy should be one where we need the least interaction with the arrays.
In my method i test the array products individually and compare that with a variable inside my loop. In this way i don't need to run a new implied loop to have Math.max check all my entries again, netting a speed boost.
This also saves on memory management as i don't need to map and return a new array of results for Math.max.
At the end of the loop i simply return the variable.
var data = [
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 0, 0, 1, 1, 0],
[1, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 2],
[1, 0, 0, 1, 0, 2, 4],
[0, 0, 0, 0, 2, 4, 4],
[0, 0, 0, 0, 4, 4, 0],
[1, 1, 1, 0, 0, 0, 0],
[1, 1, 0, 2, 0, 0, 2],
[1, 0, 0, 4, 0, 2, 0],
[0, 0, 0, 4, 2, 0, 0],
[0, 0, 2, 0, 0, 0, 1],
[0, 2, 4, 0, 0, 1, 2],
[2, 4, 4, 2, 1, 2, 4],
[4, 4, 0, 0, 2, 4, 0]
];
function getMaxSum1(arr) {
//The original method
return arr.map(function (e) { return e.reduce(function (a, b) { return a + b; }, 0); }).sort(function (a, b) { return a - b; })[arr.length - 1];
}
function getMaxSum2(arr) {
//From https://stackoverflow.com/a/51704254/5242739
return Math.max.apply(Math, arr.map(function (e) { return e.reduce(function (a, b) { return a + b; }, 0); }));
}
function sumArray(arr) {
var val = 0;
for (var index = 0; index < arr.length; index++) {
val += val;
}
return val;
}
function getMaxSum3(arr) {
//My method
var max;
for (var i = 0; i < arr.length; i++) {
var val = sumArray(arr[i]);
if (max === void 0 || val > max) {
max = val;
}
}
return max;
}
//TEST
//parameters
var runs = 10;
var tests = 100000;
//output area
var out = document.body.appendChild(document.createElement("pre"));
//test functions
function simulate1() {
var t = tests;
var dt = Date.now();
while (t--) {
getMaxSum1(data);
}
out.textContent += 'getMaxSum1 took: ' + (Date.now() - dt) + "ms\n";
requestAnimationFrame(simulate2);
}
function simulate2() {
var t = tests;
var dt = Date.now();
while (t--) {
getMaxSum2(data);
}
out.textContent += 'getMaxSum2 took: ' + (Date.now() - dt) + "ms\n";
requestAnimationFrame(simulate3);
}
function simulate3() {
var t = tests;
var dt = Date.now();
while (t--) {
getMaxSum3(data);
}
out.textContent += 'getMaxSum3 took: ' + (Date.now() - dt) + "ms\n\n";
if (runs--) {
requestAnimationFrame(simulate1);
}
}
//start
simulate1();
pre {
max-height: 200px;
overflow-y: scroll;
background-color: #eee;
}
I included OliverRadini's answer to compare the relative speed boosts.
I am following the course nand2tetris and doing the exercises but not with there software. Instead I'm trying todo everything in javascript. The purpose is to build a nand gate and from that you create all your chips/gates.
I wrote for every gate unit tests and they pass but for my 16 bit adder they fail and I don't really know why.
function Adder() {
this.halfAdder = function(a, b) {
var gate = new Gate();
var sum = gate.XOR(a, b);
var carry = gate.AND(a, b);
return [sum, carry];
};
this.fullAdder = function(a, b, c) {
var gate = new Gate();
var out1 = this.halfAdder(a, b);
var out2 = this.halfAdder(c, out1[0]);
var result = gate.OR(out1[1], out2[1])
return [out2[0], result];
};
this.Adder16 = function(a, b) {
/*
HalfAdder(a=a[0],b=b[0],sum=out[0],carry=carry1);
FullAdder(a=a[1],b=b[1],c=carry1,sum=out[1],carry=carry2);
FullAdder(a=a[2],b=b[2],c=carry2,sum=out[2],carry=carry3);
FullAdder(a=a[3],b=b[3],c=carry3,sum=out[3],carry=carry4);
FullAdder(a=a[4],b=b[4],c=carry4,sum=out[4],carry=carry5);
FullAdder(a=a[5],b=b[5],c=carry5,sum=out[5],carry=carry6);
FullAdder(a=a[6],b=b[6],c=carry6,sum=out[6],carry=carry7);
FullAdder(a=a[7],b=b[7],c=carry7,sum=out[7],carry=carry8);
FullAdder(a=a[8],b=b[8],c=carry8,sum=out[8],carry=carry9);
FullAdder(a=a[9],b=b[9],c=carry9,sum=out[9],carry=carry10);
FullAdder(a=a[10],b=b[10],c=carry10,sum=out[10],carry=carry11);
FullAdder(a=a[11],b=b[11],c=carry11,sum=out[11],carry=carry12);
FullAdder(a=a[12],b=b[12],c=carry12,sum=out[12],carry=carry13);
FullAdder(a=a[13],b=b[13],c=carry13,sum=out[13],carry=carry14);
FullAdder(a=a[14],b=b[14],c=carry14,sum=out[14],carry=carry15);
FullAdder(a=a[15],b=b[15],c=carry15,sum=out[15],carry=carry16);
*/
var sum = [];
var carry;
sum[0] = this.halfAdder(a[0], b[0])[0];
carry = this.halfAdder(a[0], b[0])[1];
for (var i = 1; i <= 15; i++) {
sum[i] = this.fullAdder(a[i], b[i], carry)[0];
carry = this.fullAdder(a[i], b[i], carry)[1];
}
return sum;
}
}
My gates looks like the following:
function Gate() {
this.NAND = function(a, b) {
if (a == 1 && b == 1) return 0;
else return 1;
};
this.NOT = function(a) {
return this.NAND(a, a);
};
this.AND = function(a, b) {
return this.NOT(this.NAND(a, b));
};
this.OR = function(a, b) {
return this.NOT(this.AND(this.NOT(a), this.NOT(b)));
};
this.XOR = function(a, b) {
return this.OR(this.AND(a, this.NOT(b)), this.AND(this.NOT(a), b));
};
}
My half adder and full adder work, they passed all the unit tests provided by the creators of the course but for my 16 bit adder not. The unit tests are these:
describe('adder 16 bit tests', function() {
it('adder of a = 0000000000000000 and b = 0000000000000000 should be out = 0000000000000000', function() {
var adder = new Adder();
var a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var b = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var out = adder.Adder16(a, b);
var result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
assert.deepEqual(result, out);
});
it('adder of a = 0000000000000000 and b = 1111111111111111 should be out = 1111111111111111', function() {
var adder = new Adder();
var a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var b = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
var out = adder.Adder16(a, b);
var result = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
assert.deepEqual(result, out);
});
it('adder of a = 1111111111111111 and b = 1111111111111111 should be out = 1111111111111110', function() {
var adder = new Adder();
var a = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
var b = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
var out = adder.Adder16(a, b);
var result = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0];
assert.deepEqual(result, out);
});
it('adder of a = 1010101010101010 and b = 0101010101010101 should be out = 1111111111111111', function() {
var adder = new Adder();
var a = [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0];
var b = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1];
var out = adder.Adder16(a, b);
var result = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
assert.deepEqual(result, out);
});
it('adder of a = 0011110011000011 and b = 0000111111110000 should be out = 0100110010110011', function() {
var adder = new Adder();
var a = [0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1];
var b = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0];
var out = adder.Adder16(a, b);
var result = [0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1];
console.log(out);
assert.deepEqual(result, out);
});
it('adder of a = 0001001000110100 and b = 1001100001110110 should be out = 1010101010101010', function() {
var adder = new Adder();
var a = [0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0];
var b = [1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0];
var out = adder.Adder16(a, b);
var result = [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0];
assert.deepEqual(result, out);
});
});
The unit tests for the other gates and adders pass.
As you can see in this JSFiddle, when you use the arrow keys to move the red square around, the transition between tiles is very choppy and it just does not look good.
I am wondering if there is a way to have a smooth transition between tiles so it looks like one smooth motion?
var canvas, context, board, imageObj, tiles, board, display;
var NUM_OF_TILES = 2;
// viewport
var vX = 0,
vY = 0,
vWidth = 15,
vHeight = 10;
var playerX = 0,
playerY = 0;
var worldWidth = 29,
worldHeight = 19;
function loadMap(map) {
if (map == 1) {
return [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 0], [0, 1, 1, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 0], [0, 1, 1, 2, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 0], [0, 1, 1, 2, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 0], [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 1, 1, 0], [0, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 2, 1, 2, 1, 1, 1, 2, 1, 1, 0], [0, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 1, 0], [0, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 1, 0], [0, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 0], [0, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 0], [0, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 2, 2, 1, 1, 2, 1, 1, 0], [0, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 0], [0, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 1, 0], [0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]];
}
}
$(document).ready(function() {
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
canvas.tabIndex = 0;
canvas.focus();
canvas.addEventListener('keydown', function(e) {
console.log(e);
var key = null;
switch (e.which) {
case 37:
// Left
if (playerX > 0) playerX--;
break;
case 38:
// Up
if (playerY > 0) playerY--;
break;
case 39:
// Right
if (playerX < worldWidth) playerX++;
break;
case 40:
// Down
if (playerY < worldHeight) playerY++;
break;
}
// Okay! The player is done moving, now we have to determine the "best" viewport.
// Ideally the viewport centers the player,
// but if its too close to an edge we'll have to deal with that edge
vX = playerX - Math.floor(0.5 * vWidth);
if (vX < 0) vX = 0;
if (vX+vWidth > worldWidth) vX = worldWidth - vWidth;
vY = playerY - Math.floor(0.5 * vHeight);
if (vY < 0) vY = 0;
if (vY+vHeight > worldHeight) vY = worldHeight - vHeight;
draw();
}, false);
var board = [];
canvas.width = 512;
canvas.height = 352;
board = loadMap(1);
imageObj = new Image();
tiles = [];
var loadedImagesCount = 0;
for (x = 0; x <= NUM_OF_TILES; x++) {
var imageObj = new Image(); // new instance for each image
imageObj.src = "http://mystikrpg.com/canvas/img/tiles/t" + x + ".png";
imageObj.onload = function() {
// console.log("Added tile ... "+loadedImagesCount);
loadedImagesCount++;
if (loadedImagesCount == NUM_OF_TILES) {
// Onces all tiles are loaded ...
// We paint the map
draw();
}
};
tiles.push(imageObj);
}
function draw() {
context.clearRect(0,0,canvas.width, canvas.height);
for (y = 0; y <= vHeight; y++) {
for (x = 0; x <= vWidth; x++) {
theX = x * 32;
theY = y * 32;
context.drawImage(tiles[board[y+vY][x+vX]], theX, theY, 32, 32);
}
}
context.fillStyle = 'red';
context.fillRect((playerX-vX)*32, (playerY-vY)*32, 32, 32);
}
});
I played around a little bit and got something working:
case 39:
// Right
if (playerX < worldWidth) {
var start = playerX;
var end = Math.round(playerX + 1);
$({ i : start }).animate({ i: end}, {
duration: 400,
step: function(now) {
playerX = now;
draw();
}
});
}
break;
I use the jquery animate function in order to interpolate between the values. I realized the draw function is called only once, in order to get an animation i had to call it every step.
In order to avoid errors on the re-centering use Math.round() there too.
vX = Math.round(playerX) - Math.floor(0.5 * vWidth);
if (vX < 0) vX = 0;
if (vX+vWidth > worldWidth) vX = worldWidth - vWidth;
vY = Math.round(playerY) - Math.floor(0.5 * vHeight);
if (vY < 0) vY = 0;
if (vY+vHeight > worldHeight) vY = worldHeight - vHeight;
Of course you have to do additional work, e.g. the start and stop points could vary this way. As suggested you maybe should use pixel positions for your char instead of tiles. But i dont know your intent.
You can avoid the getting stuck on keydown by checking if the tile is in a "full" position by checking
if (playerY < worldHeight && playerY % 1 == 0) {...