23
\$\begingroup\$

Games are fun

this codegolf here was so fun I had to make a version for other classic games similar in complexity. Shortest Way of creating a basic Space Invaders Game in Python

This time, however, try to recreate the classic 'Snake' game, in which you start out as a small shape, constantly moving to collecting pieces to increase your score. When you collect a piece, your 'tail' grows, which follows the path you have made. The objective is to last the longest without crashing into your own tail, or into the walls

Qualifications:

  • You, the characters that make up the tail, the walls, and the pieces you collect should all be different characters
  • show an HUD with the score. The score increases by 1 point for each piece you collect
  • The player loses when they collide with their own tail or the wall
  • a piece spawns in a random area immediately after a piece is collected, not to mention at the start of the game
  • Speed of the game doesn't matter, as long as it is consistent
  • The 'cells' should be 2x1 characters, since the height of block characters is ~twice the width Can be 1x1, because 2x1 is just ugly and I didnt really think of that
  • The keys for changing the direction should be awsd, left, up, down, right respectively
  • the starting direction should always be up
  • You must show the edges of the wall. The score may overlap the wall

Shortest code that meets the above criteria wins. Imaginary Bonus Points for creativity

\$\endgroup\$
  • \$\begingroup\$ The snake isn't supposed to grow when eating? \$\endgroup\$ – ceased to turn counterclockwis Jan 4 '12 at 0:18
  • \$\begingroup\$ hm? "When you collect a piece, your 'tail' grows, which follows the path you have made.", so yes, the snake grows. \$\endgroup\$ – Blazer Jan 4 '12 at 2:46
  • 2
    \$\begingroup\$ Without the awsd and the starting direction should always be up requirements, M-x snake would work \$\endgroup\$ – scrblnrd3 Apr 22 '14 at 14:12
  • \$\begingroup\$ @scrblnrd3 M-: (progn(define-key snake-mode-map"a"'snake-move-left)...(setq snake-initial-velocity-x 0 snake-initial-velocity-y 1)(snake)) would do the trick then. \$\endgroup\$ – Jonathan Leech-Pepin Mar 31 '16 at 12:51
  • \$\begingroup\$ Related: Nibbles Nostalgia \$\endgroup\$ – sergiol Jun 9 '18 at 1:11
28
\$\begingroup\$

JavaScript (553 512 bytes)

Link to playable version

c=0;a=b=d=-1;e=[f=[20,7],[20,8]];i=Math.random;~function n(){if(c&&(87==a||83==a
))c=0,d=87==a?-1:1;if(d&&(65==a||68==a))d=0,c=65==a?-1:1;p([j=e[0][0]+c,k=e[0][1
]+d])||!j||39==j||!k||10==k?b+=" | GAME OVER":(e.unshift([j,k]),p(f)?(f=[1+38*i(
)|0,1+9*i()|0],b++):e.pop());for(m=h="";11>h;h++){for(g=0;40>g;g++)l=g+","+h,m+=
!g||39==g||!h||10==h?"X":e[0]==l?"O":p(l)?"*":f==l?"%":" ";m+="\n"}x.innerHTML=m
+b;!b.sup&&setTimeout(n,99)}();onkeydown=function(o){a=o.keyCode};function p(o){
return e.join(p).indexOf(p+o)+1}

I tried to make it output to the real console at first (with console.log and console.clear), but it was flickering too much, so I put it into console-like HTML. It will work with this:

<pre id=x>

Also I implemented it with 2x1 cells first, but it just looked worse than 1x1. That would be a minor change though.

Uses awsd keys on keyboard.

Update:

I was able to cut it down to 512 (exactly 0x200) bytes by improving the tail search and doing some more magic.

You now get 2 points when a piece spawns in your tail (it's a feature). I also fixed the overlapping when the snake bites itself.

\$\endgroup\$
  • 1
    \$\begingroup\$ beautiful! and you're right, it does look better as 1x1 than 2x1. the only worry I really had there was up and down being way faster than left and right but it's doable considering the constraints. The flashing in the console I don't mind so much (see my space invaders program, its fairly flickering) but I suppose a plain text web page works too! one qualm though... is there any way to restart without needing to refresh? :( \$\endgroup\$ – Blazer Jan 4 '12 at 5:24
  • \$\begingroup\$ Doesn't work with awsd \$\endgroup\$ – Neal Jan 4 '12 at 21:56
  • \$\begingroup\$ @Blazer That would take more 13 characters :-/ ... and you have the F5 key anyway. \$\endgroup\$ – copy Jan 5 '12 at 0:23
  • \$\begingroup\$ @Neal Yeah I used the arrow keys but fixed it now. \$\endgroup\$ – copy Jan 5 '12 at 0:24
  • \$\begingroup\$ @copy I suppose I didn't make it a requirement \$\endgroup\$ – Blazer Jan 5 '12 at 0:28
18
\$\begingroup\$

x86 Machine Code (128 bytes)

Much like my submission for Generating a Mandlebrot Fractal, I wrote a prod for the game of snake in 128 bytes. It doesn't fully meet the requirements of the challenge (it starts moving right, not all walls are drawn), but I'm posting it because I think it is an interesting and creative solution. The score is shown in binary on the right, the arrow keys control the direction of motion, the 'food' is dropped randomly, and it ends if you hit yourself, the wall, or the edge of the screen.

Link for executable and source code

Screenshot

Also, in regards to the earlier comment about whether dosbox is cheating, I think perfectly acceptable as long as it is in a text-based display mode, since then it is just a dos terminal.

\$\endgroup\$
8
\$\begingroup\$

16 bit 8086

526 bytes / 390 bytes

Decode this using a Base64 decoder and call it "snake.com" then execute from Windows command prompt. Tested on WinXP, you may need to use DosBox to get the right video mode. Control keys are 'wasd' and space to exit. Press 'w' to start.

uBMAzRC5AD+2AOipAb1AAbgAoI7Auf//v4sMsAHzqrgAtLksAfOqg8cU/sx19OgsAYs+8gKwAuj4
ALQAzRpCiRYOA4kWEAPouAC0C80hCsB0IbQIzSG+ygKDxgOAPAB0EjgEdfSLRAGzAP/Qo1cBiB7w
AulqAIEGdAGu/7P+uNECgMMEw7MCuNsCgMMGw4s+8gKLHvACisPolwADv+YCJoo16I0AiT7yAoD+
A775AnREiz70AiaKHbAA6HUAA7/mAok+9AKA/gB0FscGVwHNAoEudAGu/zPJtj/o2QDofQC0AM0a
OxYOA3X2/wYOA+lZ/8YEAE7+BIA8CnT16F4AaOAB6EQAM9K5LQD38YvCweACBQoA9+WL+OguALlL
ADPS9/HB4gKDwgsD+iaAPQB10rADiMRXq4HHPQGrq4HHPAGrq4HHPQGrX8OhEAO62wD34rntf/fx
iRYQA4vCw772Ar8K9bUEshCstACL2AHDi4f6ArMDtwXR+LEAwNEC/smA4Q8miA0p7/7PdevoIQA6
xHQE/st13ugKAP7NdcroAwB1+8O3BSbGBQEp7/7PdfaBx0EG/srDuBAQM9uAwwLNEID7CnX2w7gD
AM0QzSB3dgEgxgIAYYcBZIUBIMYCAHd8AXN+ASDGAgAA+wAF/P8EAAIAH4ofigAAAADRxeD/TJlO
gQPvQrVA4++BVdVjgQ==

Here's a character mode version that's 390 bytes long:

uAMAzRC4ALiOwLlQADP/uCCf86uzF6u4AA+xTvOruCCfq7LdfCxUPOr6BgBiz5+AqF8Aqu0AM0aQ
okWhgKJFogC6MUAtAvNIQrAdCG0CM0hvlYCg8YDgDwAdBI4BHX0i0QBswD/0KNSAYgefALpdgCBB
m8Bov+z/rhdAoDDBMOzArhnAoDDBsOLPn4Cix58AiaJHQOclgmijUmiR2JPn4CgP4DvoUCdFOLPo
ACJoodJscFAAADv3JYiT6AAoD+AHQkxwZSAVkCgS5vAaL/vwEAudAHJoA9qnUEJsYFzIPHAuLx6F
4AtADNGjsWhgJ19oMGhgIC6Uz/xgQATv4EgDwKdPXoPgBo5wHoIgC5FwD38Wn6oADoFgC5TgD38U
ID0gP6JoA9AHXhJscFA93DoYgCutsA9+K57X/38YkWiAKLwjPSw76CAr8CALkEALSfrAQwq+L6w8
0gd3EBIFcCAGGCAWSAASBXAgB3dwFzeQEgVwIAYP+gAP7/AgACqtAH0AcAAAAA

This character mode one's three bytes longer (but the snake's better):

uAMAzRC4ALiOwLlQADP/uCCf86uzF6u4AA+xTvOruCCfq/7LdfCxUPOr6BsBiz6BAibHBQEKtADN
GkKJFokCiRaLAujHALQLzSEKwHQhtAjNIb5ZAoPGA4A8AHQSOAR19ItEAbMA/9CjUwGIHn8C6XgA
gQZwAaD/s/64YAKAwwTDswK4agKAwwbDiz6BAosefwImiR0Dv3VYJoo1JscFAQqJPoECgP4DvogC
dFOLPoMCJoodJscFAAADv3VYiT6DAoD+AHQkxwZTAVwCgS5wAaD/vwEAudAHJoA9qnUEJsYFzIPH
AuLx6F4AtADNGjsWiQJ19oMGiQIE6Ur/xgQATv4EgDwKdPXoPgBo6gHoIgC5FwD38Wn6oADoFgC5
TgD38UID0gP6JoA9AHXhJscFA93DoYsCutsA9+K57X/38YkWiwKLwjPSw76FAr8CALkEALSfrAQw
q+L6w80gd3IBIFoCAGGDAWSBASBaAgB3eAFzegEgWgIAYP+gAP7/AgACqtAH0AcAAAAA
\$\endgroup\$
  • \$\begingroup\$ points for creativity, but i think using dosbox is cheating because the challenge is to make the game work in an ascii console or terminal, not a dosbox. also, shouldn't code golf be source code, not binary? \$\endgroup\$ – Blazer Jan 5 '12 at 23:10
  • 5
    \$\begingroup\$ @Blazer: That is the source code - I typed the machine code in using a hex editor - that's how l337 I am! ;-) The DosBox thing is only needed if your video drivers have trouble with mode 13 graphics (mine card is OK with it). It wouldn't be difficult to do an ascii version (probably smaller too) \$\endgroup\$ – Skizz Jan 6 '12 at 8:50
  • \$\begingroup\$ The "390-byte" version decodes to only 388 bytes and hangs when run under dosbox. Looks like something may have been lost in transmission. :( Still, the other two versions are extremely cool! \$\endgroup\$ – Ilmari Karonen Jan 6 '12 at 12:45
  • \$\begingroup\$ Is there an ungolfed version of the code? (I don't know this language) \$\endgroup\$ – A.L Apr 20 '14 at 18:46
  • 1
    \$\begingroup\$ @n.1: The program is 8086 machine code, you can load it into a debugger (D86) and view the code as written, albeit without label names. \$\endgroup\$ – Skizz Apr 22 '14 at 8:07
5
\$\begingroup\$

shell/sh, 578 chars

I tried to be POSIX compliant (being as much portable as possible and avoid bashisms, even the random-number-generator does not need /proc). You can e.g. play it in your native terminal or via a SSH-session: run with 'dash -c ./snake' There is also an unuglyfied/readable variant in ~2800 bytes, which can be seen here.

Some notes: shell-scripting is not suited for coding games 8-)

  • to be fair, we only used so called 'builtins', which means:
    • no external calls of programs like 'clear', 'stty' or 'tput'
    • because of that, we redraw the whole screen on every move
    • the only used builtins (aka native commands) are:
      • echo, eval, while-loop, let, break, read, case, test, set, shift, alias, source
  • there is no random number generator (PRNG), so we have to built our own
  • getting a keystroke blocks, so we have to spawn another thread
    • for getting the event in parent-task we use a tempfile (ugly!)
  • the snake itself is a list, which is cheap:
    • each element is a (x,y)-tuple
    • loosing the tail means: shift the list by 1
    • adding a (new) head means: append a string
  • the grid is internally an array, but shell/sh does not know this:
    • we "emulated" array(x,y) via an ugly eval-call with global vars
  • and finally: we had a lot of fun!
#!/bin/sh
alias J=do T=let E=echo D=done W=while\ let
p(){ eval A$1x$2=${3:-#};}
g(){ eval F="\${A$1x$2:- }";}
r(){
E $((1+(99*I)%$1))
}
X=9
Y=8
L="8 8 $X $Y"
I=41
W I-=1
J
p $I 1
p $I 21
p 1 $I
p 41 $I
D
p 3 3 :
>L
W I+=1
J
E -ne \\033[H
y=22
W y-=1
J
Z=
x=42
W x-=1
J
g $x $y
Z=$Z$F
D
E "$Z"
D
E $B
. ./L
case $D in
a)T X+=1;;d)T X-=1;;s)T Y-=1;;*)T Y+=1;;esac
g $X $Y
case $F in
\ |:)p $X $Y O
L="$L $X $Y"
case $F in
:)W I+=1
J
x=`r 39`
y=`r 19`
g $x $y
[ "$F" = \  ]&&{
p $x $y :
break
}
D
T B+=1;;*)set $L
p $1 $2 \ 
shift 2
L=$@;;esac;;*).;;
esac
D&
while read -sn1 K
J
E D=$K>L
D

