程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to use Python to realize a simple Snake game

編輯:Python

How do you use it? python To achieve a simple Snake game

This article mainly explains “ How do you use it? python To achieve a simple Snake game ”, Interested friends might as well come and have a look . The method introduced in this paper is simple and fast , Practical . Now let Xiaobian take you to learn “ How do you use it? python To achieve a simple Snake game ” Well !

pygame Written “ snake ” Little games :

“ snake ” This little game is a regular guest in programming learning , because :

Simple , The most basic game elements only need snakes and food .( Three more elements are needed to hit a plane , Think about the difference ?) In the direction, just up, down, left and right 4 Just a fixed direction . There are basic data structures and object-oriented ideas in it . Game development itself will use many object-oriented concepts , And the snake's body is a natural “ Linked list ” structure , It's perfect for practicing data structures . Another interesting point is ,Python This word means Python in English , Greedy snakes can be regarded as “ Namesake game ” 了 . In many schools, the homework of program development course will have the topic of greedy snake , Students often ask about our relevant code .( Nokia mobile phones are also fond of this game .) I did one before 《 Snake eating battle 》 Of Python edition , be based on cocos2d-python Development . But that's a little complicated for beginners .
Here we make a brief introduction :
This code is based on pygame Development , So please make sure your Python Has been successfully installed in pygame. Then run the... In the code directly game2.py You can start the game . In addition to the final code , We also deliberately decomposed several processes py file , For students who want to develop their own reference .
Let's analyze first , What do you need to pay attention to in writing this game .

1、 What does a snake mean ?

We can divide the whole game area into small squares , It's made up of a set of connected lattices “ The snake ”, We can use different colors to represent , Such as in the figure above , I have a dark background , Light color means “ The snake ”.
We can use coordinates to represent each small square ,X Axis and Y The range of axes can be set . Use a list to store “ Snake-body. ” Coordinates of , So one “ The snake ” It's coming out. , Finally, just show it in different colors .

2、 How the snake moves ?

The first reaction is to act like an earthworm , Each little square moves one space forward , But it's very cumbersome to implement . It was stuck here in the beginning .
Imagine the snake we played with , Every time “ The snake ” It feels like the whole body has moved one space forward , Get rid of the brain “ The snake ” Of “ action ”, Think about before and after moving “ The snake ” Location change of , In fact, except for the head and tail , The rest has not changed at all . That's easy , Add the coordinates of the next grid to the beginning of the list , And remove the last element of the list , It's like the snake moves one space forward .

3、 How to determine the end of the game ?

“ The snake ” If you move beyond the scope of the game area or touch yourself, you will lose , The range of axis coordinates is predetermined , It's easy to judge if it's out of range . So how do you judge yourself ?
If the thought in my head is “ The snake ” Moving pictures , That's really hard , But put it in the code , our “ The snake ” It's a list , So just judge whether the coordinates of the next grid have been included in “ The snake ” It's OK to be in the list of ?
Sort out these problems , We can start coding .

Define game elements and interfaces :

def main():    pygame.init()    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))    pygame.display.set_caption(' snake ')    light = (100, 100, 100)  #  The color of the snake     dark = (200, 200, 200)  #  The color of the food     font1 = pygame.font.SysFont('SimHei', 24)  #  The font of the score     font2 = pygame.font.Font(None, 72)  # GAME OVER  The font of     red = (200, 30, 30)  # GAME OVER  Font color for     fwidth, fheight = font2.size('GAME OVER')    line_width = 1  #  Grid line width     black = (0, 0, 0)  #  Grid line color     bgcolor = (40, 40, 60)  #  Background color     #  Direction , Start right     pos_x = 1    pos_y = 0    #  If the snake is moving to the right , Then quickly click down and left , Because the program refresh is not so fast , The down event will be overwritten to the left , Cause the snake to retreat , direct GAME OVER    # b  Variables are used to prevent this from happening     b = True    #  Range     scope_x = (0, SCREEN_WIDTH // SIZE - 1)    scope_y = (2, SCREEN_HEIGHT // SIZE - 1)    #  The snake     snake = deque()    #  food     food_x = 0    food_y = 0

Initialize snakes and food :

 #  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) in snake:            #  To prevent food from coming out of the snake             food_x = random.randint(scope_x[0], scope_x[1])            food_y = random.randint(scope_y[0], scope_y[1])    _init_snake()    _create_food()

All the code :

