issue when trying to move two div's onkeydown - javascript

The code seems right to me but when i try to move the div with class ai using the key 'A' and 'Q' it doesn't work , it work only with the div which have the class player when hitting up and down arrow :
LIVE DEMO
JavaScript :
var playerPosition = 0,
playerPosition2 = 0;
window.onkeydown = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if(key == 40) { // up arrow
playerPosition += 5;
} if(key == 38) { // down arrow
playerPosition -= 5;
}
if(key == 113) { // q buttton
playerPosition2 += 5;
} if(key == 97) {
playerPosition2 -= 5; // a button
}
var players1 = document.getElementsByClassName('player');
for(var i = 0; i < players1.length; i++) {
if (playerPosition < 0) {
playerPosition = 0;
}
else if (playerPosition > 330) {
playerPosition = 330;
}
players1[i].style.top = playerPosition + "px";
}
var players2 = document.getElementsByClassName('ai');
for(var i = 0; i < players2.length; i++) {
if (playerPosition2 < 0) {
playerPosition2 = 0;
}
else if (playerPosition > 330) {
playerPosition2 = 330;
}
players2[i].style.top = playerPosition2 + "px";
}
}

Not sure where you got those keyCode values
a = 65
q = 81
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Related

How to solve this multiple nested for loop

EDIT: Big edit from ealier
I have achieved: the ultimate for-loop HELL.
What it does: scans an image and finds a 40 by 40 pixel square that has every pixel within it approximately the same color.
The problem: The code doesn't work as intended. Unsure why, but all my attempts to debug are in vain.
jimp.read('jeffrey.png')
.then(image => {
console.log(jimp.intToRGBA(image.getPixelColor(0,0)))
console.log(image.bitmap.width)
console.log(image.bitmap.height)
var breakAll = false;
var FINALX;
var FINALY;
var doneCounter = 0;
//40 by 40 pixels needed for qr code. Thisis barcode, so make it 40 by 80 or smthn, figure out that x thing.
for(var x = 0; x < image.bitmap.width; x++) {
var breakThis = false;
console.log(x + " is x")
if(breakAll == true) {
break;
}
var verticalStart = 0;
for(var y1 = verticalStart; y1 < image.bitmap.height; y1++) {
if(breakAll == true) {
break;
}
var tempStandardR = jimp.intToRGBA(image.getPixelColor(x,y1)).r;
var tempStandardG = jimp.intToRGBA(image.getPixelColor(x,y1)).g;
var tempStandardB = jimp.intToRGBA(image.getPixelColor(x,y1)).b;
var verticalCounter = 0;
for(var y2 = y1; y2 < image.bitmap.height; y2++) {
if(breakAll == true) {
break;
}
if(verticalCounter >= 40) {
//Then do X stuff
//horizcountertim
for(var y3 = y1; y3 < y1 + 40; y3++) {
if(breakAll == true) {
break;
}
breakThis = false;
var horizontalCounter = 0;
var tempStandardR3 = jimp.intToRGBA(image.getPixelColor(x,y3)).r;
var tempStandardG3 = jimp.intToRGBA(image.getPixelColor(x,y3)).g;
var tempStandardB3 = jimp.intToRGBA(image.getPixelColor(x,y3)).b;
for(var x2 = x; x2 < x + 41; x2++) {
if(breakAll == true) {
break;
}
console.log(doneCounter)
if(doneCounter >= 40) {
//SUCESS!!!!!!
//THE SPOT HAS BEEN FOUND AT (x minus 40, y minus 40).
//insert other image in this image at above coordinates. Wow I highly doubt this works.
console.log('SUCESS!!!!!!!!!')
FINALX = x2-40;
FINALY = y3-40;
breakAll = true;
break;
}
if(breakAll == true) {
break;
}
var tempStandardR4 = jimp.intToRGBA(image.getPixelColor(x2,y3)).r;
var tempStandardG4 = jimp.intToRGBA(image.getPixelColor(x2,y3)).g;
var tempStandardB4 = jimp.intToRGBA(image.getPixelColor(x2,y3)).b;
if((((tempStandardR3 - tempStandardR4) <= 20) && ((tempStandardR3 - tempStandardR4) >= -20)) && (((tempStandardG3 - tempStandardG4) <= 20) && ((tempStandardG3 - tempStandardG4) >= -20)) && (((tempStandardB3 - tempStandardB4) <= 20) && ((tempStandardB3 - tempStandardB4) >= -20))) {
horizontalCounter++;
if(horizontalCounter == 40) {
horizontalCounter = 0;
doneCounter++;
break;
}
// if((x2 - x >= 39) && (y3 - y1) >= 39) {
if(breakAll == true) {
break;
}
}
else {
horizontalCounter = 0;
verticalCounter = 0;
doneCounter = 0;
console.log('donecounter reset')
verticalStart = y3;
//y2 = y3;
breakThis = true;
break;
}
}
if(breakAll == true) {
break;
}
if(breakThis = true) {
break;
}
}
if(breakThis = true) {
breakThis = false;
break;
}
}
if(breakAll == true) {
break;
}
var tempStandardR2 = jimp.intToRGBA(image.getPixelColor(x,y2)).r;
var tempStandardG2 = jimp.intToRGBA(image.getPixelColor(x,y2)).g;
var tempStandardB2 = jimp.intToRGBA(image.getPixelColor(x,y2)).b;
if((((tempStandardR - tempStandardR2) <= 20) && ((tempStandardR - tempStandardR2) >= -20)) && (((tempStandardG - tempStandardG2) <= 20) && ((tempStandardG - tempStandardG2) >= -20)) && (((tempStandardB - tempStandardB2) <= 20) && ((tempStandardB - tempStandardB2) >= -20))) {
verticalCounter++;
}
else {
verticalCounter = 0;
verticalStart = y2;
console.log('lvl1 reset')
doneCounter = 0;
break;
}
}
}
}
console.log(' done');
console.log(FINALX + " = x")
console.log(FINALY + " = y")
})
.catch(err => {
console.log(err);
})
Each of the tempStandards are the RGB value for that individual pixel.
All of the for loops are to get a 40 by 40 open grid.
The issue I do see is a problem, but am baffled as to why, is doneCounter, that is supposed to ++ every time a horizontal counter has reached 40 and thus finished its horizontal check of one row of the 40 by 40 grid.
The issue when console logging doneCounter is, it console logs the same value twice, which makes no sense since its within the same for loop that has an if else statement that either adds to donecounter or resets it to 0.
EDIT: I scrapped the above code to try and remake it entirely to see if that would let it work, still failed though and not a clue as to why: Below is the updated attempt:
jimp.read('jeffrey.png')
.then(image => {
console.log(jimp.intToRGBA(image.getPixelColor(0,0)))
console.log(image.bitmap.width)
console.log(image.bitmap.height)
var breakAll = false;
var FINALX;
var FINALY;
var doneCounter = 0;
var veritcalCounter = 0;
var verticalStart = 0;
var horizontalCounter = 0;
var breakAll = false;
var breakThis = false;
//40 by 40 pixels needed for qr code. Thisis barcode, so make it 40 by 80 or smthn, figure out that x thing.
for(var x = 0; x < image.bitmap.width; x++) {
console.log(x)
verticalCounter = 0;
for(var y = 0; y < image.bitmap.height; y++) {
var tempStandardR = jimp.intToRGBA(image.getPixelColor(x,verticalStart)).r;
var tempStandardG = jimp.intToRGBA(image.getPixelColor(x,verticalStart)).g;
var tempStandardB = jimp.intToRGBA(image.getPixelColor(x,verticalStart)).b;
var tempStandardR2 = jimp.intToRGBA(image.getPixelColor(x,y)).r;
var tempStandardG2 = jimp.intToRGBA(image.getPixelColor(x,y)).g;
var tempStandardB2 = jimp.intToRGBA(image.getPixelColor(x,y)).b;
if((((tempStandardR - tempStandardR2) <= 20) && ((tempStandardR - tempStandardR2) >= -20)) && (((tempStandardG - tempStandardG2) <= 20) && ((tempStandardG - tempStandardG2) >= -20)) && (((tempStandardB - tempStandardB2) <= 20) && ((tempStandardB - tempStandardB2) >= -20))) {
verticalCounter++;
if(verticalCounter == 40) {
verticalCounter = 0;
for(var y1 = y-40; y1 < y; y1++) {
horizontalCounter = 0;
for(var x1 = x; x1 < x+41; x1++) {
var tempStandardR3 = jimp.intToRGBA(image.getPixelColor(x,y1)).r;
var tempStandardG3 = jimp.intToRGBA(image.getPixelColor(x,y1)).g;
var tempStandardB3 = jimp.intToRGBA(image.getPixelColor(x1,y1)).b;
var tempStandardR4 = jimp.intToRGBA(image.getPixelColor(x1,y1)).r;
var tempStandardG4 = jimp.intToRGBA(image.getPixelColor(x1,y1)).g;
var tempStandardB4 = jimp.intToRGBA(image.getPixelColor(x1,y1)).b;
if((((tempStandardR3 - tempStandardR4) <= 20) && ((tempStandardR3 - tempStandardR4) >= -20)) && (((tempStandardG3 - tempStandardG4) <= 20) && ((tempStandardG3 - tempStandardG4) >= -20)) && (((tempStandardB3 - tempStandardB4) <= 20) && ((tempStandardB3 - tempStandardB4) >= -20))) {
if(x1 == x+40) {
doneCounter++;
if(doneCounter == 39) {
//SUCESS!!!!!!
//THE SPOT HAS BEEN FOUND AT (x minus 40, y minus 40).
//insert other image in this image at above coordinates. Wow I highly doubt this works.
console.log('SUCESS!!!!!!!!!')
FINALX = x;
FINALY = y1-40;
breakAll = true;
break;
}
break;
}
}
else {
verticalCounter = 0;
horizontalCounter = 0;
doneCounter = 0;
y = y1;
breakThis = true;
break;
}
if(breakAll == true) {
break;
}
}
if(breakThis == true) {
breakThis = false;
break;
}
if(breakAll == true) {
break;
}
}
if(breakAll == true) {
break;
}
}
if(breakAll == true) {
break;
}
}
else {
verticalCounter = 0;
verticalStart = 0;
}
if(breakAll == true) {
break;
}
}
if(breakAll == true) {
break;
}
}
console.log(' done');
console.log(FINALX + " = x")
console.log(FINALY + " = y")
})
.catch(err => {
console.log(err);
})