enter image description here

\$\endgroup\$
  • \$\begingroup\$ Does this actually work? if the snake is going to the right and you press a it stops. Weird. \$\endgroup\$ – gniourf_gniourf Apr 20 '14 at 14:59
  • \$\begingroup\$ Yes, because you bite yourself - thats the way it must be IMHO. We discussed that internally and everybody agrees on this. \$\endgroup\$ – Bastian Bittorf Apr 20 '14 at 15:31
  • \$\begingroup\$ echo -n is definitely not portable. If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined. Using echo for anything other than literal text without any switches is not portable. pubs.opengroup.org/onlinepubs/009604599/utilities/echo.html \$\endgroup\$ – nyuszika7h Apr 20 '14 at 18:57
  • \$\begingroup\$ nyuszika7h: any idea how to circument this? \$\endgroup\$ – Bastian Bittorf Apr 20 '14 at 20:53
  • \$\begingroup\$ nyuszika7h: i found a way to remove the main 'echo -n' call - so there is only one call left. it's calling the escape-sequence for 'go to home-position (0,0)' \$\endgroup\$ – Bastian Bittorf Apr 22 '14 at 14:07
4
\$\begingroup\$

Ruby 1.9 /Windows only/ (354 337 355 346 bytes)

require'Win32API';G=(W=Win32API).new g="crtdll","_getch",t=[],?I
B=(c=?#*39+h="#
#")+((S=' ')*38+h)*20+c;n=proc{c while B[c=rand(800)]!=S;B[c]=?*;S}
n[h=760];k={97=>-1,100=>1,119=>d=-41,115=>41}
(B[h]=?O;system'cls';$><<B<<$.;sleep 0.1
d=k[G.call]if W.new(g,"_kbhit",[],?I).call>0
t<<h;B[h]=?o;B[h+=d]==?*?B[h]=n[$.+=1]:B[t.shift]=S)while B[h]==S

Plays in a 20x40 board in the windows console. The score is shown under the board. Use WASD to control the snake, any other key to exit (forcefully!). Edit the sleep time at the end of line 5 to control the speed. (Or save 10 characters and make it nearly unplayable by removing the sleep entirely!)

Bonus feature: randomly fails to start (when initial piece is generated in snake's location).

I needed ~100 chars to work around the lack of a non-blocking getchar. Apparently Ruby 1.9.3 includes a "io/console" library which would have saved roughly half of those. And this solution is Windows specific. There are published solutions to do the same type of thing in *nix systems, but I haven't tested them to compare the character count.

Edit:

Had to add 18 bytes after I realized that the tail only grows after eating, not after each step.

Edit 2: (Possibly) fixed crash issue, saved the 9 bytes by restricting to one food item.

\$\endgroup\$
  • \$\begingroup\$ I like the idea of multiple food items at once, however there is a big problem: the tail should move with the player, only growing by one character for every piece of food you collect. \$\endgroup\$ – Blazer Jan 5 '12 at 23:08
  • \$\begingroup\$ You added the comment while I was working on fixing it... If there is only supposed to be one piece, I can remove the 9.times{}, saving 9 chars. \$\endgroup\$ – AShelly Jan 5 '12 at 23:43
  • \$\begingroup\$ the only requirement is that there be 1 or more piece of food at a time, so yes you could just make it 1 piece at a time, saving some characters \$\endgroup\$ – Blazer Jan 5 '12 at 23:49
  • \$\begingroup\$ the game randomly crashed on me at ~140 points, not sure why. but otherwise very nice \$\endgroup\$ – Blazer Jan 6 '12 at 2:32
  • \$\begingroup\$ Fixed the crash, I think. If it crashes again, please let me know the ruby error message. \$\endgroup\$ – AShelly Jan 28 '12 at 0:47
3
\$\begingroup\$

Applesoft Basic - 478 (462)

This was my first ever code golf, but it was written back in 1989, and it mostly implements the snake game as requested (but without food, the snakes just continuously grow, and it's actually two players, not one) using only two lines of Applesoft Basic.

There were a number of two-line program contests at the time, such as in Dr. Dobbs journal. I spent 6 months figuring out how to fit this into two lines which have a limit of 255 characters (and only one branch)

More info at: http://davesource.com/Projects/SpeedWaller/

The program typed in is exactly two lines:

1ONSCRN(X,Y)<>7ANDB<>0ANDSCRN(U,V)<>7GOTO2:HOME:GR:X=10:Y=20:U=30:V=Y:I=201:J=202:K=203:M=205:W=215:A=193:S=211:Z=218:O=1:Q=-1:P=49152:COLOR=7:HLIN0,39AT0:HLIN0,39AT39:VLIN0,39AT0:VLIN0,39AT39:VTAB22: ?"WASZ IJKM  "C:ONB=0GOTO2:CALL-678:RUN
2PLOTX,Y:PLOTU,V:B=PEEK(P):G=B<>ZANDB<>W:H=B<>AANDB<>S:O=G*(O*H+(B=S)-(B=A)):L=H*(L*G+(B=Z)-(B=W)):G=B<>IANDB<>M:H=B<>JANDB<>K:Q=G*(Q*H+(B=K)-(B=J)):R=H*(R*G+(B=M)-(B=I)):X=X+O:Y=Y+L:U=U+Q:V=V+R:FORN=1TO99:NEXT:C=C+1:VTAB22:HTAB12:?C:GOTO1

The listing when formatted looks like this:

1 ONSCRN(X,Y)<>7 AND B<>0 AND SCRN(U,V) <> 7 GOTO 2: HOME : GR :
  X=10 : Y=20 : U=30 : V=Y : I=201 : J=202 : K=203 : M=205 : W=215 :
  A=193 : S=211 : Z=218 : O=1 : Q=-1 : P=49152 : COLOR=7 : HLIN 0,39
  AT 0 : HLIN 0,39 AT 39 : VLIN 0,39 AT 0 : VLIN 0,39 AT 39 : VTAB 22 :
  ? "WASZ IJKM  "C : ON B=0 GOTO 2 : CALL -678 : RUN
2 PLOT X,Y : PLOT U,V : B=PEEK(P) : G= B<>Z AND B<>W: H=B<>A AND B<>S :
  O=G*(O*H+(B=S)-(B=A)) : L=H*(L*G+(B=Z)-(B=W)) : G=B<>I AND B<>M :
  H=B<>J AND B<>K : Q=G*(Q*H+(B=K)-(B=J)) : R=H*(R*G+(B=M)-(B=I)) :
  X=X+O : Y=Y+L : U=U+Q : V=V+R : FOR N=1 TO 99 : NEXT : C=C+1 :
  VTAB 22 : HTAB 12 : ? C : GOTO 1

The game is actually two players and includes "instructions" at the bottom of the page showing the keys as well as a counter so you can see how many steps you survived. It's 478 characters, 16 of those are the instructions and counter output, so 462 if you want to shave those off.

\$\endgroup\$
2
\$\begingroup\$

Python 3 - 644

from curses import *
import time
from collections import deque
from random import randrange as R
N,W,S,E=z=119,97,115,100
t=tuple
u=0,0
def m(s):
 a=lambda o,y,x:y.addch(o[0],o[1],x);q=lambda:(R(L-2),R(C-2));L,C=s.getmaxyx();curs_set(0);s.nodelay(1);s.border();s.refresh();r=newwin(L-2,C-2,1,1);n=deque();y,x=[L-2,0];d=N;n.append(u);c=N;p=q();a(p,r,N);a(u,s,48)
 while 1:
  if c in z:d=c
  if d==N:y-=1
  if d==S:y+=1
  if d==W:x-=1
  if d==E:x+=1
  l=n.pop()
  if (y,x) in n:return
  if (y,x)==p:p=q();a(p,r,N);n.append(l);s.addstr(0,0,str(len(n)))
  n.appendleft((y,x));a((y,x),r,S);a(l,r,32);r.refresh();time.sleep(.2);c=s.getch()
wrapper(m)

Does not quit cleanly. Piece might disappear if it spawns on top of the snake.

\$\endgroup\$
1
\$\begingroup\$

Bash (too many characters: ca. 1522)

t=tput
tc="$t cup"
tr="$t rev"
ts="$t sgr0"
ox=5
oy=5
((w=$($t cols)-2-2*ox))
((h=$($t lines)-2-2*oy))
trap "$t rmcup
stty echo
echo 'Thanks for playing snake!'
" EXIT
$t smcup
$t civis
stty -echo
clear
printf -v hs %$((w+2))s
printf -v v "|%${w}s|"
$tc $oy $ox
printf %s ${hs// /_}
for((i=1;i<=h+1;++i)); do
$tc $((oy+i)) $ox
printf %s "$v"
done
$tc $((oy+h+2)) $ox
printf %s ${hs// /¯}
dx=0
dy=-1
hx=$((w/2))
hy=$((h-2))
l=2
xa=($hx $hx)
ya=($hy $((hy+1)))
$tr
for((i=0;i<${#xa[@]};++i)); do
$tc $((ya[i]+1+oy)) $((xa[i]+1+ox))
printf \ 
done
$ts
print_food() {
$tc $((fy+1+oy)) $((fx+1+ox))
printf "*"
}
nf() {
rf=1
while((rf))
do
rf=0
((fx=RANDOM%w))
((fy=RANDOM%h))
for ((i=0;i<${#ya[@]};++i))
do
if((ya[i]==fy&&xa[i]==fx))
then
rf=1
break
fi
done
done
print_food
}
nf
ps() {
s="SCORE: $l"
$tc $((oy-1)) $((ox+(w-${#s})/2))
printf "$s"
}
ps
while :
do
read -t 0.2 -s -n1 k
if (($?==0))
then
case $k in
w|W)((dy==0))&&{ dx=0;dy=-1;};;
a|A)((dx==0))&&{ dx=-1;dy=0;};;
s|S)((dy==0))&&{ dx=0;dy=1;};;
d|D)((dx==0))&&{ dx=1; dy=0;};;
q|Q)break;;
esac
fi
((hx=${xa[0]}+dx))
((hy=${ya[0]}+dy))
if((hx<0||hy<0||hx>w||hy>h))
then
go=1
break
fi
for((i=1;i<${#ya[@]}-1;++i))
do
if((hx==xa[i]&&hy==ya[i]))
then
go=1
break 2
fi
done
$tc $((ya[-1]+1+oy)) $((xa[-1]+1+ox))
printf \ 
$tr
$tc $((hy+1+oy)) $((hx+1+ox))
printf \ 
$ts
if((hx==fx&&hy==fy))
then
((++l))
ps
nf
else
ya=(${ya[@]::${#ya[@]}-1})
xa=(${xa[@]::${#xa[@]}-1})
fi
ya=($hy ${ya[@]})
xa=($hx ${xa[@]})
done
if((go))
then
$tc 3 3
echo GAME OVER
read -t 3 -s -n1
fi

Screenshot

\$\endgroup\$
1
\$\begingroup\$

C# .NET Framework 4.7.2 Console (2,456 2,440 2,424 2,408 2,052 bytes)

This was fun, but I really had to think what variables were what, because they are only one letter.

using m=System.Console;using System;using System.Collections.Generic;using System.Drawing;using System.Numerics;using System.Threading;class s{static void Main(){m.CursorVisible=0>1;new s()._();}int l;Action<int,int> n=new Action<int,int>(m.SetCursorPosition);Vector2 d,c,a;List<Vector2>p;Size b;void _(){while(1>0){f();b=new Size(25,25);p=new List<Vector2>();l=0;d=new Vector2(0,-1);c=new Vector2(b.Width/2,b.Height/2);e();m.SetWindowSize(b.Width+4,b.Height+4);m.SetBufferSize(b.Width+4,b.Height+4);while(1>0){k();if(t())break;g();r();}f();m.SetWindowSize(b.Width+4,b.Height+6);m.SetBufferSize(b.Width+4,b.Height+6);n(1,b.Height+3);m.WriteLine("        Game over,\n   press any key to retry.");f();m.ReadKey(1>0);m.Clear();}}private bool t(){if(c.X<0||c.Y<0||c.X>=b.Width||c.Y>=b.Height){r();n((int)c.X+2,(int)c.Y+2);m.Write('X');return 1>0;}for(i=0;i<p.Count;i++){for(int j=0;j<i;j++){if(p[i].X==p[j].X&&p[i].Y==p[j].Y){r();n((int)c.X+2,(int)c.Y+2);m.Write('X');return 1>0;}}}return 0>1;}private void e(){a=new Vector2(z.Next(b.Width),z.Next(b.Height));l++;}void f(){while(m.KeyAvailable)m.ReadKey(1>0);}int i;void k(){var b=DateTime.Now;while((DateTime.Now-b).TotalMilliseconds<230)Thread.Sleep(10);if(!m.KeyAvailable)return;var a=m.ReadKey(1>0).Key;switch(a){case ConsoleKey.A:if(d.X==0)d=new Vector2(-1,0);break;case ConsoleKey.W:if(d.Y==0)d=new Vector2(0,-1);break;case ConsoleKey.S:if(d.Y==0)d=new Vector2(0,1);break;case ConsoleKey.D:if(d.X==0)d=new Vector2(1,0);break;}f();}void g(){c+=d;p.Add(new Vector2(c.X,c.Y));while(p.Count>l)p.RemoveAt(0);if(c.X==a.X&&c.Y==a.Y)e();}void r(){n(1,1);m.Write('/');m.Write(new string('-',b.Width));m.Write('\\');n(1,b.Height+2);m.Write('\\');m.Write(new string('-',b.Width));m.Write('/');for(i=0;i<b.Height;i++){n(1,i+2);m.Write('|');n(b.Width+2,i+2);m.Write('|');}for(i=0;i<b.Height;i++){for(int j=0;j<b.Width;j++){n(i+2,j+2);m.Write(' ');}}n((int)a.X+2,(int)a.Y+2);m.Write('@');for(i=0;i<p.Count;i++){n((int)p[i].X+2,(int)p[i].Y+2);m.Write('#');}n(2,0);m.WriteLine("Score:"+l);}Random z=new Random();}

Some screenshots:

Snake with score of 10 Snake crashed with score of 4

Binary: https://github.com/wooden-utensil/snakeCodeGolf/releases/tag/v1.0.0.0

GitHub repository: https://github.com/wooden-utensil/snakeCodeGolf

New contributor
facepalm42 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
  • \$\begingroup\$ Console.Write("Score:"+l);Console.WriteLine() -> Console.WriteLine("Score:"+l) \$\endgroup\$ – Stephen 19 hours ago
  • \$\begingroup\$ Have you tried tuples as in (int X,int Y)d; ...; d=(0,-1)? That might save bytes. I also can't see why are you doing Vector2 d;Vector2 c;Vector2 a; instead of Vector2 d,c,a. I think you can also store the Console.SetCursorPosition function as a Action<...> single-letter variable. You can subtract DateTime with the - operator. You can also declare loop variables globally and simply zero them out when needed, without declaring them. \$\endgroup\$ – someone 19 hours ago
  • \$\begingroup\$ [suggestions continue] You can use 1>0 or store true in a variable instead of using the keyword. You might be able to use the glorious --> operator in the loops. In the DateTime b = DateTime.Now part, b can be var. You might or might not be able to save some bytes using dynamic (often lets you merge differently-typed declarations). \$\endgroup\$ – someone 18 hours ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.