""" Greedy Snake games """import randomimport sysimport timeimport pygamefrom pygame.locals import *from collections import dequeSCREEN_WIDTH = 600SCREEN_HEIGHT = 480SIZE = 20def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):    imgText = font.render(text, True, fcolor)    screen.blit(imgText, (x, y))def main():    pygame.init()    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))    pygame.display.set_caption(' snake ')    light = (100, 100, 100)  #  The color of the snake     dark = (200, 200, 200)  #  The color of the food     font1 = pygame.font.SysFont('SimHei', 24)  #  The font of the score     font2 = pygame.font.Font(None, 72)  # GAME OVER  The font of     red = (200, 30, 30)  # GAME OVER  Font color for     fwidth, fheight = font2.size('GAME OVER')    line_width = 1  #  Grid line width     black = (0, 0, 0)  #  Grid line color     bgcolor = (40, 40, 60)  #  Background color     #  Direction , Start right     pos_x = 1    pos_y = 0    #  If the snake is moving to the right , Then quickly click down and left , Because the program refresh is not so fast , The down event will be overwritten to the left , Cause the snake to retreat , direct GAME OVER    # b  Variables are used to prevent this from happening     b = True    #  Range     scope_x = (0, SCREEN_WIDTH // SIZE - 1)    scope_y = (2, SCREEN_HEIGHT // SIZE - 1)    #  The snake     snake = deque()    #  food     food_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) in snake:            #  To prevent food from coming out of the snake             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  #  Do you want to start , When start = True,game_over = True  when , Only show  GAME OVER    score = 0  #  score     orispeed = 0.5  #  Raw speed     speed = orispeed    last_move_time = None    pause = False  #  Pause     while True:        for event in pygame.event.get():            if event.type == QUIT:                sys.exit()            elif event.type == KEYDOWN:                if event.key == K_RETURN:                    if game_over:                        start = True                        game_over = False                        b = True                        _init_snake()                        _create_food()                        pos_x = 1                        pos_y = 0                        #  score                         score = 0                        last_move_time = time.time()                elif event.key == K_SPACE:                    if not game_over:                        pause = not pause                elif event.key in (K_w, K_UP):                    #  This judgment is to prevent the snake from pressing the down button when it moves up , Lead to direct  GAME OVER                    if b and not pos_y:                        pos_x = 0                        pos_y = -1                        b = False                elif event.key in (K_s, K_DOWN):                    if b and not pos_y:                        pos_x = 0                        pos_y = 1                        b = False                elif event.key in (K_a, K_LEFT):                    if b and not pos_x:                        pos_x = -1                        pos_y = 0                        b = False                elif event.key in (K_d, K_RIGHT):                    if b and not pos_x:                        pos_x = 1                        pos_y = 0                        b = False        #  Fill background color         screen.fill(bgcolor)        #  Painted grid lines   A vertical bar         for x in range(SIZE, SCREEN_WIDTH, SIZE):            pygame.draw.line(screen, black, (x, scope_y[0] * SIZE), (x, SCREEN_HEIGHT), line_width)        #  Painted grid lines   Horizontal line         for y in range(scope_y[0] * SIZE, SCREEN_HEIGHT, SIZE):            pygame.draw.line(screen, black, (0, y), (SCREEN_WIDTH, y), line_width)        if game_over:            if start:                print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, 'GAME OVER',                           red)        else:            curTime = time.time()            if curTime - last_move_time > speed:                if not pause:                    b = True                    last_move_time = curTime                    next_s = (snake[0][0] + pos_x, snake[0][1] + pos_y)                    if next_s[0] == food_x and next_s[1] == food_y:                        #  Eat the food                         _create_food()                        snake.appendleft(next_s)                        score += 10                        speed = orispeed - 0.03 * (score // 100)                    else:                        if scope_x[0] <= next_s[0] <= scope_x[1] and scope_y[0] <= next_s[1] <= scope_y[1] \                                and next_s not in snake:                            snake.appendleft(next_s)                            snake.pop()                        else:                            game_over = True        #  Painting food         if not game_over:            #  avoid  GAME OVER  When the time is right  GAME OVER  The words are covered up             pygame.draw.rect(screen, light, (food_x * SIZE, food_y * SIZE, SIZE, SIZE), 0)        #  Draw a snake         for s in snake:            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, 30, 7, f' Speed : {score // 100}')        print_text(screen, font1, 450, 7, f' score : {score}')        pygame.display.update()if __name__ == '__main__':    main()

Here we are , I'm sure you're right “ How do you use it? python To achieve a simple Snake game ” Have a deeper understanding of , You might as well put it into practice ! This is the Yisu cloud website , For more relevant contents, you can enter the relevant channels for inquiry , Pay attention to our , Continue to learn !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved