Implement a snake in 50 lines of code. the specific implementation code is as follows. if you are interested, refer to the following code. I hope it will help you prepare several demos for the interview recently, in order to show yourself, they are all designed and implemented in person. one of them is to implement a snake in 50 lines of code, to illustrate a way for the monks to practice programming themselves-to short the code and to understand the language details.
The code is as follows:
Import sys, pygame
From pygame. locals import *
From random import randrange
Up = lambda x :( x [0]-1, x [1])
Down = lambda x :( x [0] + 1, x [1])
Left = lambda x: (x [0], x [1]-1)
Right = lambda x: (x [0], x [1] + 1)
Tl = lambda x: x <3 and x + 1 or 0
Tr = lambda x: x = 0 and 3 or X-1
Dire = [up, left, down, right]
Move = lambda x, y: [y (x [0])] + x [:-1]
Grow = lambda x, y: [y (x [0])] + x
S = [(5, 5), (5, 6), (5, 7)]
D = up
Food = randrange (0, 30), randrange (0, 40)
FPSCLOCK = pygame. time. Clock ()
Pygame. init ()
Pygame. display. set_mode (800,600 ))
Pygame. mouse. set_visible (0)
Screen = pygame. display. get_surface ()
Screen. fill (0, 0, 0 ))
Times = 0.0
While True:
Time_passed = FPSCLOCK. tick (30)
If times >=150:
Times = 0.0
S = move (s, d)
Else:
Times + = time_passed
For event in pygame. event. get ():
If event. type = QUIT:
Sys. exit ()
If event. type = KEYDOWN and event. key = K_UP:
S = move (s, d)
If event. type = KEYDOWN and event. key = K_LEFT:
D = dire [tl (dire. index (d)]
If event. type = KEYDOWN and event. key = K_RIGHT:
D = dire [tr (dire. index (d)]
If s [0] = food:
S = grow (s, d)
Food = randrange (0, 30), randrange (0, 40)
If s [0] in s [1:] or s [0] [0] <0 or s [0] [0]> = 30 or s [0] [1] <0 or s [0] [1]> = 40:
Break
Screen. fill (0, 0, 0 ))
For r, c in s:
Pygame. draw. rect (screen, (255, 0, 0), (c * 20, r * 20, 20 ))
Pygame. draw. rect (screen, (0,255, 0), (food [1] * 20, food [0] * 20, 20 ))
Pygame. display. update ()
Games:
Note:
1. in fact, pygame is not used, and some conditions can be changed. it is estimated that some conditions can be shorter than half .. If your python level is high, try again ..
2. but the 50 lines of greedy code are still readable, and the code is too short to be written ..
3. the key is to use lamda expressions to Implement rotation, movement, and other algorithms, as well as function objects ..
4. Which of the following "practitioners" can write less quickly? the younger brother is willing to enlighten me ....
Author: aiqier