Skip to content

Instantly share code, notes, and snippets.

@AlephAlpha
Last active May 21, 2020 16:10
Show Gist options
  • Save AlephAlpha/7245191 to your computer and use it in GitHub Desktop.
Save AlephAlpha/7245191 to your computer and use it in GitHub Desktop.
Snake game in Mathematica.
Module[{a, s, d, f}, RemoveScheduledTask@ScheduledTasks[];
a[] := s =
If[#[[1]] == f,
f = RandomChoice[Complement[Tuples[Range /@ {34, 55}], #]]; #,
Most@#] &@PrependTo[s, s[[1]] + d]; s = {{17, 28}};
f = {18, 28}; d = {1, 0};
RunScheduledTask[
If[1 <= #[[1]] <= 34 && 1 <= #[[2]] <= 55 && FreeQ[Most@s, #] &[
s[[1]] + d], a[],
s = Position[
Uncompress@
"1:eJzt1U0OQDAQhuFKXIRLuISVI1hIrCy4f3RZiY6ZUpnFu/\
m0afTnMalu3qalDyHsbYxx3Y9lSHtrfAYiDYAAAggggBwHQAABBBBAjgMggAACyBtQk4vK\
o3IoZr574+2uskDyRuWtKFr20K6rHVXOLAMV1ojcMtXNh0DZdT+pIPu3+\
reC5IVMFXTtFt5Bb4Cq3EEKyLIT8Rd7CIAAAggggBwHQAABBBBAjgMggACqGicbMV7k",
1]; RemoveScheduledTask@ScheduledTasks[]], 0.3];
EventHandler[
Dynamic@ArrayPlot@
SparseArray[Append[s, f] -> 1, {34, 55}], {"LeftArrowKeyDown" :>
If[d != {0, 1}, d = {0, -1}; If[d == {0, -1}, a[]]],
"RightArrowKeyDown" :>
If[d != {0, -1}, d = {0, 1}; If[d == {0, 1}, a[]]],
"UpArrowKeyDown" :>
If[d != {1, 0}, d = {-1, 0}; If[d == {-1, 0}, a[]]],
"DownArrowKeyDown" :>
If[d != {-1, 0}, d = {1, 0}; If[d == {1, 0}, a[]]]}]]
@Spookyghostking
Copy link

I am afraid to say that your IQ is 0; Let me elaborate:
When you are pressing the same arrow as the direction you're going, you clip through your tail.
This is because the code for doing this only runs the a[ ] method/function which does not check for tail collisions.

Sorry about the 0 IQ thing, my professor made me edit this code, and I had to figure this shit out, so I'm pretty salty.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment