If you have two ants, they create interesting patterns depending on their positions. As well as the hive (blob) - highway (diagonal line) pattern, they can run a create/destroy loop on a partial hive, or they can start chasing each other in an expanding-collapsing diamond pattern. It is worth creating an Ant class to support that. You can then extend that to encode the turn behaviour (left, right, no change, 180deg) and/or what colour to change to. These create some interesting behaviours -- I've had some ant variants build a "super highway" of a certain colour in a straight line, then zoom along it (using the "no change" turn rule). Combining ants with different rules is also interesting (but they need to support the same number of colours, otherwise they will stop if they get to an unsupported colour). You could also extend this to support Turmites (en.wikipedia.org/wiki/Turmite), who's behaviour depends on their state as well as the cell colour.
Langton's Car. Set all pixels positions on screen to a random value of either 0,1,2, or 3. Set a particle "car" in the middle with an arbitrary velocity vector. On each frame, the car will move to a new position. if the pixel is 0, increase speed slightly, but never more than maxSpeed. If the pixel is 1, angle slightly to the right. If the pixel is 2, decrease speed slightly, but never less than 1. If the pixel is 3, angle slightly to the left. Reset the pixel it's on to a new random value so no infinite loops occur, and then update position. For bonus points, set up a "garage" somewhere (3 sides of a rectangle), and see if the car can drive into it. If you increase the increment of the angle to 90 degrees left or right, the car will drift sideways for a few frames before correcting. Add tire squealing sound effects as needed.
Instead of that single direction variable (and the 4 constants and that huge movement function) when just using a vector (dirX, dirY) everything becomes much simpler. Rotating is just swapping dirX and dirY and inverting one of them. Which you invert defines the direction you're rotating. The movement is just adding dirX to x and dirY to y. Of course we still need the screen edge wrapping. Something like this: void Turn(boolean turnRight) { int tmp = dirX; if (turnRight) { dirX = -dirY; dirY = tmp; } else { dirX = dirY; dirY = -tmp; } } void moveForward() { x = (x + dirX + width) % width; y = (y + dirY + height) % height; }
My favorite way to set variables from a 1 or 0 value like this is doing (in this case) int color = grid[x][y]*255 Since if its 0, it'll be 0 and if its 1, it'll be 255
One way I implemented turning was with an array in js: direction = [0, -1, 0, 1] Then using some array management: direction.unshift(direction.pop()) // turns one way if (isWhite(img, loc.x + 1, loc.y + 1)) { direction.push(direction.shift()) // if white, turn right (undoes the first turn that always happens) direction.push(direction.shift()) // then turns again, effectively turning the way we wanted for this situation Then if you play with the direction variable values you can come up with some really neat patterns some are just loosely similar to Langton's ant, and others are bizarre recursive/fractal patterns. Loved this video. Fun inspiration, and had fun writing it for myself in p5!
When I made it, I did the same, but I used a 4 number array representing the amount to change the ant's index (As I had it represented by a position in a 1d array of the grid), and had a variable that would range from 0 to 3 representing the direction. When the ant would move, it would use the direction as an index for the aforementioned array, and that would be the amount it changes it's position by. For turning, I had an array of +1 and -1 representing right and left respectively, and using the value of the cell the ant moves into (post-step) as an index for this array, I would change the direction variable. So it would either increase by 1, or decrease by 1. Before assigning it, I would perform a bitwise AND operation on it with 0b11 (3) so that if it became -1, it would change to 3. My goal was to write it in JS while optimizing the absolute hell out of it, to the best of my ability, so that it would run as fast as possible in a webpage. With just JS, I got it to 80 million steps/second (Capped by Chrome), and with WebAssembly, I got it to 200 million/second. With WebAssembly: www.jdoodle.com/h/1Yw With pure JS: www.jdoodle.com/h/1ZM I had to reconstruct the pure JS version from a slightly older one because I didn't save the version that I made just before shifting to WASM. I'm pretty sure that I had it at just about 60 million/second, but it's running closer to 50 million/second. Maybe I missed something small, idk. (Note: The arrays are saved as Int32Array as a performance optimization) Test settings (10 million/frame): Rules: L Delay: 0 Steps: 10000000 Width: 2 Height: 2
I think more interesting would be to encode the two states (0, 1) as (negative, positive). That way to flip the state you literally just have to flip the sign. Further more we could encode how often we visit the same pixel by incrementing (/ decrementing) the pixel value. Now you can use a color code to draw the pixels. I guess we should still draw the "background" either black or white and the "foreground" with our color based on the cells value. state = grid[x][y]; // flipping state = -state; // increment only when positive if (state >= 0) state++; grid[x][y] = state; The "(state >= 0)" condition also takes care of the initial "0" in the array. So " 0" is considered black (foreground)
The reason why the image is rotated is because of the initial direction of the ant, if the ant dir is set to 0(up), then the first move will set the dir to 1(right) which makes the image rotated -90 degrees, so the initial dir should be 3(left) so that the first move will be upwards but not to the right.
Great video as always, speaking of "ants" could you do a video on an ant colony optimisation algorithm to follow up on your genetic algorithm and machine learning series.
I did this myself, and I thought I should see if you made a video on it! You actually did! I totally could've used this when making Langton's Ant haha.
same, my code is PVector pos, move; int spacing = 25; color white = color(255); color black = color(0); void setup(){ size(1000,1000, P2D); rectMode(CENTER); background(255); noStroke(); pos = new PVector(width/2,height/2); move = new PVector(0, -spacing); } void draw(){ color c = get(floor(pos.x), floor(pos.y)); if (c == white){ move.rotate(-HALF_PI); fill(black); rect(pos.x,pos.y,spacing, spacing); pos.add(move); } if (c == black){ move.rotate(HALF_PI); fill(white); rect(pos.x,pos.y,spacing,spacing); pos.add(move); } }
Cool video, Dan. But one of the really amazing and fun things about Langton's Ant is what happens when there are two or more ants running around and interacting. Also, how to accept user input to set the initial position and direction of the ants. Maybe a followup video?
Yes, I had meant to mention this is an exercise for the user to try but somehow forgot. Thanks for the comment I'm going to pin it! (And yes, I should follow up on this too.)
Daniel is an awesome creative and ( perhaps too ) energetic person ( ok I'm kidding ). Superb dancer, but most importantly a good teacher and very inspiring. Oh yeah, a good writer/author, if you haven't already if you are a sincere fledgling Processing enthusiast you should check out his writings/ books etc.
Love the videos! You should consider using an enumeration for the direction and/or the state of each cell. You could have up,down,left,right for directions and on,off,ant for cell state.
My first coding challenge. *Ant colony particle swarm optimization* 1. All ants should search food randomly from their nest. 2. Each ant should create trail of pheromone after finding food from food source to nest 2. The Pheromone should evaporating after some seconds 3. As the concentration of pheromone or trail from ants nest to food source increases all ants should follow this trail of concentrated pheromones. 4. This trail of concentrated pheromone must shortest path from nest to food source. *I am saying about mimic real ants. I believes it will be a great challenge for you. Sorry for my bad English.*
_Emboldened words are edits_ I just made a version of this in the *online* p5 editor! I added some features like presets, multiple ants, and a generation counter. ( editor.p5js.org/OrangeC7/sketches/Sy0wACPiQ ) (I got the multiple ant idea with objects idea from this guy: th-cam.com/video/G1EgjgMo48U/w-d-xo.html&lc=UgyUDCU5lxCHRM8aib14AaABAg ) The program prints the starting positions of the ants (for when it's randomized) so they can be recorded for later and used as a preset (the code explains how to do that) Thanks for reading this and checking it out! :D P.S.: I was going to add a feature where the black pixels would instead be coloured based on the ant that last placed it, but it would require me to basically rewrite how the grid functions which would be hard to do since pretty much everything else is based on the grid. (._.*)
Even though this is old video but came here from one of the Dust video. This is really interesting! Why is it always making a highway after the 11000 steps? Any reason or hypothesis? 🤔
Couldn't left and right turn be done using one variable for direction? like int AntDir = 0 //or 1,2,3 depending on clockwise direction then using increment/decrement and modulo to cycle through them? would've been easier and clearer imo.
Unfortunately Java implements modulo funnily, if you take the modulo of a negative number it returns the same number. For example: -5%10 = -5 Whereas in other languages it would be 5. js also does it in the funny way too.
Why use modulus when a logical and would work? It's only using the bottom two bits of the direction. If it uses the third it's in an overflow/underflow condition and using a logical and should always create the correct value in less cycles.
I implemented colors by adding another layer of depth to the grid array, so that it's [y][x][filled?, color in hex] (x and y switched in case I want to rotate the array, don't have a use for it yet), with the colors being stored in a separate array. When the ant moves on a tile, the tile's color gets increased by one, up to the length of the color array, after which it's maxed out at colorArray.length - 1. imgur.com/03xSczh @ 11k cycles imgur.com/UYLpny4 @ 1M cycles Also, distribution graph of colors over cycles (not counting empty tiles) @ 1M cycles imgur.com/Kn27MjY btw, love your videos.
For wrapping around the Grid, should it not have been if x >= width? I noticed you accounted for the other case of setting x = width-1, but technically the other way the ant would go one pixel off screen no? (Apologies if you say this in the next few mins of video lol)
I tried to make it do as many updates as possible, and it was able to do more than 40 000 000 updates a second about 60 000 updates a frame :D ma computa is fast
I tried to use html canvas. I have seen various directions and wrap, just not at the same time. Why won't updates catch it in its state? Here is what I have if it will fit... // Not Quite Langton's Ant Coding Challenge ANTW=ANTH=4; ANTX=ANTY=200; v=5; DIR=[1,2,3,4,5]; window.onload=function() { c=document.getElementById('gc'); cc=c.getContext('2d'); setInterval(update,1000/100); ANTX=c.width/2; ANTY=c.height/2; } function update() { ANTX+=0; ANTY-=5; DIR=1; if (DIR === 1) { DIR+=1; ANTX+=0; ANTY+=5; turnRight(); } else if (DIR === 2) { DIR+=1; ANTX-=5; ANTY+=0; turnRight(); } else if (DIR === 3) { DIR+=1; ANTX+=0; ANTY-=5; turnRight(); } else if (DIR === 4) { DIR+=1; ANTX+=5; ANTY+=0; turnRight(); } if (ANTX > c.width-5) { ANTX=5; } else if (ANTX < 5) { ANTX=c.width-5; } else if (ANTY > c.height-5) { ANTY=5; } else if (ANTY < 5) { ANTY=c.height-5; } function turnRight() { if (DIR > 4) { DIR-=4; } return DIR; } cc.fillStyle='black'; cc.fillRect(0,0,c.width,c.height); cc.fillStyle='red'; cc.fillRect(ANTX-ANTW/2,ANTY-ANTH/2,ANTW,ANTH); } Presently, the red dot just sits there. That is what it was doing when I started several hours ago! If you would help that would be awesome.... And by the way, from the main image I though the ant would crawl diagonally over an image to turn it into a semi 3-D line drawing. Would that be awesome? Anyway, thanks for all these great videos!
Why use anything provided to you by the programming language when you can just hack away at the keyboard until the spaghetti ends up producing a result!
Sean Franklin Admittedly, this is intended more to get people interested in coding and show them how it works then to be highly professional; accessibility is high priority here. Just look at the number of comments on pretty much any of his videos saying that so-and-so doesn’t know programming but enjoys watching him anyways, or that somebody became interested in programming because of him; that aspect of reaching out to laymen would be gone. I’ll admit he is pretty all over the place in this one, but I can forgive him for that.
Need help, in this code, when x becomes larger than 255, why is the fill color still white? int x; void setup() { size(200, 200); surface.setResizable(true); smooth(); frameRate(60); x = 0; } void draw() { rectMode(CENTER); stroke(255, 0, 0); strokeWeight(5); fill(x); rect(width/2, height/2, 100, 100); x++; if(x > 255){ rect(100,100,20,20); } }
Hi daniel, do u have any good tips on how to become better with js ive just begon with it and the books said that ive must practice al lot i want to do that but i dont know where i sould start.
Just tried it my self - 106 Lines, the area wrap around, '+' and '-' to change the speed, 'Space' to let it run as fast as it can, and highlighting of the ant. it can do roughly 25 million iterations a second. was kinda fun using processing again for such a silly thing.
Thanks so much for doing these videos, Dan! I didn't know about Langton's Ant before and I love that you present some of these "well known" concepts in your Coding Challenges! I have a few suggestions regarding the optimization of the code though - I felt like you were kinda all over the place in this coding challenge. :'D (no offense) You don't actually need to create a PImage, because you can just use the pixels array of the program itself. Also we only need to do background(255) once in the setup() instead of every frame because we don't want to redraw everything every time. When you were talking about optimization, the first thing that came to my mind was just changing the colorMode to (RGB, 1) so you don't need the grid array anymore! I quickly wrote my version of the same program, if anyone wants to take a look at it: pastebin.com/YWd1CdZX Btw maybe someone knows this: I also tried to just put noSmooth() in the setup() and then draw a point(x, y) with either stroke(0) or stroke(1) in the draw loop, but it didn't really work the same way and I couldn't figure out why it wouldn't do the exact same thing as setting the pixel manually. Any suggestions?
at 7:00, I have a question about which would be the difference between using ifs and switch... wouldnt the result be the same? Also, just before he was talking about using modulus instead of the ifs also... whats the point of that? wouldnt the result be the same? I sometimes do some silly programs for microcontrollers and always had these doubts... Another one is: is there a problem updating a variable (to a same value) for each computer cycle? because, of course, we can add an if statement to jump it. But is there a pratical difference about these 2 situations?
@@TheCodingTrain Actually, it is not. Logically, it may seem the same, but there is a difference between if/else and switch-case. The instruction for performing a conditional jump takes 2 machine cycles if the condition is not met, and 3 if it is met. An if-else statement will jump to the end of each body if the condition is not met, while a switch-case will jump to a body if the condition is met. For example, let's say it were the 4th condition that was met (I will exclude the comparison, and only count the conditional jump instruction's time) if-else: 3 3 3 2 switch-case: 2 2 2 3 And when a switch-case doesn't test each condition, it uses an array of addresses for each condition, and jumps to one of these by index. This is especially efficient if the switch-case uses consecutive conditions, for example, [0, 1, 2, 3, 4, 5, 6...], but make no mistake, a switch-case and if-else are NOT the same. Switch-case is just slightly faster.
I made this a long time ago and forgot to post it! I made a processing sketch that takes langton's ant, and uses it as a paintbrush with ever slightly shifting colors that create some neat looking images! I did it in a short amount of time so please forgive the sloppy code. Here is the link to my github repository: github.com/Leighzer/Langtons_Paint_Brush
I wrote this in p5 and after a while it will eventually just fill the screen (I just counted, and it took 3 million moves to fill the 400x400 screen) It only takes a minute and a half to do that, with output to screen every 10,000 moves.
He's using Processing, which makes it really easy to make graphical applications by abstracting a lot of the boilerplate of java. Processing doesn't need a main method, it uses setup and draw methods instead
If you have two ants, they create interesting patterns depending on their positions. As well as the hive (blob) - highway (diagonal line) pattern, they can run a create/destroy loop on a partial hive, or they can start chasing each other in an expanding-collapsing diamond pattern.
It is worth creating an Ant class to support that. You can then extend that to encode the turn behaviour (left, right, no change, 180deg) and/or what colour to change to. These create some interesting behaviours -- I've had some ant variants build a "super highway" of a certain colour in a straight line, then zoom along it (using the "no change" turn rule). Combining ants with different rules is also interesting (but they need to support the same number of colours, otherwise they will stop if they get to an unsupported colour).
You could also extend this to support Turmites (en.wikipedia.org/wiki/Turmite), who's behaviour depends on their state as well as the cell colour.
This is such good info thank you! I should definitely do a follow-up!
I'd love to see a Langton's Ant Part 2! After I saw the video about it on Numberphile, I made it on my graphing calculator lol.
I made a video of Langton's ants "fighting", it's on my channel if anyone's interested :)
if an ant enters an ant tile add another ant!
Langton's Car. Set all pixels positions on screen to a random value of either 0,1,2, or 3. Set a particle "car" in the middle with an arbitrary velocity vector. On each frame, the car will move to a new position.
if the pixel is 0, increase speed slightly, but never more than maxSpeed.
If the pixel is 1, angle slightly to the right.
If the pixel is 2, decrease speed slightly, but never less than 1.
If the pixel is 3, angle slightly to the left.
Reset the pixel it's on to a new random value so no infinite loops occur, and then update position.
For bonus points, set up a "garage" somewhere (3 sides of a rectangle), and see if the car can drive into it. If you increase the increment of the angle to 90 degrees left or right, the car will drift sideways for a few frames before correcting. Add tire squealing sound effects as needed.
Cool suggestion!
This is a very elaborate comment. Can you do it and just show us the result
Instead of that single direction variable (and the 4 constants and that huge movement function) when just using a vector (dirX, dirY) everything becomes much simpler. Rotating is just swapping dirX and dirY and inverting one of them. Which you invert defines the direction you're rotating.
The movement is just adding dirX to x and dirY to y. Of course we still need the screen edge wrapping.
Something like this:
void Turn(boolean turnRight) {
int tmp = dirX;
if (turnRight) {
dirX = -dirY;
dirY = tmp;
} else {
dirX = dirY;
dirY = -tmp;
}
}
void moveForward() {
x = (x + dirX + width) % width;
y = (y + dirY + height) % height;
}
My favorite way to set variables from a 1 or 0 value like this is doing (in this case)
int color = grid[x][y]*255
Since if its 0, it'll be 0 and if its 1, it'll be 255
Nice improvement!
Normalize a value
:0
I never though you could do that ..thanks for the trick!
I like the beard, man! Your videos are always welcome!
One way I implemented turning was with an array in js:
direction = [0, -1, 0, 1]
Then using some array management:
direction.unshift(direction.pop()) // turns one way
if (isWhite(img, loc.x + 1, loc.y + 1)) {
direction.push(direction.shift()) // if white, turn right (undoes the first turn that always happens)
direction.push(direction.shift()) // then turns again, effectively turning the way we wanted for this situation
Then if you play with the direction variable values you can come up with some really neat patterns some are just loosely similar to Langton's ant, and others are bizarre recursive/fractal patterns.
Loved this video. Fun inspiration, and had fun writing it for myself in p5!
When I made it, I did the same, but I used a 4 number array representing the amount to change the ant's index (As I had it represented by a position in a 1d array of the grid), and had a variable that would range from 0 to 3 representing the direction. When the ant would move, it would use the direction as an index for the aforementioned array, and that would be the amount it changes it's position by. For turning, I had an array of +1 and -1 representing right and left respectively, and using the value of the cell the ant moves into (post-step) as an index for this array, I would change the direction variable. So it would either increase by 1, or decrease by 1. Before assigning it, I would perform a bitwise AND operation on it with 0b11 (3) so that if it became -1, it would change to 3.
My goal was to write it in JS while optimizing the absolute hell out of it, to the best of my ability, so that it would run as fast as possible in a webpage. With just JS, I got it to 80 million steps/second (Capped by Chrome), and with WebAssembly, I got it to 200 million/second.
With WebAssembly: www.jdoodle.com/h/1Yw
With pure JS: www.jdoodle.com/h/1ZM
I had to reconstruct the pure JS version from a slightly older one because I didn't save the version that I made just before shifting to WASM. I'm pretty sure that I had it at just about 60 million/second, but it's running closer to 50 million/second. Maybe I missed something small, idk. (Note: The arrays are saved as Int32Array as a performance optimization)
Test settings (10 million/frame):
Rules: L
Delay: 0
Steps: 10000000
Width: 2
Height: 2
I don't even do that much coding, but this is so much fun and so very useful!
I think more interesting would be to encode the two states (0, 1) as (negative, positive). That way to flip the state you literally just have to flip the sign. Further more we could encode how often we visit the same pixel by incrementing (/ decrementing) the pixel value. Now you can use a color code to draw the pixels. I guess we should still draw the "background" either black or white and the "foreground" with our color based on the cells value.
state = grid[x][y];
// flipping
state = -state;
// increment only when positive
if (state >= 0)
state++;
grid[x][y] = state;
The "(state >= 0)" condition also takes care of the initial "0" in the array. So " 0" is considered black (foreground)
I'm a simple man, I see new coding train video, I like.
Finally! Processing is back,boys! :D :D
I discovered Processing at the same time I heard Support for Java is ending...
Chris Hawker lol
Alright! This challenge was my suggestion! Thanks Daniel
Yay!
In JavaScript, I got it to run at 80 million steps/second, and including WebAssembly, I got it to 200 million/second.
The reason why the image is rotated is because of the initial direction of the ant, if the ant dir is set to 0(up), then the first move will set the dir to 1(right) which makes the image rotated -90 degrees, so the initial dir should be 3(left) so that the first move will be upwards but not to the right.
Great video as always, speaking of "ants" could you do a video on an ant colony optimisation algorithm to follow up on your genetic algorithm and machine learning series.
I did this myself, and I thought I should see if you made a video on it! You actually did! I totally could've used this when making Langton's Ant haha.
I made it check the pixel's color, and then put a little rectangle to replace the color that the ant was just on.
same, my code is
PVector pos, move;
int spacing = 25;
color white = color(255);
color black = color(0);
void setup(){
size(1000,1000, P2D);
rectMode(CENTER);
background(255);
noStroke();
pos = new PVector(width/2,height/2);
move = new PVector(0, -spacing);
}
void draw(){
color c = get(floor(pos.x), floor(pos.y));
if (c == white){
move.rotate(-HALF_PI);
fill(black);
rect(pos.x,pos.y,spacing, spacing);
pos.add(move);
}
if (c == black){
move.rotate(HALF_PI);
fill(white);
rect(pos.x,pos.y,spacing,spacing);
pos.add(move);
}
}
I've been going through the entire Internet looking for this, I build this in minecraft but couldn't remember what it was called
These are my favorite kinds of Coding Train videos!
Cool video, Dan. But one of the really amazing and fun things about Langton's Ant is what happens when there are two or more ants running around and interacting. Also, how to accept user input to set the initial position and direction of the ants. Maybe a followup video?
Yes, I had meant to mention this is an exercise for the user to try but somehow forgot. Thanks for the comment I'm going to pin it! (And yes, I should follow up on this too.)
I played a pixel game and the ants made the same patterns, never knew it was this!
Daniel is an awesome creative and ( perhaps too ) energetic person ( ok I'm kidding ).
Superb dancer, but most importantly a good teacher and very inspiring. Oh yeah, a good writer/author, if you haven't already if you are a sincere fledgling Processing enthusiast you should check out his writings/ books etc.
nicely done. Really very intuitive way to learn all these. Thanks and keep up the good work.
in line 82, u just can set the color inside the if statments, so u dont need to chek grid[x][y] twice, u already chek in the state == 0;
Love the videos! You should consider using an enumeration for the direction and/or the state of each cell. You could have up,down,left,right for directions and on,off,ant for cell state.
Yes, a good point, thanks for the tip!
My first coding challenge.
*Ant colony particle swarm optimization*
1. All ants should search food randomly from their nest.
2. Each ant should create trail of pheromone after finding food from food source to nest
2. The Pheromone should evaporating after some seconds
3. As the concentration of pheromone or trail from ants nest to food source increases all ants should follow this trail of concentrated pheromones.
4. This trail of concentrated pheromone must shortest path from nest to food source.
*I am saying about mimic real ants. I believes it will be a great challenge for you. Sorry for my bad English.*
Please suggest here! github.com/CodingTrain/Rainbow-Topics/issues
@@TheCodingTrain Hey... Hey I made an issue on GitHub after commenting here... Waiting...
Whatever you do, don't implement Langton's uncle
12:32 That "YEA" was amazing :D :d
_Emboldened words are edits_
I just made a version of this in the *online* p5 editor! I added some features like presets, multiple ants, and a generation counter. ( editor.p5js.org/OrangeC7/sketches/Sy0wACPiQ )
(I got the multiple ant idea with objects idea from this guy: th-cam.com/video/G1EgjgMo48U/w-d-xo.html&lc=UgyUDCU5lxCHRM8aib14AaABAg )
The program prints the starting positions of the ants (for when it's randomized) so they can be recorded for later and used as a preset (the code explains how to do that)
Thanks for reading this and checking it out! :D
P.S.: I was going to add a feature where the black pixels would instead be coloured based on the ant that last placed it, but it would require me to basically rewrite how the grid functions which would be hard to do since pretty much everything else is based on the grid. (._.*)
Thank you for sharing this educational videos with us! I wish I had you as my professor at university
omg 19:20 made me really happy ahahahaha
You should code something to generate a few layers of the Hilbert Curve.
Will you ever do a video on geometric flows like curve-shortening, mean-curvature, or Ricci flow?
Even though this is old video but came here from one of the Dust video. This is really interesting! Why is it always making a highway after the 11000 steps? Any reason or hypothesis? 🤔
Couldn't left and right turn be done using one variable for direction? like
int AntDir = 0 //or 1,2,3 depending on clockwise direction
then using increment/decrement and modulo to cycle through them? would've been easier and clearer imo.
Part of the video is giving the viewer the opportunity to learn how to do things better.
Yes, a great improvement!
Unfortunately Java implements modulo funnily, if you take the modulo of a negative number it returns the same number. For example:
-5%10 = -5
Whereas in other languages it would be 5.
js also does it in the funny way too.
you could just take the absolute of the mod then
Thanatos 12321 Or not use 0,1,2,3. Have the directions start at anything above 0 modulo (weird Java modulo) should work then, right?
Awesome videos man! Keep it up!
Why use modulus when a logical and would work? It's only using the bottom two bits of the direction. If it uses the third it's in an overflow/underflow condition and using a logical and should always create the correct value in less cycles.
Thanks for this suggestion!
I implemented colors by adding another layer of depth to the grid array, so that it's [y][x][filled?, color in hex] (x and y switched in case I want to rotate the array, don't have a use for it yet), with the colors being stored in a separate array. When the ant moves on a tile, the tile's color gets increased by one, up to the length of the color array, after which it's maxed out at colorArray.length - 1.
imgur.com/03xSczh @ 11k cycles
imgur.com/UYLpny4 @ 1M cycles
Also, distribution graph of colors over cycles (not counting empty tiles) @ 1M cycles imgur.com/Kn27MjY
btw, love your videos.
In python you could have just used a dict of all the points where the grid is 1. Way less processing power and storage required.
I love the p5.js series also :)
Love this Atamata!
I would have named constants ANTNORTH ANTEAST, etc. to avoid confusion with left and right.
Use dx and dy for changing direction
For wrapping around the Grid, should it not have been if x >= width? I noticed you accounted for the other case of setting x = width-1, but technically the other way the ant would go one pixel off screen no?
(Apologies if you say this in the next few mins of video lol)
Yep, you did find it later on. Good job man! These challenges are super cool to watch!
I tried to make it do as many updates as possible, and it was able to do more than 40 000 000 updates a second about 60 000 updates a frame :D
ma computa is fast
RIP garbage collector xD 🎵 we will refactor this later🎵
Keep up the good work man
I tried to use html canvas. I have seen various directions and wrap, just not at the same time. Why won't updates catch it in its state?
Here is what I have if it will fit...
// Not Quite Langton's Ant Coding Challenge
ANTW=ANTH=4;
ANTX=ANTY=200;
v=5;
DIR=[1,2,3,4,5];
window.onload=function() {
c=document.getElementById('gc');
cc=c.getContext('2d');
setInterval(update,1000/100);
ANTX=c.width/2;
ANTY=c.height/2;
}
function update() {
ANTX+=0;
ANTY-=5;
DIR=1;
if (DIR === 1) {
DIR+=1;
ANTX+=0;
ANTY+=5;
turnRight();
} else if (DIR === 2) {
DIR+=1;
ANTX-=5;
ANTY+=0;
turnRight();
} else if (DIR === 3) {
DIR+=1;
ANTX+=0;
ANTY-=5;
turnRight();
} else if (DIR === 4) {
DIR+=1;
ANTX+=5;
ANTY+=0;
turnRight();
}
if (ANTX > c.width-5) {
ANTX=5;
} else if (ANTX < 5) {
ANTX=c.width-5;
} else if (ANTY > c.height-5) {
ANTY=5;
} else if (ANTY < 5) {
ANTY=c.height-5;
}
function turnRight() {
if (DIR > 4) {
DIR-=4;
}
return DIR;
}
cc.fillStyle='black';
cc.fillRect(0,0,c.width,c.height);
cc.fillStyle='red';
cc.fillRect(ANTX-ANTW/2,ANTY-ANTH/2,ANTW,ANTH);
}
Presently, the red dot just sits there. That is what it was doing when I started several hours ago! If you would help that would be awesome....
And by the way, from the main image I though the ant would crawl diagonally over an image to turn it into a semi 3-D line drawing. Would that be awesome?
Anyway, thanks for all these great videos!
Why use anything provided to you by the programming language when you can just hack away at the keyboard until the spaghetti ends up producing a result!
Sean Franklin Admittedly, this is intended more to get people interested in coding and show them how it works then to be highly professional; accessibility is high priority here. Just look at the number of comments on pretty much any of his videos saying that so-and-so doesn’t know programming but enjoys watching him anyways, or that somebody became interested in programming because of him; that aspect of reaching out to laymen would be gone. I’ll admit he is pretty all over the place in this one, but I can forgive him for that.
I really enjoyed watch you code but you mention a lot how you could do things better, I'd love to see those methods too.
Why make the grid ints when only storing a 1 or 0, why not Boolean??
Cool! Seems a little complicated though :D
whatt dou?? this is magic man... i can't even seem to realize what he's doing.
Need help, in this code, when x becomes larger than 255, why is the fill color still white?
int x;
void setup() {
size(200, 200);
surface.setResizable(true);
smooth();
frameRate(60);
x = 0;
}
void draw() {
rectMode(CENTER);
stroke(255, 0, 0);
strokeWeight(5);
fill(x);
rect(width/2, height/2, 100, 100);
x++;
if(x > 255){
rect(100,100,20,20);
}
}
Because you have a fill(255) so every rect is going to be white. If you want to fill black put a fill(0) inside the if (x>255)
oh mistyped, imagine if x were in the place of that 255
Hi daniel, do u have any good tips on how to become better with js ive just begon with it and the books said that ive must practice al lot i want to do that but i dont know where i sould start.
Just tried it my self - 106 Lines, the area wrap around, '+' and '-' to change the speed, 'Space' to let it run as fast as it can, and highlighting of the ant.
it can do roughly 25 million iterations a second. was kinda fun using processing again for such a silly thing.
That's so cool!
Thanks so much for doing these videos, Dan!
I didn't know about Langton's Ant before and I love that you present some of these "well known" concepts in your Coding Challenges!
I have a few suggestions regarding the optimization of the code though - I felt like you were kinda all over the place in this coding challenge. :'D (no offense)
You don't actually need to create a PImage, because you can just use the pixels array of the program itself. Also we only need to do background(255) once in the setup() instead of every frame because we don't want to redraw everything every time.
When you were talking about optimization, the first thing that came to my mind was just changing the colorMode to (RGB, 1) so you don't need the grid array anymore!
I quickly wrote my version of the same program, if anyone wants to take a look at it: pastebin.com/YWd1CdZX
Btw maybe someone knows this:
I also tried to just put noSmooth() in the setup() and then draw a point(x, y) with either stroke(0) or stroke(1) in the draw loop, but it didn't really work the same way and I couldn't figure out why it wouldn't do the exact same thing as setting the pixel manually. Any suggestions?
Thanks for these great suggestions!
at 7:00, I have a question about which would be the difference between using ifs and switch... wouldnt the result be the same? Also, just before he was talking about using modulus instead of the ifs also... whats the point of that? wouldnt the result be the same? I sometimes do some silly programs for microcontrollers and always had these doubts... Another one is: is there a problem updating a variable (to a same value) for each computer cycle? because, of course, we can add an if statement to jump it. But is there a pratical difference about these 2 situations?
Yes, a switch statement is just concise syntax for a certain kind of if statement, but the result is exactly the same!
@@TheCodingTrain Actually, it is not. Logically, it may seem the same, but there is a difference between if/else and switch-case. The instruction for performing a conditional jump takes 2 machine cycles if the condition is not met, and 3 if it is met. An if-else statement will jump to the end of each body if the condition is not met, while a switch-case will jump to a body if the condition is met. For example, let's say it were the 4th condition that was met (I will exclude the comparison, and only count the conditional jump instruction's time)
if-else:
3
3
3
2
switch-case:
2
2
2
3
And when a switch-case doesn't test each condition, it uses an array of addresses for each condition, and jumps to one of these by index. This is especially efficient if the switch-case uses consecutive conditions, for example, [0, 1, 2, 3, 4, 5, 6...], but make no mistake, a switch-case and if-else are NOT the same. Switch-case is just slightly faster.
Processing is back!!
That was quite awesome
Are you writing in Java w/ processing library included? Or Javascript with p5?
yes yes i know this comment is a yer old but i dont care
hes coding in java not js
How to use modulus to account for the edges?
Hey! Quick question, would Sublime Text or Atom work with this code or should I just use processing?
I used Atom, using the p5/javascript version of processing.
Couldn't you use an eNUM for the instead of the integers for the way that it's facing?
Yes, a good point! I tend to be informal about these sorts of things and refactor later.
i created it using js, framerate is too low. It's gonna take an eternity to get to the highway.
:(
What resolution do you have on your screen???
How on earth do you find all these algorithms?
Sam DeLong Go Wikipedia, search for "AI", click around.
19:16 "and run it", screen goes black, ad break.
Thats what i asked for thanks
what a smart ant...
It will be cool when you will make some videos with pure Java, not Processing but like real Java.
Here is my version of Langton's ant in Processing...
github.com/ccosnean/Langton_s_ant.git
Ahh, these diagonal lines..
I'd change it to bounce off the wall, so it changes direction more often.
5:49 eww use some modulus operators (%) plz
I made this a long time ago and forgot to post it! I made a processing sketch that takes langton's ant, and uses it as a paintbrush with ever slightly shifting colors that create some neat looking images! I did it in a short amount of time so please forgive the sloppy code.
Here is the link to my github repository: github.com/Leighzer/Langtons_Paint_Brush
Nice work! You can submit a link to the coding train website if you like!
github.com/CodingTrain/website/wiki/Community-Contributions-Guide
How do you find these coding challenges?
People suggest here! github.com/CodingTrain/Rainbow-Topics/issues
Kinda want to see what that looks like after you've let it run for a day or two.
I wrote this in p5 and after a while it will eventually just fill the screen (I just counted, and it took 3 million moves to fill the 400x400 screen) It only takes a minute and a half to do that, with output to screen every 10,000 moves.
TMW you coded Langton's ant before Dan did :O
Also TMW your code was more complicated than his
Who is Dan?
@@KnakuanaRka Dan is Dan Shiffman... the guy in the video
Did anybody else spot that Langton's ant was giving you the bird?
how can you write those two functions (turnRight and turnLeft) in one line of code?
If you know which way to turn (-1 for left, +1 for right) you could do this:
dir = (dir + turn) % 4;
I think you'd have to say:
dir = (dir + 4 + turn) % 4;
Otherwise it won't work with dir = 0 and turn = -1.
The Coding Train Thanks for pointing that out! You are right, forgot how modulus works in Java :)
@@danielgrunkin8705 Or, you can use "& 0b11" instead of % 4 to avoid that problem. Then you could ditch the + 4
Coding challenge: Implement QLearning without using any ml libraries
thanks!
10:51 R.I.P. Bitrate
col = 255 * grid[x][y]
:)
Didn't see any comment like this lol
Why is it mirrored
The direction the ant will move in diagonally depends on which direction it is facing initially (north, south, east, or west).
I've ants in my room :(
:(
Dat Epic Beard Tho
new sub!!!
JavaScript version?
You'll find it here! thecodingtrain.com/CodingChallenges/089-langtonsant.html
Can you do tic tac toe game in p5.js or something like that. Who agrees!
His hair has a bit more floof than usual
I'm made Langton's ant on scratch which is kid coding drag n drop bock code thing!
You hatred my thing cool
19 th like.....keep up the good work, Dan, love yr videos,.////////
Yeah, Processing. Do fullScreen() please.
idk why but for some reason I feel like I could turn this into a pseudorandom number generator.
I love this idea!
Processing :)
wait a second, are you using java? if so, you didn't have a main class, how is that even working?
He's using Processing, which makes it really easy to make graphical applications by abstracting a lot of the boilerplate of java. Processing doesn't need a main method, it uses setup and draw methods instead
Thanks! I scratched my head around for a bit on that one.
No problem! I'd highly recommend checking out processing, it's super useful and really easy to use
I'll stick with p5
Can you make this in JavaScript also?
I'm planning on uploading a JS version today, stay tuned!
YO Itachi whats up? Dattebayo!
MODULUS! :p
coding channel inspired me to jave my own channel
my channel is basic version of javascript
Hola