how to get multiple keyboard inputs in javaScript

I am trying to make a pong like game in html, but every time one player try to move the other movement will stop.
//javaScript
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115)
{
p1axis += 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 119)
{
p1axis -= 2;
document.getElementById("p1").style.top = p1axis + "%";
}
if(x == 108)
{
p2axis += 2;
document.getElementById("p2").style.top = p2axis + "%";
}
if(x == 111)
{
p2axis -= 2;
document.getElementById("p2").style.top = p2axis + "%";
}
}
I expect that both players will be able to play freely.
instead only one can move at once.
You can create an array and add keys as they are pressed. You will have to remove them as the key is released. Also, I just used keydown with jQuery, you can also use keydown with JavaScript.
var bKeys = [];
$('body').keydown(function(e) {
if (bKeys.includes(e.which) === false) {
bKeys.push(e.which);
}
});
$('body').keyup(function(e) {
bKeys.pop(e.which);
});
setInterval(() => {
console.log(bKeys);
}, 15);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Remember to click in the body when you run the code
var k1 = false, k2 = false, k3 = false, k4 = false;
var p1axis = 40;
var p2axis = 40;
function input(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = true;
}
if(x == 119 || x == 87)
{
k2 = true;
}
if(x == 108 || x == 76)
{
k3 = true;
}
if(x == 111 || x == 79)
{
k4 = true;
}
}
function remove(event)
{
var x = event.charCode || event.keyCode;
if(x == 115 || x == 83)
{
k1 = false;
}
if(x == 119 || x == 87)
{
k2 = false;
}
if(x == 108 || x == 76)
{
k3 = false;
}
if(x == 111 || x == 79)
{
k4 = false;
}
}
function move()
{
if(k1)
{
p1axis += 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k2)
{
p1axis -= 1;
document.getElementById("p1").style.top = p1axis + "%";
}
if(k3)
{
p2axis += 1;
document.getElementById("p2").style.top = p2axis + "%";
}
if(k4)
{
p2axis -= 1;
document.getElementById("p2").style.top = p2axis + "%";
}
setTimeout(move, 20);
}

