Snake is a very simple game, suitable for practiced hand.
First analyze the game
1. How do snakes draw?
Snakes are made up of a small block, then we can use a list to record the coordinates of each small box, the display of all the small squares to draw out.
2, how to move the snake?
The first reaction is to think of the earthworm creep, each block moving forward a grid, but this is very troublesome, carefully think about, in fact, in addition to the head and tail, the other parts of the snake is not moved at all, it is simple, the next grid to add the coordinates to the list, and remove the last element of the list, the equivalent of a snake
3, how to determine the end of the game?
Snake moves beyond the range of the game area or even if you lose, out of range is easy to judge, it is easy to meet yourself, as long as the next grid of coordinates are already included in the list of snakes.
By clearing these questions, we can start coding.
Let's take a look at my game.
In this example, enter: Start the game, SPACEBAR: Pause/Resume, arrow key or WSAD key: controls the direction of movement.
Each eat a food plus 10 points, every 100 points to speed up the level, no level, I play to 1100 points, the speed is too fast, and then the GAME over
"""Greedy Snake"""ImportRandomImportSYSImport TimeImportPygame fromPygame.localsImport* fromCollectionsImportDequescreen_width= 600Screen_height= 480SIZE= 20defPrint_text (screen, font, x, y, text, fcolor= (255, 255, 255)): Imgtext=font.render (text, True, Fcolor) Screen.blit (Imgtext, (x, y))defMain (): Pygame.init () screen=Pygame.display.set_mode ((Screen_width, Screen_height)) pygame.display.set_caption ('Greedy Snake') Light= (100, 100, 100)#the color of the snakeDark = (200, 200, 200)#Food ColorFont1= Pygame.font.SysFont ('Simhei', 24)#the font of the scoreFont2 = Pygame.font.Font (None, 72)#the font of GAME overRed = (200, 30, 30)#GAME over font colorFwidth, fheight = Font2.size ('GAME over') Line_width= 1#Grid line widthBlack = (0, 0, 0)#Grid Line Colorbgcolor = (40, 40, 60)#Background Color #direction, starting rightPos_x = 1pos_y=0#If the snake is moving to the right, then quick click down to the left, because the program refresh is not so fast, the down event will be left covered, causing the snake to retreat, direct game over #b variables are used to prevent this from happening.b =True#RangeScope_x = (0, screen_width//SIZE-1) scope_y= (2, screen_height//SIZE-1) #SnakesSnake =deque ()#Foodfood_x =0 food_y=0#Initialize Snake def_init_snake (): nonlocal snake snake.clear () snake.append ((2, scope_y[0])) Snake.append ((1, scope_y[0])) Snake.append ((0, scope_y[0]))#Food def_create_food (): nonlocal food_x, food_y food_x= Random.randint (scope_x[0], scope_x[1]) food_y= Random.randint (scope_y[0], scope_y[1]) while(Food_x, Food_y)inchSnake:#to keep food out of the snakes.food_x = Random.randint (scope_x[0], scope_x[1]) food_y= Random.randint (scope_y[0], scope_y[1]) _init_snake () _create_food () Game_over=True Start= False#whether to start when start = True,game_over = True to show game overScore = 0#scoreOrispeed = 0.5#Original SpeedSpeed =orispeed Last_move_time=None Pause= False#Pause whileTrue: forEventinchpygame.event.get ():ifEvent.type = =QUIT:sys.exit ()elifEvent.type = =KEYDOWN:ifEvent.key = =K_return:ifGame_over:start=True Game_over=False b=True _init_snake () _create_food () pos_x= 1pos_y=0#scoreScore =0 Last_move_time=time.time ()elifEvent.key = =K_space:if notGame_over:pause= notPauseelifEvent.keyinch(K_w, k_up):#The decision is to prevent the snake from moving up while pressing the down arrow, causing the direct GAME over ifB and notpos_y:pos_x=0 pos_y=-1b=FalseelifEvent.keyinch(k_s, K_down):ifB and notpos_y:pos_x=0 pos_y= 1b=FalseelifEvent.keyinch(K_a, k_left):ifB and notpos_x:pos_x=-1pos_y=0 B=FalseelifEvent.keyinch(K_d, k_right):ifB and notpos_x:pos_x= 1pos_y=0 B=False#Fill Background ColorScreen.fill (bgcolor)#draw a vertical line of gridlines forXinchRange (size, screen_width, size): pygame.draw.line (screen, black, (x, scope_y[0]*SIZE), (x, Screen_height), line_width)#draw a grid horizontal line forYinchRange (Scope_y[0] *size, screen_height, size): pygame.draw.line (screen, black, (0, y), (Screen_width, y), line_width) ifGame_over:ifstart:print_text (screen, Font2, (Screen_width-Fwidth)//2, (screen_height-fheight)//2,'GAME over', Red)Else: Curtime=time.time ()ifCurtime-last_move_time >Speed :if notpause:b=True Last_move_time=curtime next_s= (Snake[0][0] + pos_x, snake[0][1] +pos_y)ifNext_s[0] = = food_x andNEXT_S[1] = =food_y:#to eat food._create_food () Snake.appendleft (next_s) score
+ = 10 Speed= orispeed-0.03 * (Score//100) Else: ifScope_x[0] <= next_s[0] <= scope_x[1] andScope_y[0] <= next_s[1] <= scope_y[1] andnext_s not inchsnake:snake.appendleft (next_s) Snake.pop () Else: Game_over=True#Painting Food if notGame_over:#To avoid the game over when the word to cover the game overPygame.draw.rect (screen, light, (food_x * SIZE, Food_y *size, size, size), 0)#Draw a snake forSinchsnake:pygame.draw.rect (screen, dark, (s[0)* size + line_width, s[1] * size +Line_width, SIZE-Line_width * 2, Size-line_width * 2), 0) print_text (screen, font1,7, F'speed: {score//100}') Print_text (screen, font1,7, F'score: {score}') pygame.display.update ()if __name__=='__main__': Main ()
Python: Game: Snake (attached source)