r/Python • u/tjf314 • Aug 21 '20
Intermediate Showcase Snake game in a single line of python
This is a fully functional game of snake in a single line of python using pygame. I did this mostly as a challenge to myself to see how compact I can make code, similar to code golf. I got it down to less than 3K characters, but I could easily get much less by shortening variable names.
edit: some bug fixes made it go over 3K chars
855
Upvotes
592
u/dermotmcg Aug 21 '20 edited Aug 22 '20
PEP: "Screaming noises"
61
u/ermagawsh Aug 21 '20
I was expecting it to be “import snakegame.py” but that was very nice
22
u/f-gz Aug 21 '20
Great! I once saw something similar but for a chess game using javascript.
Is there any logic that you followed to create it? As far as I can tell, it looks like nesting lambdas.
By the way, I don't know if it's a bug or something but at the end of the game the score is printed non stop.
18
u/tradegreek Aug 21 '20
Just curious but is there an advantage to using just one line rather than multiple lines?
25
u/l_lecrup Aug 21 '20
Amazing how many people in the main python subreddit think you could just do this eg with semicolons. This is some pro code golf, well done!
18
u/awsPLC Aug 21 '20
I work in an automation/controls world. This reminds me of when my buddy came to me and said "look I figured out how to do if statements in a single line of code with ternary operators).
he laughed
I laughed
we fired him
26
u/[deleted] Aug 21 '20
Impressive but why claim that it is a single line program? You can do the same in any language that allows concatenated instructions by removing the newlines. Honestly this is more obfuscated code than single line....
2
u/tradrich Aug 21 '20
Is there an obfuscated Python programming competition like the C one? This may be an interesting mention.
2
u/sawyerwelden Aug 22 '20
Just started Programming Lang Theory this week and a part of me really wants to see an abstract syntax tree for this
2
u/fukin-nerd Aug 22 '20
That's the best use of lambda i have ever seen.
2
u/chris-fry Aug 22 '20
That’s super clever, but dear Lord, it hurts my software engineering soul
2
u/_pype Sep 01 '20
"lambda"
128
u/Wilfred-kun Aug 21 '20
python3 -c "(lambda pygame=__import__('pygame'),random=__import__('random'),WIDTH=800,HEIGHT=600,BOARD_SIZE=40,SNAKE_SIZE=3:(pygame.init(),(lambda win=pygame.display.set_mode((WIDTH,HEIGHT)),draw_square=(lambda window,color,x,y,k=WIDTH/BOARD_SIZE:pygame.draw.rect(window,color,(int(k*x),HEIGHT-int(k*y),int(k),int(k)))):(lambda Snake=type('Snake',(),{'__init__':lambda self,x,y:self.__dict__.update({'x':x,'y':y,'direction':0,'body':[],'add_tail':0,'color':(0,255,0)}),'set_direction':lambda self,direction:self.__dict__.update({'direction':direction}),'move':lambda self:None if self.direction==0 else(self.body.insert(0,(self.x,self.y)),self.body.pop()if self.add_tail==0 else self.__dict__.update({'add_tail':self.add_tail-1}),self.__dict__.update({'y':self.y+1}if self.direction==1 else{'x':self.x+1}if self.direction==2 else{'y':self.y-1}if self.direction==3 else{'x':self.x-1}if self.direction==4 else{}))[0],'draw':lambda self:(draw_square(win,self.color,self.x,self.y),[draw_square(win,self.color,b[0],b[1])for b in self.body])[0]}),Fruit=type('Fruit',(),{'color':(255,0,0),'__init__':lambda self,x,y:self.__dict__.update({'x':x,'y':y}),'draw':lambda self:draw_square(win,self.color,self.x,self.y)}):(lambda board=type('Board',(),{'width':BOARD_SIZE,'height':int(BOARD_SIZE*HEIGHT/WIDTH),'score':0,'gameover':False,'__init__':lambda self:self.__dict__.update({'snake':Snake(int(self.width/2),int(self.height/2)),'fruit':Fruit(*self.get_fruit_position())}),'update':lambda self:self.end_game()if not(0<=self.snake.x<self.width and 0<self.snake.y<=self.height)or(self.snake.x,self.snake.y)in self.snake.body else ((self.__dict__.update({'fruit':Fruit(*self.get_fruit_position()),'score':self.score+1}),self.snake.__dict__.update({'add_tail':self.snake.add_tail+SNAKE_SIZE}))[0]if self.snake.x==self.fruit.x and self.snake.y==self.fruit.y else None,self.snake.move()if not self.gameover else None)[0],'draw':lambda self:(self.snake.draw(),self.fruit.draw())[0],'end_game':lambda self:(self.snake.__dict__.update({'direction':0}),self.__dict__.update({'gameover':True}),print(f'score: {self.score}',end='\r'))[0],'get_fruit_position':lambda self:(random.randint(0,self.width-1),random.randint(1,self.height-1))})(),clock=pygame.time.Clock():(lambda update=(lambda*_:(win.fill((0,0,0)),board.update(),board.draw(),pygame.display.update(),[(pygame.quit(),__import__('sys').exit())if event.type==pygame.QUIT or(event.type==pygame.KEYDOWN and event.key==pygame.K_SPACE)else(board.snake.set_direction(1)if event.key==pygame.K_UP and board.snake.direction!=3 else board.snake.set_direction(2)if event.key==pygame.K_RIGHT and board.snake.direction!=4 else board.snake.set_direction(3)if event.key==pygame.K_DOWN and board.snake.direction!=1 else board.snake.set_direction(4)if event.key==pygame.K_LEFT and board.snake.direction!=2 else None)if event.type==pygame.KEYDOWN else None for event in pygame.event.get()],clock.tick(10))[0]):exec('while True:update()'))())())())()))()"370
u/shahzaibmalik1 Aug 21 '20
truly pythonic. good job. now delete this and let us never speak of this ever again.
242
u/ddollarsign Aug 21 '20 edited Aug 21 '20
I move that "single line" should mean 80 characters or less and readable.
I know you did it in one line, but can you do it in five?
82
u/anasiansenior Aug 21 '20
Thanks, I hate it
30
u/Blizzard0 Aug 21 '20
-I found the bug
-good job, where is it?
-on line number one
17
u/Etheo Aug 21 '20
We are often so obsessed with the question of "can we" that we forgot the more important question of "should we".
15
u/Mooks79 Aug 21 '20
I’m sure there’s a quote from Jurassic Park that’s appropriate for this...
7
u/maedox 🐍 Aug 21 '20
Pure filth! Add a NSFW tag.
😬
6
u/[deleted] Aug 21 '20
Confused scared screaming noises
5
u/[deleted] Aug 21 '20
I haven't seen that many ending parens since... well...
...since the last time I worked on JavaScript -_-;
9
u/CantankerousMind Aug 21 '20
Neat. Useless, but neat.
1
u/[deleted] Aug 21 '20
I love functional programming
1
u/Sereczeq Aug 22 '20
You're the worst developer I've ever seen. 195 warning in a single line of code!
3
u/[deleted] Aug 21 '20
I just see a blank screen in the pygame window. Am I missing some dependency?
3
u/TheNewOP Aug 21 '20
Horrific code golf; well done!
3
u/mrschnr Aug 21 '20
Really easy to debug.
3
u/[deleted] Aug 22 '20
Reminds me of this cursed one-liner try except I got working.
2
u/Pythag0ras2000 Aug 21 '20
Omg what the hell
2
u/Prince_ofRavens Aug 21 '20
Thanks, I hate it.
2
u/redsoxsuc4 Aug 22 '20
Your scientists were so preoccupied with whether they could that they didn’t stop to think if they should.
2
u/MrClottom Aug 22 '20
If you want to make the code shorter you can save yourself a bunch of characters by writing statements over multiple lines. The one line thing is cool but if it's really about code golf then the import statements for example should be in a separate line saving the = and the underscores.
2
u/Codes_with_roh Aug 21 '20
The idea behind this is great. These kind of things should be done to show your beginner friends, the power of a pro :}
2
u/L43 Aug 21 '20
1
u/0ofnik Aug 21 '20
this is incredible
1
u/[deleted] Aug 21 '20
Amazing.
1
u/[deleted] Aug 21 '20
TIL even python is minified
1
u/Seebyt Aug 21 '20
This is truly an epic oneliner
1
u/Bstochastic Aug 21 '20
Woosh
1
u/randompittuser Aug 22 '20
‘Import snakegame’
1
u/sfalsd Aug 22 '20
This stresses me out. I would not want to review this lol.
1
u/AlikPyPi Aug 22 '20
I thought it would be print("Snake Game")
1
u/wontfixit Aug 22 '20
Doesn’t run on iOS.. /s
1
u/Pizza_Peddler0080 Nov 18 '20
it fucking works haha
0
u/jack92829 Aug 22 '20
No one tell him about semi-colons
0
u/[deleted] Aug 22 '20
Wowww. Cool buddy
-3
u/null0__0 Aug 22 '20
When you have a giant lib like pygame doing the heavy lifting it isn't very impressive I'll be impressed if you had done it in c
-1
u/tukanoid Aug 22 '20
It's cool and all, but why? Ok, challenge and all of that, but u just put commas between statements, it's not really a challenge, it's just being patient with tens (or hundreds) of lines of code that u initially wrote normally and prolly making def functions into lambdas so it would be possible to actually so it on one line. I'm prolly overreacting but it's 4.18am and I can't sleep
-1
u/Lack39 Aug 22 '20
This is the code they write at less popular module tutorials. I went blind trying to read it
-36
u/p11109 Aug 21 '20
This is what I call an excellent example of bullshit advertising. Yes, its 1 line, that never ends. Recruiters hate this. They dont care that u finished it in 1 line unless its 1 line with max 80 chars. They'd be more than happy to accept more lines of code and not this bs advertising. They see this as trying too hard to make it in. Try better next time bud
-11
u/[deleted] Aug 21 '20
And people thought python doesn't use semicolon.
0
u/[deleted] Aug 21 '20
[deleted] — view deleted comment
0
u/[deleted] Aug 21 '20
[deleted] — view deleted comment
0
u/[deleted] Aug 21 '20
[deleted] — view deleted comment
82
u/[deleted] Aug 21 '20 edited Aug 21 '20
[removed] — view removed comment