I implemented a Conway's Game of Life in JavaScript but I'm not seeing the same patterns such as Gosper's Glider Gun. I seed the grid the ways it's depicted in the Wikipedia article but, the gun never happens.
Will someone look at my code and see if there's anything wrong with it, any suggestions to the implementation?
https://github.com/DiegoSalazar/ConwaysGameOfLife
You are not updating all of the cells simultaneously, rather sequentially. A cell that is born in the first generation will not appear alive to the calculation of other cells of the first generation (it still counts as dead).
Create a new property called willBeAlive and use that to hold the cell's new calculated alive state. Once all the calculations for that generation are done, set each cell's alive property to its willBeAlive property and redraw.
Here are the changes:
Automaton.prototype.update = function() {
for (var x = 0; x < this.w; x++) {
for (var y = 0; y < this.h; y++) {
this.grid[x][y].killYourselfMaybe();
}
}
// set the alive property to willBeAlive
for (var x = 0; x < this.w; x++) {
for (var y = 0; y < this.h; y++) {
this.grid[x][y].alive = this.grid[x][y].willBeAlive;
}
}
}
Cell.prototype.killYourselfMaybe = function(grid) {
var num = this.numLiveNeighbors();
this.willBeAlive = false;
if (this.alive) {
// 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
if (num < 2) this.willBeAlive = false;
// 2. Any live cell with two or three live neighbours lives on to the next generation.
if (num == 2 || num == 3) { this.willBeAlive = true}
// 3. Any live cell with more than three live neighbours dies, as if by overcrowding.
if (num > 3) this.willBeAlive = false;
} else {
// 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
if (num == 3) this.willBeAlive = true;
}
}
and here is a seed array for "Gosper's Glider Gun":
[[2,6],[2,7],[3,6],[3,7],[12,6],[12,7],[12,8],[13,5],[13,9],[14,4],[14,10],[15,4],[15,10],[16,7],[17,5],[17,9],[18,6],[18,7],[18,8],[19,7],[22,4],[22,5],[22,6],[23,4],[23,5],[23,6],[24,3],[24,7],[26,2],[26,3],[26,7],[26,8],[36,4],[36,5],[37,4],[37,5]]
Related
I'm creating a small game in javascript and I'm using svg for the graphics. Right now I'm having a problem with updating the game in the middle of a game tick. If I exit my loop directly after I update the fill attribute with "setAttributeNS", it's redrawn, but if I don't do that, it isn't updated until after "game_tick" is over. Even worse, if I call "game_tick" multiple times in a row, the svg objects aren't updated until after I've run all of the "game_tick"s instead of being updated after each one.
function game_tick(){
num_grid_copy = num_grid.slice();
for (var x = 0; x < num_squares_x; x += 1) {
for (var y = 0; y < num_squares_x; y += 1) {
var n = get_neighbors(x,y);
var isAliveInNextGen = next_gen(n, num_grid[x*num_squares_x+y]);
num_grid_copy[x*num_squares_x+y] = isAliveInNextGen;
if (isAliveInNextGen == 1){
rect_grid[x*num_squares_x+y].setAttributeNS(null, 'fill', '#0099ff');
}
else {
rect_grid[x*num_squares_x+y].setAttributeNS(null, 'fill', '#fff');
}
}
}
num_grid = num_grid_copy;
}
Thanks to valuable input from Robert I realized that javascript execution and page rendering are done in the same thread. I changed the function to the following:
function start() {
var inc = 0,
max = 25;
delay = 100; // 100 milliseconds
var repeat = setInterval(function() {
game_tick();
if (++inc >= max)
clearInterval(repeat);
},
delay);
}
This works fine. I can set the delay and the number of times it repeats.
My simple JavaScript game is a Space Invaders clone.
I am using the p5.js client-side library.
I have tried many things to attempt at speeding up the game.
It start off fast, and then over time it get slower, and slower, it isn't as enjoyable.
I do not mean to show every bit of code I have. I am not showing every class, but I will show the main class where everything is happening.
Could someone eyeball this and tell me if you see anything major?
I am new to JS and new to making games, I know there is something called update()
that people use in scripting but I am not familiar with it.
Thank you.
var ship;
var flowers = []; // flowers === aliens
var drops = [];
var drops2 = [];
function setup() {
createCanvas(600, 600);
ship = new Ship();
for (var i = 0; i < 6; i ++) {
flowers[i] = new Flower(i * 80 + 80, 60);
}
flower = new Flower();
}
function draw() {
background(51);
ship.show();
ship.move();
shipDrops();
alienDrops();
dropsAndAliens();
dropDelete();
drop2Delete();
}
// if 0 drops, show and move none, if 5, etc..
function shipDrops() {
for (var i = 0; i < drops.length; i ++) {
drops[i].show();
drops[i].move();
for (var j = 0; j < flowers.length; j++) {
if(drops[i].hits(flowers[j]) ) {
flowers[j].shrink();
if (flowers[j].r === 0) {
flowers[j].destroy();
}
// get rid of drops after it encounters ship
drops[i].evaporate();
}
if(flowers[j].toDelete) {
// if this drop remove, use splice function to splice out of array
flowers.splice(j, 1); // splice out i, at 1
}
}
}
}
function alienDrops() {
// below is for alien/flower fire drops 2
for (var i = 0; i < drops2.length; i ++) {
drops2[i].show();
drops2[i].move();
if(drops2[i].hits(ship) ) {
ship.shrink();
drops2[i].evaporate(); // must evap after shrink
ship.destroy();
if (ship.toDelete) {
delete ship.x;
delete ship.y;
} // above is in progress, deletes after ten hits?
}
}
}
function dropsAndAliens() {
var randomNumber; // for aliens to shoot
var edge = false;
// loop to show multiple flowers
for (var i = 0; i < flowers.length; i ++) {
flowers[i].show();
flowers[i].move();
// ******************************************
randomNumber = Math.floor(Math.random() * (100) );
if(randomNumber === 5) {
var drop2 = new Drop2(flowers[i].x, flowers[i].y, flowers[i].r);
drops2.push(drop2);
}
//**************** above aliens shooting
// below could be method, this will ensure the flowers dont
//go offscreen and they move
//makes whtever flower hits this space become the farther most
//right flower,
if (flowers[i].x > width || flowers[i]. x < 0 ) {
edge = true;
}
}
// so if right is true, loop thru them all again and reset x
if (edge) {
for (var i = 0; i < flowers.length; i ++) {
// if any flower hits edge, all will shift down
// and start moving to the left
flowers[i].shiftDown();
}
}
}
function dropDelete() {
for (var i = drops.length - 1; i >= 0; i--) {
if(drops[i].toDelete) {
// if this drop remove, use splice function to splice out of array
drops.splice(i, 1); // splice out i, at 1
}
}
}
function drop2Delete() {
for (var i = drops2.length - 1; i >= 0; i--) {
if(drops2[i].toDelete) {
// if this drop remove, use splice function to splice out of array
drops2.splice(i, 1); // splice out i, at 1
}
}
}
function keyReleased() {
if (key != ' ') {
ship.setDir(0); // when i lift the key, stop moving
}
}
function keyPressed() {
// event triggered when user presses key, check keycode
if(key === ' ') {
var drop = new Drop(ship.x, height); // start ship x and bottom of screen
drops.push(drop); // when user hits space, add this event to array
}
if (keyCode === RIGHT_ARROW) {
// +1 move right
ship.setDir(1);
} else if (keyCode === LEFT_ARROW) {
// -1 move left
ship.setDir(-1);
} // setir only when pressing key, want continuous movement
}
Please post a MCVE instead of a disconnected snippet that we can't run. Note that this should not be your entire project. It should be a small example sketch that just shows the problem without any extra code.
But to figure out what's going on, you need to debug your program. You need to find out stuff like this:
What is the length of every array? Are they continuously growing over time?
What is the actual framerate? Is the framerate dropping, or does it just appear to be slower?
At what point does it become slower? Try hard-coding different values to see what's going on.
Please note that I'm not asking you to tell me the answers to these questions. These are the questions you need to be asking yourself. (In fact, you should have all of these answers before you post a question on Stack Overflow!)
If you still can't figure it out, then please post a MCVE in a new question post and we'll go from there. Good luck.
So I have been making this little shooter game with javascript and I have ran to a problem I cant figure out.
I have a collision check which checks if any alive enemy collides with the player or a bullet using a for loop. The loop runs fine until I spawn an enemy.
In the beginning of the for loop you can see console.log, it logs numbers only till the first alive enemy's index. For example if enemies[4] is alive and no other enemies with index before that are alive, it keeps logging 0, 1, 2, 3 and 4. If I then kill all the enemies the loop runs full 50 times again (which is the length of the array) until an enemy spawns.
checkCollision: function(){
function calculate(enemy, other){
var r = enemy.r + other.r;
var dx = enemy.posX - other.posX;
var dy = enemy.posY - other.posY;
var d = Math.sqrt((dx * dx) + (dy * dy));
if(r > d){
enemy.alive = false;
other.alive = false;
return true;
}
return false;
}
for (var i = 0, max = this.enemies.length; i < max; i++) {
console.log(i);
if(this.enemies[i].alive){
if(calculate(this.enemies[i], this.player)){
continue;
}
for (var i = 0, max = this.player.weapon.bullets.length; i < max; i++){
if(this.player.weapon.bullets[i].alive){
if(calculate(this.enemies[i], this.player.weapon.bullets[i])){
break;
}
}
}
}
}
}
Here is a little visualization:
[0] = !alive
[1] = alive
[2] = !alive
[3] = alive
[4] = alive
Now the for loop would run only 2 times, therefore not checking the collision for 3 and 4, which is what i want it to do.
Well, you have a loop, which loops over all enemies, but checks only one enemy at a time and only against the player, not against each other.
So try something like:
for (var i = 0, max = this.enemies.length; i < max; i++) {
for (var j = 0, max = this.enemies.length; j < max; j++) {
if(calculate(this.enemies[i], this.enemies[j]){
doSomething();
}
}
}
// Don't forget the player.
In case you are interested, there is a quite good HTML5 Game Development course which teaches you how to use an open source physics engine, which takes care of those things.
While looking for a job, I made a small version of Mario, using that open source project, and the info from that course. You can see the game on my website under "projects".
Edit
So after your example I understood your question. You are reusing the i and max variables in the inner loop about bullets. So if the inner loop finishes, the outer loop will also terminate as they both check i < max.
Hello fellow programmers,
Today I have a question that's related to one of my projects I'm making kinda like Tower Defense using canvas. However, I stuck on trying to detect multiple circles in one coordinate. Here's my example:
for (var a = 0; a < buildArcherX.length; a++) {
for (var a = 0; a < buildArcherY.length; a++) {
if (Math.sqrt(Math.pow(buildArcherX[a] - this.x, 2) + Math.pow(buildArcherY[a] - this.y, 2)) <= arch.radius + 7) {
this.attackedByArcher = true;
} else {
this.attackedByArcher = false;
}
}
}
As you can see in this example, I'm using arrays to put my coordinates in for my "Defenses". The for statements runs through all the "defense" coordinates in the arrays. The if statement in the code calculates if any of the defense coordinates are within "this" coordinates. This returns a boolean if any of the defenses are in range.
However I got to this point, and then got stuck on this problem: What happens if multiple defenses are in range? Then "this" would need to take more damage. So I'm just wondering if I can show the number of defenses in range.
Thanks!
You can use an integer to store the value of how many defenses are in range and increment it whenever a defense has been found in range.
Also, you must use 2 different variables when nesting loops.
this.defensesInRange = 0;
for (var x = 0; x < buildArcherX.length; x++) {
for (var y = 0; y < buildArcherY.length; y++) {
if (Math.sqrt(Math.pow(buildArcherX[x] - this.x, 2) + Math.pow(buildArcherY[y] - this.y, 2)) <= arch.radius + 7) {
this.defensesInRange += 1;
}
}
}
I'm presented with the following challenge question:
There are a circle of 100 baskets in a room; the baskets are numbered
in sequence from 1 to 100 and each basket contains one apple.
Eventually, the apple in basket 1 will be removed but the apple in
basket 2 will be skipped. Then the apple in basket 3 will be removed.
This will continue (moving around the circle, removing an apple from a
basket, skipping the next) until only one apple in a basket remains.
Write some code to determine in which basket the remaining apple is
in.
I concluded that basket 100 will contain the last apple and here's my code:
var allApples = [];
var apples = [];
var j = 0;
var max = 100;
var o ='';
while (j < max) {
o += ++j;
allApples.push(j);
}
var apples = allApples.filter(function(val) {
return 0 == val % 2;
});
while (apples.length > 1) {
for (i = 0; i < apples.length; i += 2) {
apples.splice(i, 1);
}
}
console.log(apples);
My question is: did I do this correctly? What concerns me is the description of "a circle" of baskets. I'm not sure this is relevant at all to how I code my solution. And would the basket in which the remaining apple reside be one that would otherwise be skipped?
I hope someone can let me know if I answered this correctly, answered it partially correct or my answer is entirely wrong. Thanks for the help.
So, ... I got WAY too into this question :)
I broke out the input/output of my last answer and that revealed a pretty simple pattern.
Basically, if the total number of items is a power of 2, then it will be the last item. An additional item after that will make the second item the last item. Each additional item after that will increase the last item by 2, until you reach another item count that is again divisible by a power of 2. Rinse and repeat.
Still not a one-liner, but will be much faster than my previous answer. This will not work for 1 item.
var items = 100;
function greatestPowDivisor(n, p) {
var i = 1;
while(n - Math.pow(p, i) > 0) {
i++;
}
return Math.pow(p, (i - 1));
}
var d = greatestPowDivisor(items, 2)
var last_item = (items - d) * 2;
I believe Colin DeClue is right that there is a single statement that will solve this pattern. I would be really interested to know that answer.
Here is my brute force solution. Instead of moving items ("apples") from their original container ("basket") into a discard pile, I am simply changing the container values from true or false to indicate that an item is no longer present.
var items = 100;
var containers = [];
// Just building the array of containers
for(i=0; i<items; i++) {
containers.push(true);
}
// count all containers with value of true
function countItemsLeft(containers) {
total = 0;
for(i=0; i<containers.length; i++) {
if(containers[i]) {
total++;
}
}
return total;
}
// what is the index of the first container
// with a value of true - hopefully there's only one
function getLastItem(containers) {
for(i=0; i<containers.length; i++) {
if(containers[i]) {
return(i);
}
}
// shouldn't get here if the while loop did it's job
return false;
}
var skip = false;
// loop through the items,
// setting every other to false,
// until there is only 1 left
while(countItemsLeft(containers) > 1) {
for(i=0; i<containers.length; i++) {
if(containers[i]) {
if(skip) {
skip = false;
} else {
containers[i] = false;
skip = true;
}
}
}
}
// what's the last item? add one to account for 0 index
// to get a human readable answer
var last_item = getLastItem(containers) + 1;
Needs error checking, etc... but it should get the job done assuming items is an integer.