How to Win Snake: The UNKILLABLE Snake AI

Поделиться
HTML-код
  • Опубликовано: 10 июн 2024
  • I watched the CodeBullet Snake AI video on the morning after Thanksgiving and spent WAAAAYY too much time working on an AI of my own. I present to you: Snake, as played algorithmically with Dynamic Hamiltonian Cycle Repair. The snake can never die - like really, actually, literally, can't be killed - it's just a matter of how fast it wins the game…
    If you, like me, enjoy watching snakes run around eating apples for hours on end, enjoy this follow-up where I took the median-length game from my best performing algorithm and posted the whole darn thing on RUclips:
    • The UNKILLABLE Snake A...
    Check out the other social media for updates and ramblings:
    / alphaphoenixchannel
    / alpha__phoenix
    #Snake #AI #Math
    CODE!
    github.com/BrianHaidet/AlphaP...
    Snake References:
    @CodeBullet
    CodeBullet's (Most recent) snake video: • I Created a PERFECT SN...
    @johnflux1
    John Tapsell's Nokia snake project: johnflux.com/2015/05/02/nokia...
    Mathworks File Exchange Reference:
    A* code originally written by Einar Ueland
    www.mathworks.com/matlabcentr...
    Actual MATH Papers:
    mathworld.wolfram.com/GridGrap...
    epubs.siam.org/doi/10.1137/02...
    www.cs.technion.ac.il/~itai/pu...
    drops.dagstuhl.de/opus/vollte...
    link.springer.com/chapter/10....
    arxiv.org/pdf/1008.0541v1.pdf
    arxiv.org/pdf/1707.05994.pdf
    onlinelibrary-wiley-com.proxy...
    www.sciencedirect.com/science...
    en.wikipedia.org/wiki/Hamilto...
    citeseerx.ist.psu.edu/viewdoc/...
    weber.itn.liu.se/~valpo40/page...
    www.sciencedirect.com/science...
    www.sciencedirect.com/science...
    Other clips in this video:
    xkcd.com/356/
    Morbo "Dooom" (Futurama)
    "That's Illegal" meme (Red vs. Blue)
    Music in this video:
    I Dunno by grapes is licensed under a Creative Commons Attribution license (creativecommons.org/licenses/...)
    ccmixter.org/files/grapes/16626
  • НаукаНаука