an if statement returns true, but the condition won't trigger

I have an if statement in my code as you can see below. When I check in console log when those two elements collide with each other, the if statement becomes true, but it won't stop my interval function. I wonder what would have caused it to not work as it should?
var animationTimer = setInterval(bladAnimation, 30);
document.onkeydown = function(event) {
if (event.keyCode == 37) {
// <--
fx = -15;
fy = 0;
froskAnimation()
}
if (event.keyCode == 38) {
// opp
fy = -15;
fx = 0;
froskAnimation()
}
if (event.keyCode == 39) {
// -->
fx = 15;
fy = 0;
froskAnimation()
}
if (event.keyCode == 40) {
// ned
fy = 15;
fx = 0;
froskAnimation()
}
}
function froskAnimation() {
Xfrosk = fx + Xfrosk;
Yfrosk = fy + Yfrosk;
if ((Yfrosk + 70 > maxY) || (Yfrosk < minY)) {
Yfrosk = Yfrosk - fy;
}
if ((Xfrosk + 70 > maxX) || (Xfrosk < minX)) {
Xfrosk = Xfrosk - fx;
}
frosk.style.left = Xfrosk + "px";
frosk.style.top = Yfrosk + "px";
console.log(Xfrosk)
}
function bladAnimation() {
Yblad = by + Yblad;
if ((Yblad + 70 > maxY) || (Yblad < minY)) {
by = by * -1;
}
blad.style.top = Yblad + "px";
}
if (blad.x < frosk.x + frosk.width && blad.x + blad.width > frosk.x
&& blad.y < frosk.y + frosk.height && blad.y + blad.height > frosk.y) {
clearInterval(animationTimer);
}
full code here: https://codepen.io/ctrlvi/pen/jXbJYG
That condition is executed only once, when your javascript is loaded. At that point the condition is probably false. You should move it at the end of bladAnimation (I suppose what you're trying to do is stop the self-moving block when it hits the other one).
function bladAnimation() {
Yblad = by + Yblad;
if ((Yblad + 70 > maxY) || (Yblad < minY)) {
by = by * -1;
}
blad.style.top = Yblad + "px";
if (blad.x < frosk.x + frosk.width && blad.x + blad.width > frosk.x
&& blad.y < frosk.y + frosk.height && blad.y + blad.height > frosk.y) {
clearInterval(animationTimer);
}
}

Generating a random grid of connected paths

I am trying to generate a random grid of connected paths. The image below shows how far I've managed to get it:
The rules that the grid needs to adhere to are the following:
all the paths must connect to each other in some way but there can be dead ends
there can be no blocks that have no connections (i.e. can't be reached)
the blocks on the edge must have paths that point inward, not outward.
As you can see in my image, my code isn't quite right, but I can't find the error.
Here is a fiddle with the code: jsfiddle.net/thatOneGuy/jz5sfr00/1
But I think my mistake is in this function:
function linkAll() {
for (var x = 0; x < 9; x++) {
for (y = 0; y < 9; y++) {
//link up to each other
var count = 0;
if ((x > 0) && (y > 0)) {
if (hz[x - 1][y].right) {
hz[x][y].left = 1;
} else count++;
if (hz[x][y - 1].bottom) {
hz[x][y].top = 1;
} else count++;
}
if ((x < 9) && (y < 9)) {
if (hz[x + 1][y].left) {
hz[x][y].right = 1;
} else count++;
if (hz[x][y + 1].top) {
hz[x][y].bottom = 1;
} else count++;
}
if (count == 4) {
var newPath = getDirection(getRandomInt(0, 3));
if (newPath == 'top') {
hz[x][y - 1].bottom = 1
hz[x][y].top = 1;
} else if (newPath == 'left') {
hz[x - 1][y].right = 1;
hz[x][y].left = 1;
} else if (newPath == 'bottom') {
hz[x][y + 1].top = 1;
hz[x][y].bottom = 1;
} else if (newPath == 'right') {
hz[x + 1][y].left = 1;
hz[x][y].right = 1;
}
}
} //end for (y)
} //end for (x)
}
UPDATE:
I realised that I confused the x and y values of the array. They should have been swopped.
So I added a linkEdges() function so that the edge blocks all link together:
function linkEdges(){
for(var x = 0; x < 10; x++){
for(var y = 0; y < 10; y++){
if((x==0) && (y > 0) && (y < 9)){
if(hz[0][y-1].right){
//console.log(x + ' ' + y + ' y-1 = 1');
//console.log('Inside (y-1) ');
//console.log(hz[x][y]);
if (hz[0][y].left != null)
{
hz[0][y].left = 1;
}
}
}
if ((y==0) && (x > 0)){
if(hz[x-1][0].bottom){
if(hz[x][0].top != null)
hz[x][0].top = 1;
}
}
if ((y==9) && (x < 9) && (x > 0)){
if(hz[x+1][9].top){
if(hz[x][9].bottom != null)
hz[x][9].bottom = 1;
}
}
if ((x==9) && (y < 9)){
if(hz[9][y+1].left){
if(hz[9][y].right != null)
hz[9][y].right = 1;
}
}
} //end for(y)
}//end for(x)
}
I also updated the linkAll() function:
function linkAll(){
for(var x=0; x < 9; x++){
for(var y=0; y < 9; y++){
//link up to each other
var count = 0;
if((x > 0) && (y > 0)){
if(hz[x-1][y].bottom){
hz[x][y].top = 1;
}
else count++;
if(hz[x][y-1].right){
hz[x][y].left = 1;
}
else count++;
}
if((x < 9) && (y < 9)){
if(hz[x+1][y].top){
hz[x][y].bottom = 1;
}
else count++;
if(hz[x][y+1].left){
hz[x][y].right = 1;
}
else count++;
}
if(count == 4){
//console.log('x: ' + x + ' y: '+y);
var newPath = getDirection(getRandomInt(0, 3));
//console.log(newPath);
if(newPath == 'top'){
hz[x][y-1].right = 1
hz[x][y].left = 1;
}
else if(newPath == 'left'){
hz[x-1][y].bottom = 1;
hz[x][y].top = 1;
}
else if(newPath == 'bottom'){
hz[x][y+1].left = 1;
hz[x][y].right = 1;
}
else if(newPath == 'right'){
hz[x+1][y].top = 1;
hz[x][y].bottom = 1;
}
}
}//end for (y)
}//end for (x)
}
My grid now looks like this:
I just don't know how to connect those last few edges. I think it has something to do with my linkEdges() function.

javascript array problem

i have written a snake program using javascript..
the problem is that the snake does not grow more than 2 blocks size....
<html>
<head>
<script type="text/javascript">
var matrix, body, dir, key, lastx, lasty, start, applex, appley, eat, hal;
function node(x, y) {
this.x = x;
this.y = y;
}
function draw() {
var str;
for (var i = 0; i < body.length; i++) {
matrix[body[i].x * 50 + body[i].y].bgColor = "black";
}
}
function halt() {
hal = 1 - hal;
if (hal == 0) automove();
}
function check_status() {
if (start == 1 && hal == 0) {
var ch;
if (eat == 1) {
do {
ch = 0;
applex = Math.round(49 * Math.random());
appley = Math.round(49 * Math.random());
for (var i = 0; i < body.length; i++)
if (body[i].x == applex && body[i].x == appley) ch = 1;
} while (ch == 1);
matrix[applex * 50 + appley].bgColor = "blue";
eat = 0;
}
lastx = body[body.length - 1].x;
lasty = body[body.length - 1].y;
for (var i = 1; i < body.length; i++) {
body[i].x = body[i - 1].x;
body[i].y = body[i - 1].y;
}
if (dir == 1)--body[0].x;
else if (dir == -1)++body[0].x;
else if (dir == 2)--body[0].y;
else if (dir == -2)++body[0].y;
if (body[0].x == -1 || body[0].x == 50 || body[0].y == 50 || body[0].y == -1) {
alert("GAME OVER!!");
start = 0;
}
for (var i = 1; i < body.length; i++) {
if (body[0].x == body[i].x && body[0].y == body[i].y) {
alert("GAME OVER!!");
start = 0;
i = 10000;
}
}
if (body[0].x == applex && appley == body[0].y) {
eat = 1;
body[body.length] = new node(lastx, lasty);
}
matrix[lastx * 50 + lasty].bgColor = "white";
draw();
}
}
function automove() {
if (start == 1 && hal == 0) {
if (key != -dir) dir = key;
check_status();
window.setTimeout("automove()", 200);
}
}
function init() {
start = 1;
var x = document.getElementById("mine");
var str = "<table id='tab' align='center' height='500px' cellSpacing='0' cellPadding='0' width='500px' border='4' >";
for (var i = 0; i < 50; i++) {
str += "<tr>";
for (var j = 0; j < 50; j++)
str += "<td></td>";
str += "</tr>";
}
str += "</table>";
x.innerHTML = str;
matrix = document.getElementsByTagName("td");
body = new Array();
body[0] = new node(0, 0);
draw();
dir = key = -1;
eat = 1;
v = 0;
hal = 0;
automove();
}
function keypress(e) {
if ((e.keyCode == 38) || ((e.which) && (e.which == 38))) //up
key = 1;
else if ((e.keyCode == 40) || ((e.which) && (e.which == 40))) //down
key = -1;
else if ((e.keyCode == 37) || ((e.which) && (e.which == 37))) //left
key = 2;
else if ((e.keyCode == 39) || ((e.which) && (e.which == 39))) //right
key = -2;
check_status();
}
</script>
</head>
<body onkeydown=keypress(event)>
<br/>
<input type="button" onClick="init()" value="play">
<input type="button" onClick="halt()" value="pause">
<p id="mine"></p>
<br><h5 id="score"></h5>
</body>
</html>
The problem is here:
lastx=body[body.length-1].x;
lasty=body[body.length-1].y;
for(var i=1;i<body.length;i++)
{
body[i].x=body[i-1].x;
body[i].y=body[i-1].y;
}
In that loop, body[1] is assigned to body[0], then body [2] is assigned to body[1] etc. This means that everything from index 1 to the end will be set equal to body[0], then body[0] is altered based on direction - so there are only two positions.
Look into the javascript unshift method.
You could replace that loop with:
body.unshift(body[0]);

Categories

Resources