Комментарии • 1,3 тыс.

  • @AlphaPhoenixChannel
    @AlphaPhoenixChannel  3 года назад +1952

    Wanted to let everybody know that I've been solidly shown up by a viewer! Twan was able to improve on my method by a massive 20% using a locally-gridded movement scheme that scales as well or better than my method (to my understanding there's still one 2D step that's akin to blobfinding). The snake only moves according to certain rules, which effectively places the snake into a subset of possible graph spaces that are MUCH easier to check for hamiltonicity. It was a broad concept I kicked around while working on this project but never thought up an implementable solution.
    I don't think it's on youtube anywhere, but there's a beautiful video of it running here: github.com/twanvl/snake/

    • @fanisgikas4753
      @fanisgikas4753 3 года назад +60

      Congratulations on your channel. I am from Greece , I do not speak English and this text is from a Google translation. Your video inspired me to deal again with a snake game for excel that I had created 2 years ago. From my tests I concluded that you can reduce the final movements by more than 20% with a simple trick, to set as a tail a virtual tail in half, or at any other point you wish, of the snake's body. with this technique you drastically reduce the unnecessary movements to fill the inaccessible area.. Ιn my tests so far the game on a 20x20 surface ends with an average of 10.200 moves with a higher 11.100 and a lower 8.950 with zero failures

    • @nater9178
      @nater9178 2 года назад +29

      Also, you don’t need to check for a mapwide path until the snake is longer then half the board, so a separate algorithm could control the first “half” of the game.

    • @twanboltze8196
      @twanboltze8196 2 года назад +5

      Whut

    • @Benw8888
      @Benw8888 2 года назад +15

      I'd be extremely eager to see you make a video on your viewer's results! Perhaps you could collab or ask the viewer for permission to make a (shorter) follow up video?

    • @greengoblin9567
      @greengoblin9567 2 года назад +7

      Very elegant algorithm. Keep up the good work. This kind of hard coding should be used more with ai and neural nets. This blew the neural nets out of the water. Keep up the good work.

  • @Pklose75
    @Pklose75 2 года назад +1594

    "I underestimated what NP-Hard really meant" spoke to me on a spiritual level.

    • @rykehuss3435
      @rykehuss3435 2 года назад +61

      You always underestimate it until you try to bruteforce it

    • @baronvonbeandip
      @baronvonbeandip 2 года назад +25

      NP stands for Not Plausible, after all.

    • @LucasPlay171
      @LucasPlay171 2 года назад +13

      @@rykehuss3435 you never understimate it with a potato PC like mine

    • @createnew8368
      @createnew8368 Год назад +5

      It means Not feasibly Possible

    • @DailyCorvid
      @DailyCorvid Год назад +2

      @@LucasPlay171 I just think back to AOL dial-up in 1993, on a 486-DX66 with 2MB of RAM - and I think, bruteforce technology just needs more time! At the moment the trend is creating NP-Hard based encryption. But I think in future, NP-Hard defeating bruteforce software will become all the rage !

  • @Jakub1989YTb
    @Jakub1989YTb 3 года назад +2378

    10:25 When I'm explaining to my colleague, what my algorythm does.

    • @AlphaPhoenixChannel
      @AlphaPhoenixChannel  3 года назад +291

      www.smbc-comics.com/comic/2014-02-24

    • @smileyp4535
      @smileyp4535 2 года назад +120

      @@AlphaPhoenixChannel you nerds and your applicable comics 😂 I love it

    • @memetech-
      @memetech- 2 года назад +40

      Dis day dzz daz dzz dzz
      Autocorrect had to get used to that

    • @bjnartowt
      @bjnartowt 2 года назад +13

      I mean...there's something to be said for an explanation that is both correct *and* Tweet-sized :)

    • @moothechicken8904
      @moothechicken8904 2 года назад +3

      Lol

  • @cmilkau
    @cmilkau 2 года назад +1484

    Simple optimization: the repaired hc doesn't need to contain the snake as it is NOW, it only needs to contain the snake as it WILL BE after eating the apple.

    • @JaspreetSingh-fo2qe
      @JaspreetSingh-fo2qe 2 года назад +17

      nice

    • @fraser21
      @fraser21 2 года назад +141

      I had the same idea, but I think it’s subtly not at all simple and non-trivially chaotic. If you modify the hc to include a future snake, the present snake no longer follows the hc that would predict that future.

    • @DavidSmith-bh6ez
      @DavidSmith-bh6ez 2 года назад +79

      That essentially boils down to calculating the entire entire path before taking it, which is not better (and with the current code might never terminate, whenever the snake would get stuck in a loop), or calculating all possible paths to make use of it, but that's gonna take a couple heat deaths to finish.

    • @MattWyndham
      @MattWyndham 2 года назад +6

      like david smith said, the repaired hc is actually just a tiny change to a small part of it. The snake as it is NOW still exists in the hc and so leaving it there is free, plus after eating the apple you only have one more segment of snake and nothing else has changed

    • @BaTycoon
      @BaTycoon 2 года назад +4

      @CodeBullet should feel good about this. Maybe. Sorta.

  • @STUCASHX
    @STUCASHX 2 года назад +688

    Can you imagine watching a live Snake A.I. competition where many A.I.'s are pitched against each other in 1 v 1 eliminations with the winner being the first to finish and the grids get larger as you get towards the finals?
    I think it would be pretty cool...

    • @blakceyedpeas
      @blakceyedpeas 2 года назад +25

      Some algorithms may work better at different sizes of the board, so it may be a good idea to not change the size

    • @pufthemajicdragon
      @pufthemajicdragon 2 года назад +106

      @@blakceyedpeas Or you encourage people to write generalized algorithms that work across a variety of grid sizes.

    • @XoXkS
      @XoXkS 2 года назад +54

      We did that in an university course.
      It was a modified snake games with two snakes playing against each other in the same field. You could either win by points (which did rarley happen) or win if the other snake dies. Attacking and trying to trap the other snake was allowed. Also there were power ups one could pick up and use, like moving the apple or setting a blocking wall piece.
      At the end of the course all the snakes fought against each other.
      Was a great course!

    • @user-si6wk4ij1s
      @user-si6wk4ij1s 2 года назад +24

      @@XoXkS So was it like a combination of Snake and Tron with additional boosts? Nice.

    • @stephen7715
      @stephen7715 Год назад +1

      BMTron is the game this reminds me of :)
      Played that in high school constantly

  • @BlastinRope
    @BlastinRope 2 года назад +396

    New snake mechanic: poop button that shrinks you 1/3rd but leaves a dot on the map that never disapears and you lose if you eat it

    • @regem9121
      @regem9121 2 года назад +7

      no it is win

    • @endlesswanderer1753
      @endlesswanderer1753 2 года назад +90

      Dude. Now that you mention it, I have never seen an expanded version of Snake. Out of all the hundreds of millions of snake clones, about the only variety is the Paint-roller version; where there are four or more players on a single board competing to make the other snakes collide into them.
      We need a Snake 99 now. Wait. That's just Slither io.

    • @AkariEnderwolf
      @AkariEnderwolf 2 года назад +15

      @@endlesswanderer1753 That paint roller game sounds like Tron, specifically Light Cycles.

    • @justdsaic3255
      @justdsaic3255 2 года назад +24

      @@endlesswanderer1753 what about google’s snake? That comes packed with tons of weird extra versions?

    • @shoes4clues955
      @shoes4clues955 2 года назад +11

      @@endlesswanderer1753 google snake has several different modes and has had them for years and is still being updated

  • @chancylvania
    @chancylvania 3 года назад +649

    Holy shit matlab. That’s the first time I’ve ever seen a video use matlab for which I haven’t explicitly looked up matlab.

    • @pvic6959
      @pvic6959 2 года назад +23

      as a software engineer this scares me lol. but i understand hes more comfortable with matlab as a tool

    • @chancylvania
      @chancylvania 2 года назад +10

      @@supernovahm1178 like I’ve never seen matlab used when I haven’t specifically looked up a matlab tutorial

    • @chancylvania
      @chancylvania 2 года назад +4

      @@supernovahm1178 I mean most people don’t know what matlab is. Unless you’ve used it in college people know python and others more

    • @chancylvania
      @chancylvania 2 года назад +5

      @@supernovahm1178 I don’t know what that is but it’s still a programming language.

    • @RylHango
      @RylHango 2 года назад +8

      @@supernovahm1178 implying intelligent people prefer matlab over python

  • @tf2excession
    @tf2excession 2 года назад +188

    One of the signs that you might be the type of person to get nerd sniped is if you hear "xkcd 356" and immediately recognize it as the nerd sniping xkcd.

    • @7anx2142
      @7anx2142 2 года назад +1

      uhh

    • @vilian9185
      @vilian9185 Месяц назад

      not nerd enough ​@@7anx2142

  • @Fortaker
    @Fortaker 2 года назад +115

    I'll say this: I know absolutely nothing about coding, programming, or algorithms. I did play Snake when I was a kid, but never knew how it worked. My math skills are in the gutter (like elementary school levels), and unlikely to improve anytime soon.
    But for all that, I was riveted to this video. You have a great way of instructing, and I never felt lost. I couldn't help but laugh as your snake made so many "illogical" moves (at least from a human perspective). I loved it! Great job, and I hope to see more in the future!

  • @MrBenMcLean
    @MrBenMcLean 2 года назад +37

    It immediately occurs to me that a complete Hamiltonian cycle of the empty space isn't what's actually necessary to avoid death. What's actually necessary to avoid death is for there to be some combination of future moves which could eventually reach every currently empty square. The distinction is that the Hamiltonian cycle looks only at the spaces that are empty now while the "combination of future moves" idea also allows the snake to move into spaces that will become empty from its tail moving out of them in the future. This would allow the snake to do "riskier" things to get to the apple quicker while still never dying.

  • @mullafacation
    @mullafacation 2 года назад +20

    14:12 The algorithm is like those cars at traffic lights that slowly move forward thinking that they are getting half a metre closer to wherever they want to be but then can't see the lights when they turn green so they waste more time but feel like they are going faster or if a shop opens in 5 minutes but you go on a 2 hour walk to another city.

  • @six
    @six 2 года назад +215

    This is a childhood fever dream come true

    • @RamkrishanYT
      @RamkrishanYT 2 года назад

      Get lost, another fake channel of Dan

    • @vanconojl
      @vanconojl 2 года назад

      @@RamkrishanYT Dan?

  • @tristanreid5770
    @tristanreid5770 2 года назад +52

    Saw this a few hours ago and can't stop thinking about it - I have been thoroughly sniped! I think it's useful to think of a scenario where after the next apple every single square encountered is a new apple. In that scenario if the path doesn't follow a Hamiltonion Cycle as it reaches that next apple, the game will fail. So that's the minimum requirement - that as the snake reaches the next apple, it must be guaranteed that the snake has an HC. Note that this minimum requirement is weaker than the current strategy, which is following an HC from the CURRENT position. For example, if the snake is 10 units long and the HC from the current position takes 100 moves to get to the apple, we can send the snake on the shortest non-intersecting path to the 90th step of the HC path. The reason this is guaranteed to work is that at the next time the snake is eat the apple and grow, it will be in the same position as if it had followed the whole HC path.

    • @MedoFortyTwo
      @MedoFortyTwo 2 года назад +4

      I don't think the snake necessarily needs a Hamiltonian cycle after reaching the apple. Since you can still make your choice of direction after the new apple appears (at least according to the rules I'm familiar with), you can break the chain as soon as your path past eating the next apple has a choice of direction.

    • @kindlin
      @kindlin Год назад +1

      This was actually the main thing I was thinking about as I watched this. All you actually, really need to do is go from current position to apple in a way that leaves a valid Hamiltonian. You can even do a quick check for non-Hamiltonian solutions to verify the number of squares left in that Hamiltonian is more than the length of snake cutting you off, then you can even use some half cycles that eventually connect.

  • @ShankarSivarajan
    @ShankarSivarajan 4 года назад +57

    Your channel logo is brilliant!

    • @zbytpewny
      @zbytpewny 2 года назад +2

      yes, so many levels

  • @andreamarino95
    @andreamarino95 2 года назад +21

    This was EXTREMELY pleasant to follow. Thank you sooo much! It's not common for games to be that rich of structure and still so enjoyable

  •  2 года назад +132

    "I need to plan a route ASAP to tour all the labs working on NP-hard problems!!" - I see what you did there :p

    • @MattWyndham
      @MattWyndham 2 года назад +9

      traveling salesman, classic NP-Hard problem

    • @aaaab384
      @aaaab384 2 года назад

      Why don't you people study some more? You are so ignorant.

    • @ME0WMERE
      @ME0WMERE 2 года назад +1

      @@aaaab384 what about the original comment was 'ignorant'

    • @carbonwolf1087
      @carbonwolf1087 2 года назад

      @@aaaab384 do you not understand what an NP hard problem is?

    • @fzxfzxfzx
      @fzxfzxfzx 2 года назад

      @@aaaab384 who?

  • @elvenderideas
    @elvenderideas 4 года назад +27

    Wow what a great effort on this video and the algorithmic solutions to games!

  • @rownrown
    @rownrown Год назад +2

    Well done on taking something so arcane seeming and making it accessible and interesting. You made me appreciate all the thinking, hard work and collaboration between people that goes into these ai programs

  • @dorabear3030
    @dorabear3030 2 года назад +12

    Wow, this is a really good video and very entertaining. This is the first snake AI video that discussed survivability and efficiency. Love to see some deep reinforcement learning algorithm that can achieve a similar performance but I guess a customized reward function is needed to address the balance of survivability and efficiency. I personally don't think a general RL algorithm could be as good without many handcrafted features and customization.

  • @gavin5861
    @gavin5861 2 года назад +6

    I think this IS my favorite channel I've come across, I started with the one about finding a leak in a vacuum chamber and every video since has been fantastically great at explaining ideas and concepts. They are interesting, and relitively in-depth, plus they have good craftsmanship. 10/10

  • @ByteSizedGamer
    @ByteSizedGamer 2 года назад +17

    I too believe in ‘The Of Grid’

  • @maxmotkaliuk507
    @maxmotkaliuk507 4 года назад +7

    Omg, dude! Kudos for your amazing efforts on digging into this topic. Appreciate your work on this⚡️

  • @knampf9779
    @knampf9779 10 месяцев назад +1

    Thanks for showing this. Now I can implement it in my professional snake gaming career.

  • @Grinthex
    @Grinthex 2 года назад +2

    This is awesome! It is really amazing how complex seemingly simple problems can be!

  • @lorlimann
    @lorlimann 2 года назад +34

    You give us really exceptionally great content here! Love the style and honesty of everything! That graphic at 4:50 had colors in it that made it hard to see for me as a person with mild color blindness.

    • @ufffd
      @ufffd 2 года назад

      The red and blue for the nodes and edges? Or red and green from the edges and snake?

    • @henryambrose8607
      @henryambrose8607 2 года назад

      @@ufffd Red-green is the most common form of colourblindness, so most likely that I suppose. I wouldn't be surprised if it was both of them though.

  • @skuzlebut82
    @skuzlebut82 2 года назад +14

    I remember going to Wichita State University in 2000-2001, studying Computer and Electrical Engineering. I also remember beating Snake on my Nokia phone by filling the entire screen up with my snake. Going up and down but leaving the bottom path open so I could continue the loop. I ended up enlisting in the Army and being an IT Specialist. During war, even an IT Specialist gets the opportunity to be shot at.

  • @naseemgharibi
    @naseemgharibi 2 года назад

    man this is an amazing video and explanation! I learned a lot about algorithms and how to implement them in such a game.

  • @skittstuff
    @skittstuff 2 года назад +15

    Big coding mood when you said your algorithm was great...when it worked. I felt that in my soul lmao

  • @Scrogan
    @Scrogan 4 года назад +43

    Neat video, I’ve always been interested in elegant algorithmic solutions to games. I assume you could make a machine learning AI that could get even faster than what you’ve designed if you gave it the same information you were checking for with your algorithm, but to get to that point it would likely take a long time, even longer than the full Hamiltonian cycle computation method. But if someone did do so, it would be nice to see if the resultant neural network could be viewed as an algorithm.
    I see you’re also a user of graph paper for everything, I go though the stuff like nobody’s business.

    • @AlphaPhoenixChannel
      @AlphaPhoenixChannel  4 года назад +18

      I switched to pens from pencils a few years ago and then unfortunately had to mostly switch away from graph paper cause the ink soaked through. However snake was just too perfect and I have piles of the stuff laying around xD
      I’d love to see a neural net capable of rebuilding Hamiltonian cycles. You could even do all the linear algebra on a gpu then and it would fly. I don’t know how you’d design such a structure though... interesting...

    • @antonliakhovitch8306
      @antonliakhovitch8306 2 года назад +4

      Yeah, neural networks aren't quite a magical hammer that fixes everything. In particular, they suffer from being somewhat "fuzzy" - they have a hard time thinking ahead, and they can be quite unpredictable.
      My immediate intuition tells me that you would have a very, very hard time getting a neural network to never fail. With something like this hamiltonian path fixer, it's relatively easy to prove that your algorithm will never die. With a good neural network, my suspicion is that it will do exceptionally well most of the time and then randomly die in bizarre ways every once in a while.

    • @clonkex
      @clonkex 2 года назад

      @@AlphaPhoenixChannel "I switched to pens from pencils a few years ago" Wait, that's a thing people think about? I just grab whatever's closest.

    • @dumonu
      @dumonu 2 года назад

      @@clonkex Pens just feel way smoother to write with and good pens have only two states - enough ink or not enough ink. When the second state is hit, you just get a new pen. Pencils have good, dull, broken, too short, no eraser, bad eraser, etc. Plus they feel way rougher to write with. The cited reason people prefer pencils over pens - erasability - tends not to impact much in practice. It will always be faster and easier to just scratch out a mistake than flipping over the pencil or grabbing a separate eraser. I guess when you've spent a lot of time in school or doing math, you start thinking about ways to make it easier. Or I'm just a nerd. I've also switched from lined paper to printer paper for most applications.

    • @clonkex
      @clonkex 2 года назад +1

      @@dumonu I personally find pens quite difficult to write with _because_ of how smooth they are. Every time someone says "here, sign this" and hands me a pen I have to mentally prepare so as not to go flying off the page on the first stroke.

  • @ciclotronforever
    @ciclotronforever 2 года назад +1

    I made one when i was in high school ! Not so complicated, because of my knowlege, and it runned on javaME on phones ! I'll try to dig it out to see how it performed. From what I remeber it can trap itself but it was fast because it's main mode was going strait to the apple in 2 lines, one turn ! To fine tune it i used variables and tried out a lot of settings. But un 2008 on a java platform it was painfully slow.
    Your version is great, congratulation and the video is fun, which for a programming video is not easy !

  • @ut4321
    @ut4321 2 года назад +5

    So cool! Back in the 90's, I wrote Snake inside of an IVR (interactive voice response) system. You played using DTMF tones - touch tones on a dial phone! Love seeing this kind of stuff, such fun!

  • @Jaime.02
    @Jaime.02 3 года назад +3

    Amazing work, I really appreciate it

  • @2viny713
    @2viny713 2 года назад +3

    9:35 if that was a speedrun strat it would be called a wormhole

  • @ChuckSploder
    @ChuckSploder 9 месяцев назад +1

    You can use flood fill and a time-weightmap to make it be able to predict how it can dodge its tail.
    Use flood fill to make a weightmap of how many steps it would take to reach a given location, and if the step count at the index of that weightmap during the Hamiltonian search is greater than the snake segment's distance to its tail at that location, that location will be available to the Hamiltonian search as a clear spot.
    Idk if that made any sense, but if it did, I think it'd be a better step optimization than "Applefear Mode".

  • @TheParagade
    @TheParagade 2 года назад +1

    I really like how you ended up with an algorithm that switches between "strategies" because that's more or less how the ghosts from Pacman work

  • @WidgerCentral
    @WidgerCentral 2 года назад +12

    I must point out that the makers of Snake missed a huge opportunity by not adding more complex sound fx. Your options at 10:20 definitely made my day. Probably more of an audio improvement to any next-gen reboots of Snake.

    • @allanturner8340
      @allanturner8340 Год назад

      They couldn't. Snake was originally written in basic on a system 80 with only 16k ram.

  • @me3dnone107
    @me3dnone107 2 года назад +3

    You wake up old memories, when I implemented a Snake variant for the open source "Rockbox" firmware for mp3-players. Then I also implemented the most simple minded strategy for the npc opponents: Go straight for the apple. But I didn't call that AI. I called AS (Artificial Stupidity) - and that's what ist was!
    Thank you!

    • @ashen_dawn
      @ashen_dawn 2 года назад

      oh dear, rockbox takes me back - I spent many hours playing snake on my little 1-bit display Sansa player

    • @nikkiofthevalley
      @nikkiofthevalley 2 года назад

      I call those AU - - Artificial Unintelligence

  • @octopus9001
    @octopus9001 2 года назад +1

    I didn’t really understand the entire video, but I got a decent idea of what’s happening, so basically you have the snake always following a Hamiltonian cycle, but it cycles through all possible (based on parameters such as, length of snake and whether it will collide with itself or walls) paths to find the fastest way to the apple. It will reset every time the apple is acquired.
    Anyone who actually understood everything, let me know if I’m correct.

  • @slycordinator
    @slycordinator 2 года назад +1

    Coming up with a smarter algorithm reminds me of an undergrad scheme assignment. We wrote the exponential function pow(x,n) with plain recursion; [if n =1 return x; if n > 1 return x*pow(x,n-1)]. Prof had us test the time it took to run for 2^trillion or billion. My computer needed a memory upgrade, so it took a little over 30 minutes to run.
    When we added checking for even values of n [since x^(2y) == (x^y)^2], the same calculation took a few milliseconds on my underpowered box.

  • @abhinashkhare1933
    @abhinashkhare1933 2 года назад +3

    Really liked the through experiments conducted for this video, deep dive analysis of each attempt. This is almost equal to undergrad/master thesis level work.

  • @Aftermouse6248
    @Aftermouse6248 2 года назад +5

    He sounds like Mark Rober when he first started RUclips

  • @Oblivion-ki4qj
    @Oblivion-ki4qj Год назад

    man i just love your videos dude ! thanks

  • @unsafestcolt2766
    @unsafestcolt2766 2 года назад

    i played snake as a kid on my old flip phone (first phone) enjoyed the hell out of it I never stopped to think about the science that went into it. cool video man

  • @Benw8888
    @Benw8888 2 года назад +23

    There's definitely significant room for improvement from a mathematical perspective- ideally, you wouldn't want to use hamiltonian cycles at all; you'd want to use some new mathematical construct like "time-adjusted hamiltonian cycles" where new edges form based on time.
    That said, you'd need to be a math professor to make that improvement, so it's not something feasible for a coder who uses other people's results/code. I think this is a possible direction for a math research project not gonna lie- maybe I'll recommend it to my highschool math friends.

    • @hemartej
      @hemartej 2 года назад +5

      "it's not something feasible for a coder who uses other people's results/code" I don't think you meant any offense with that, but if read with the wrong eyes, it sounds a little bit condescending. There are reasons to re-use other people's work: you save time, don't reinvent the wheel and, you know, honor their efforts. Stand in the shoulders of giants and all that. It's what science is about, right? Also, sometimes using other's code requires overcoming a certain resistance that some of us have for not writing our own stuff (and I speak for myself mostly, boy am I hard to convince to reuse code instead of doing my own implementation). My point is, reusing other people's code is in no way indicative of the level of skill of this person to invent new maths. Maybe you don't need to be a professor to do it, maybe you can figure it out with enough dedication to research and fill the gaps. After all, solving hard problems is how you become a professor, and not by letting gatekeepers tell you what you can and what you can't do.
      Even if I was convinced that you need to be an authority in a certain field in order to contribute to it, I have no idea of this person's background. However, if he's a computer's science major (and since I don't know about him, I don't have any reason to believe that he isn't), for instance, he has all the authority in the world to make that and other improvements.
      Again, I don't think there was the slightest ill intent in your comment, but maybe it can be a little bit discouraging for someone passing by and reading. "Why would I try any hard problem if I'm not a professor?"

    • @ParaSpite
      @ParaSpite 2 года назад

      I wonder if a simpler ruleset could be used to make sure there's always an escape route.
      Perhaps to explore possible rules, a sort of "turn-based strategy game" version of Snake could be implemented, in which a human has an unlimited amount of time to decide on the ideal route to the next apple, and then has to draw it on the screen. Infinite chances to redraw the route, and a confirm button onscreen and/or on the keyboard to execute the move.
      This would be boringly easy for a human player, but might be a good tool to help figure out an AI ruleset that ensures safe and reliable navigation.

    • @Benw8888
      @Benw8888 2 года назад

      @@hemartej Sorry for any offense. I meant it literally, that if you only intend to use already published results, you probably wouldn't find the research I'm talking about. All I meant was that you'd have to do mathematical research for that direction.

    • @hemartej
      @hemartej 2 года назад +1

      @@Benw8888 Of course, don't worry :)
      I was convinced you didn't have any sort of ill intent with your comment, but some people could give it a different interpretation based on the wording.

  • @mikoajzabinski3569
    @mikoajzabinski3569 3 года назад +14

    It would be super cool to see how much moves snake spends in each mode.

  • @scottwilbur2573
    @scottwilbur2573 2 года назад

    Fascinating, as impressive and interesting to watch as Code Bullet!

  • @reedr7142
    @reedr7142 2 года назад +1

    I loved playing Snake Byte on the Apple //e. There were two game plays--the harder one had a bouncing plum that could crash into you. In both game plays, the player had 10 seconds to eat the apple. If that didn't happen, another apple appeared. I think each board required the player to eat 10 apples (aside from any extra that appeared because of the 10-second rule). Successive boards include obstacles that you had to move around. I never beat it, and I have been looking for that game ever since.

  • @Omaryllo
    @Omaryllo 2 года назад +8

    Did you calculate what the theoretical minimum runtime a game would take? Like could an optimal algorithm on average solve a game with like 30k moves?

    • @hughjanus6209
      @hughjanus6209 Год назад

      theoretical minimum would be then number of cells in the level. So for a 10x10 grid it would be 100 moves. This would only happen in the extremely unlikely case that each apple would spawn in the next cell that you are going to

  • @ChibiQilin
    @ChibiQilin 2 года назад +34

    Please no Hamiltonian cycles, I had enough of that in undergrad

  • @Weatherbg11
    @Weatherbg11 2 года назад

    This is the first vid i watch of alpha phoenix
    I love the "plan a always goes up in flames" thing

  • @TheJoergenDK
    @TheJoergenDK 2 года назад

    Man, you are sick in some really nice and good way, bless your enthusiasm and bless you with it, and all the goodest luck with it all!

  • @abeestosruinsageneration3725
    @abeestosruinsageneration3725 2 года назад +30

    That totally looks like something Code Bullet would do.

    • @mono2656
      @mono2656 2 года назад +3

      He did do it XD

    • @Loaderdani
      @Loaderdani 2 года назад +1

      @@mono2656 But not for as long or as well.

  • @simeongeorgiev1107
    @simeongeorgiev1107 2 года назад +9

    SIR WHAT YOU HAVE DONE IS PURELY AMAZING!!! I have no words to explain my gratitude for taking your time to 1) make the AI and implement the algorithms and 2) to make the video, edit it and upload it for us - the viewers.

  • @TheOriginalJohnDoe
    @TheOriginalJohnDoe 2 года назад

    I'll give you a like, but only because you didn't gave up after one day. Props to you, really enjoyed watching every single minute of this.

  • @felipedias4610
    @felipedias4610 2 года назад

    Man, what an amazing adventure! Congrats!

  • @King.Science
    @King.Science 2 года назад +5

    Why not code it to get the apple until a cycle is actually needed for it to clear the board that way it moves even faster until the snake is too long

  • @higheloguy9057
    @higheloguy9057 2 года назад +26

    Why not active Hamilton algorythm when snake length is almost at max?

    • @caboose9843
      @caboose9843 2 года назад +3

      perhaps it only activates in full once the snake takes up >60% of the grid?

  • @eliekurtz
    @eliekurtz 10 месяцев назад

    Unreal how much thought and time went into this - and for such a frivolous matter

  • @SilverAura
    @SilverAura 2 года назад

    I had no idea I'd actually know what you were talking about in the beginning, by minute 15. This is some insane meal-time content right here.

  • @thomashorsten835
    @thomashorsten835 2 года назад

    Really fascinating, one of the most interesting aspects is comparing purely algorithmic solutions, machine learning solutions, and "the human way" which is a mix of logic and "intuition", in the sense that we know something is the right move but can't readily explain why. Exactly how our brain manages that is probably the missing step to achieve general AI.

  • @xero110
    @xero110 2 года назад +90

    The easier method would be simply solving P vs NP. 🙂

    •  2 года назад +7

      Just assume P!=NP. Works well enough in practice.

  • @Zc0ol
    @Zc0ol 2 года назад +4

    Interesting video. I think i have a far simpler solution based on the way I played the game myself back in the day. this would take a stepped approach factoring the length of the snake. First, find the perimeter of the map and hug it. only dip down at the correct x coordinate of the apple, eat it, go all the way to 1 pixel before the perimeter and go back up back to the safety of the original perimeter path(i will call this a full dip from here on). Then when the snake gets long enough that it can almost reach its own tail, add an additional full dip at one side of the map before continuing along the perimeter as per usual. Add a full dip to the left of the map each time this happens until the snake is the maximum length and the game is complete. This will cut out the need for all complex algorithms as there would be no risk of getting stuck. The marginal loss of efficiency at the beginning of the game is significantly outweighed by the increased simplicity and efficiency of the pathing across the rest of the game and these gains continue to show dividends all the way through to the end of the game. This method is foolproof and significantly improves on the pure Hamiltonian method without the significant added complexity.

    • @nikolatasev4948
      @nikolatasev4948 Год назад +1

      Have you tried coding it and checking how it performs?

    • @Zc0ol
      @Zc0ol Год назад

      @@nikolatasev4948 I have not, based on the logic though, I don't see how it could be wrong. The strategy is so simple that I can't imagine it having enough variability to be wrong. The only limiting factor is the player and his ability to concentrate for the length of the game. computers of course don't have this variability and can play it perfectly every time. If someone does actually program it, I'd be very interested in hearing about it.

  • @serrenblaze3268
    @serrenblaze3268 2 года назад +1

    I've got a simple idea...
    Have the snake compare the distance to the apple to the distance it's tail needs to move to survive, that way it won't go back to fill in area's it doesn't need to. Half of the game is forcing the apple to spawn near the head so another idea is to calculate the distance traveled to each tile for an apple and make the snake move in a way the apple spawns the fewest moves away as high as possible. Results would be the snake recklessly charging towards the apple in a way that makes the apple likely to spawn fewer tiles away.

    • @aaaab384
      @aaaab384 2 года назад

      How about this idea: FIRST you learn grammar, and THEN you write stuff.

  • @manu-singh
    @manu-singh 2 года назад +1

    I love this video, learned a lot as I was starting Dijkstra algorithms for a neat path finding project😆

  • @BAIGAMING
    @BAIGAMING 2 года назад +4

    Your videos are so technical to the point where you can probably write this all down and get publications. You could even collaborate with profs in these branches of mathematics too, I don't see videos this technical often, you have skills. It's great to see you know MATLAB, I spent years learning it in school and making projects, but employers usually don't like it compared to other languages.

    • @aaaab384
      @aaaab384 2 года назад

      As a university professor, I can safely say I will NEVER collaborate with this person, who spreads misinformation over the internet. If you seriously think this individual should publish something (I thought you were joking at first!), then you desperately need to open a book and start studying. Any book, doesn't matter the subject. Currently, you live in a fantasy world where donkeys fly and ignorant youtubers publish mathematical papers.

    • @dakorjparie2425
      @dakorjparie2425 Год назад +3

      @@aaaab384 If I understand well, you are arguing on internet, that there are people on it, who are spreading misinformation, without proofs neither adding serious arguments to your accusations? ( I can't believe the authoritative one, a professor would not be so childish, nor hypocrite, and we wont answer to your second argument cause it's just a disguised insult).

    • @aaaab384
      @aaaab384 Год назад

      @@dakorjparie2425 try again in English.

    • @dakorjparie2425
      @dakorjparie2425 Год назад

      @@aaaab384 I can't find any reason to do it, peoples aren't your mupets, fake teacher :)

    • @jakubt8701
      @jakubt8701 Год назад +1

      I doubt you are a university professor. All math professors I met are ready to give arguments even for nonsense questions without laughing at the person who asks. Will you give such an argument?

  • @ferociousfeind8538
    @ferociousfeind8538 2 года назад +6

    The issue I see is this early/mid algorithm (at around 2/3rds the video length) needs a full and complete hamiltonian cycle, meaning that it will essentially prioritize filling in space compactly over dashing to the apple. I would check to make sure that if it did break the hamiltonian cycle, it makes sure that the cycle it is on has more spaces in it than its actual length. Though, I could see some other problem arising quickly from there during late-game play...

  • @destinyjames6117
    @destinyjames6117 2 года назад

    This is somehow motivating me to do my FYP :)
    Love your algorithmic thinking, thanks for the motivation boost ~~!

  • @Neptunequeen42
    @Neptunequeen42 2 года назад

    "MatLab was probably not the best tool for this job. But it is the hammer that I use to pound nails, screws, and rivets alike." I've never felt more seen by a youtube video in my life.

  • @Kavukamari
    @Kavukamari 2 года назад +18

    The Of Grid: How To Win At Snake

  • @alexolson3088
    @alexolson3088 2 года назад +4

    What if you Split it up into tow algorithms, One that just has the snake take the fastest possible path that doesn't run into itself, and at some point later on when that becomes unsafe(unsure when that would be, probably determined through experimentation) Switch over to the algorithm you showed? That would probably save a substantial amount in the early stages of the game.

    • @MrDoughnut99
      @MrDoughnut99 2 года назад

      Love this idea, was thinking the same thing while watching

  • @polychoron
    @polychoron 2 года назад

    I remember Code Bullet's Snake AI project... glad it inspired you 💜
    I never thought of the food pellets as apples before, but don't recall what I thought they were... in the version I played (QBasic Nibbles), I think they were numbers, lol.

  • @johnflux1
    @johnflux1 2 года назад +1

    Hey. I'd love if you mentioned me - because afaik I invented the Hamiltonian cycle idea, as CodeBullet said. I was sponsored by Nokia themselves, for the California MOMA museum. I love your new additions and ideas.

  • @alanaxel7805
    @alanaxel7805 2 года назад +5

    6:11 I'm firin mah lazor WAHHHHHHH

  • @pcarlisi
    @pcarlisi 3 года назад +7

    Love the video! But I have to nitpick slightly, specifically the section that starts at 6:17, because the question of whether the snake has a Hamiltonian cycle that reaches the corner (or more generally, can ever go into the corner) is a bit trickier than your answer makes it seem. For your given example, a Hamiltonian cycle exists for both possibilities, but for an AI to 'see' it requires it to have the foresight that while its body currently occupies said Hamiltonian, it will not in a future state when the head crosses. Which is a much more computationally complex route to go when designing an algorithm and obviously not something you want to do, but is still true none-the-less.

    • @BrianC1664
      @BrianC1664 2 года назад

      I didn't catch that on the first watch, but you make a very good point.

  • @qprett
    @qprett 2 года назад +2

    I think you can improve your algorithm when it calculates how far the tail has to move to make the path short. This means that it calculates multiple scenarios of eventual positions and chooses the fastest one. But this may require processing power we might not have.
    This could also solve the issue of doing a long run to not cut the hamiltonian cycle as after a certain amount of time it can reconnect again.

  • @catcat365
    @catcat365 Год назад

    Before this I thought of snake as a simple and charming game from the days of old. Something to bring nostalgia and play endlessly just for some simple good old fun.
    Now it haunts me as the complicated process of ai that it is. Thank you :)

  • @user-td7nf3hw6e
    @user-td7nf3hw6e 4 года назад +3

    I admire your algorithm buddy. Can you make your code public?Like upload it to github or something, I want to see it.It must be great.

    • @AlphaPhoenixChannel
      @AlphaPhoenixChannel  4 года назад +4

      sorry for the delay!
      github.com/BrianHaidet/AlphaPhoenix/tree/master/Snake_AI_(2020a)_DHCR_with_strategy

  • @imignap
    @imignap 2 года назад +388

    You implemented snake game without using python, shame...

    • @Chriva
      @Chriva 2 года назад +13

      I'm just happy not to see that cancer

    • @sit33darshanpagar16
      @sit33darshanpagar16 2 года назад

      No body ask you. 😂😂😂

    • @0009rekcurTkcuF
      @0009rekcurTkcuF 2 года назад +22

      @@sit33darshanpagar16 nobody needed to??? They were just saying that it would be funny if they imported it in python, because, well, snake close to python.

    • @nyaKona
      @nyaKona 2 года назад +3

      @@Chriva wait, why is python bad?

    • @Chriva
      @Chriva 2 года назад +5

      @@nyaKona It's a slow turd that condone bad practices. Guess where people bring those practices once they grow out of that toy? You guessed it, other languages. It truly is a cancer.

  • @purplehaze2358
    @purplehaze2358 Год назад +1

    "The hamiltonicity of arbitrary bipartite rectangular grid graphs"
    43 seconds in and I can already tell my brain is too small for this.

  • @user-hnjga8is1zr6u
    @user-hnjga8is1zr6u 2 года назад

    Ah yes, algorithm again
    This is the most relaxing video it really wants me to watch after doing physics, math, and chemistry homework before I go to 2 hours sleep before it's 6 AM

  • @aarnimustakallio7769
    @aarnimustakallio7769 3 года назад +5

    You sound exactly like Mark Rober

  • @ChristopherHouser
    @ChristopherHouser 2 года назад +3

    Does this algorithm ever consider the length of its path with respect to its tail? The length of tail that is equivalent to the length of the path to the apple won't matter for finding a new Hamiltonian cycle, it looks like. Avoiding a board split only seems relevant when the apple has been picked up.

    • @spiralingsphere3785
      @spiralingsphere3785 2 года назад

      no, that would take it out of its hamiltonian cycle. He tried making a "simple formula" that could solve all parts of snake, doing the lenght compared to tail lenght would only work until 30-50% of the board got filled (depending on the shape) and trying to do so in a hamiltonian cycle would take more processing power the longer the snake got. Which is technically what he tried early on where it didn't load anything for 15min during 1 move.

  • @Qoko88
    @Qoko88 Месяц назад

    I can't really remember when this was recommended to me and I still don't really know how (I'm no programmer, I'm interested in it and was searching up bits about AI), but I do remember just giggling like a young teenager at 3am when 10:31 happened as it clearly shows your frustration in a very practical way😂. Thanks for informing me a bit more about AI.

  • @dusanstevic89
    @dusanstevic89 2 года назад

    I just discovered your channel. Your videos are great! Subscribed.

  • @JayPixx
    @JayPixx 3 года назад +3

    Great Job, Great passion, great, man ;)

  • @razorblood
    @razorblood 4 года назад +5

    Xpress TV 👊

  • @StefsEngineering
    @StefsEngineering 2 года назад

    Cool vid! And recognizable thumbnail. First thought was: "Ah Codebullet!"

  • @xgozulx
    @xgozulx 2 года назад

    this was amazing, I'm very tempted to attempt this

  • @PasseScience
    @PasseScience 2 года назад +5

    16:00 When machine learning is not sufficient to produce perfect enough solutions the trick is to make the AI responsible of a subroutine and not of the entire decision making. By exemple in your program you have a baseline algorithm on top of which you have added "special cases optimisation" so the idea would be to make all this "special case subroutines" into a generic format for an AI output (like something suggesting several candidate paths in order of preference) that would be validated and selected by the main program. (and as usual AI suggestion are trained based on a criteria to determine to evaluate how they have performed) It would require to rewrite the program to be efficient, because good training would required at the bare minimum 10th of thousands of games. But it definitely would be fun to see how it would crush manually crafted subroutines :p

  • @StefanReich
    @StefanReich 2 года назад +4

    Yeah I can see how hacking on this could turn addictive

  • @Empire526
    @Empire526 2 года назад +1

    In the eighth grade, I made a snake AI that basically just started at the top left and "printered" its way to the bottom, leaving one column empty so it can get back to the top. About a year later, the laptop broke and I lost all of that, plus all of my other projects. Later, possibly after watching Code Bullet's video, I remade it and realized, if the food is above the snake, why should it go all the way to the bottom when it could just enter the gutter and go up to the top, or better yet, to the height of the food? So I did that, and it introduced a massive time save. About two weeks ago, I was at a camp with spotty internet and needed something to do, so I broke out the snake AI. I realized, if it was skipping going all the way to the bottom and just going up when the food was above the snake, why couldn't it do that while going down too? So I implemented that, and a huge mess of problems came out with it, needing to check if the gutter's clear before entering it, getting trapped at the bottom because the snake entered the bottom row from the left instead of the right and therefore couldn't enter the gutter, etc. but I seem to have solved all of them. Currently, there are still two bugs left that result in the game ending, but they seem to be caused by lag and my sloppy code handling inputs badly so I'm just going to ignore them. I'm planning on releasing some videos of this to my channel, one letting it run for hours, and one explaining how it works. I think mine's definitely still a lot slower than yours, but mine's a lot simpler and I think that's a worthwhile tradeoff.

  • @bblz9171
    @bblz9171 2 года назад

    You deserve all these new subscribers!

  • @jekanyika
    @jekanyika Год назад +3

    2:16 It's probably a bible thing.

  • @bpj1805
    @bpj1805 2 года назад +3

    Now spice things up with a hostile apple-placing algorithm. Although your snake seems pretty fastidious about avoiding traps.

  • @funnyanimalworld7579
    @funnyanimalworld7579 2 года назад +1

    mate you ventured beyond being just programmer, you became scientist.

  • @sudocheese
    @sudocheese 2 года назад

    Saw Snake AI in title, clicked, thought about CodeBullet, saw CodeBullet in description. Reference to XKCD in first second of video... Went to click "subscribe", already subbed. That was a fast 8 seconds.

  • @want-diversecontent3887
    @want-diversecontent3887 4 года назад +5

    For my own personal use: 10:30

  • @aeea8318
    @aeea8318 2 года назад +3

    The dude got stroke by a question one morning and basically did a PhD on it, just for that you owe my infinite respect.
    Ps: About your remark about yourself at the beginning, did you know about MBTI classification ? I swear you're an INTP dude 👍

  • @0verloaded
    @0verloaded 2 года назад

    I love the Red vs Blue reference xD also, good work figuring this out

  • @loocheenah
    @loocheenah Год назад

    When the snake realises it's closed in I would suggest, from the "entry point" of the closed area, to calculate a few moves ahead to see if a two-cell gap opens up, then build a route inside the closed area, twice as long as the length of the tail beyond the entry point and which is an HC containing the two points of the gap. Then to "plug" into that route, that is, build a path for the snake to get on that route after its midpoint. That's roughly the idea.
    .
    I mean, the whole point is not to get trapped, so we can build the whole algo off of that. We should compare the outer area cell number with the length of the snake to realize whether we will need to go back into that closed area because the open area has ended. And if the outer area is bigger, we can just run the shortest path to exit from the closed area.