Pygame Lesson 6 - Snake Game

Today we start the sixth lesson of Pygame. The content of the first few lessons is here [ click me ], welcome everyone to go to archaeology:

insert image description here

Today let's learn to make a small game [Snake], this is a very classic small game, so let's start together

Please add a picture description

1. Game preparation

import pygame, random,os  # 导入pygame模块和random、os模块

os.environ["SDL_VIDEO_WINDOW_POS"]="100,100"  # 设置环境变量,设置窗口的位置在屏幕左上角(100,100)的位置

pygame.init()  # 初始化pygame

time_clock = pygame.time.Clock()  # 创建一个Clock对象用于控制游戏的速度

sc = pygame.display.set_mode((640, 480))  # 创建一个窗口,大小为640x480像素
pygame.display.set_caption("贪吃蛇")  # 设置窗口标题为“贪吃蛇”

font = pygame.font.SysFont("宋体", 48 , True)  # 创建一个字体对象,字体为宋体,大小为48像素,加粗显示

pink = (255, 182, 193)  # 定义颜色pink为RGB值(255, 182, 193)
violet = (238,130,238)  # 定义颜色violet为RGB值(238,130,238)
white = (255, 255, 255)  # 定义颜色white为RGB值(255, 255, 255)
green = (0,255,0)  # 定义颜色green为RGB值(0,255,0)
red = (255,0,0)  # 定义颜色red为RGB值(255,0,0)

Each line of code here is commented

os.environ["SDL_VIDEO_WINDOW_POS"]="100,100": This line refers to the initial position of the upper left corner of Pygame when running the code

time_clock = pygame.time.Clock(): Create a Clock object to control the speed of the game

2. Next, we create a [snake] class

class Snake():
    def __init__(self):
        self.direction = "right"
        # 定义一个贪吃蛇的长度列表,其中有几个元素就代表有几段身体
        self.body = [[100, 100], [80, 100]]
        self.head = list(self.body[0])  # 蛇头位置
    def draw_me(self):
        # 绘制身体
        for b in self.body:
            pygame.draw.rect(sc, green, (b[0], b[1], 20, 20))

    def move_head(self):
        # 根据方向移动蛇头
        if self.direction == "right":
            self.head[0] += 20
        elif self.direction == "left":
            self.head[0] -= 20
        elif self.direction == "up":
            self.head[1] -= 20
        elif self.direction == "down":
            self.head[1] += 20

    def add_body(self):
        self.body.insert(0, list(self.head))
    def cut_tail(self):
        self.body.pop()
    def move_snake(self):
        self.add_body()
        self.cut_tail()

Code comments:

self.direction = "right": Refers to the initial direction of [Greedy Snake] when it was born

self.body = [[100, 100], [80, 100]]: Initial small grid coordinates (with the upper left corner as the origin)

self.head = list(self.body[0])# The position of the snake head, the coordinates of the snake head

Function [ draw_me], use * pygame.draw.rect(sc, green, (b[0], b[1], 20, 20))*, this has been mentioned in the third lesson: click me to review the third lesson

Function [ move_head], movement function, the left and right movement is related to the X axis, so the * in the code takes the head head[0], and the up and down movement is related to the Y axis, so thehead[1] * in the code takes the head

Function [ add_body]: increase the small square of the body, this is the function called after eating food

Function [ cut_tail]: This is the small square to delete the tail

Function [ move_snake], this function calls [ add_body, cut_tail], one is added to the head, one is subtracted from the tail, one is added to the head, one is subtracted from the tail, one is added to the head, one is subtracted from the tail..., this is moving

3. Next, we create a [snake] class

# 食物类的设计
class Food():
    def __init__(self):
        self.color=white
        #知识进阶-双倍奖励
        #self.color=random.choice([white,pink])
        x = random.randrange(0, 640,20)
        y = random.randrange(0, 480,20)
        self.postion = [x,y]
    def draw_me(self):
        pygame.draw.rect(sc, self.color, (self.postion[0], self.postion[1], 20, 20))
    def reset(self):
        x = random.randrange(0, 640,20)
        y = random.randrange(0, 480,20)
        self.postion = [x,y]
        #知识进阶-双倍奖励
        #self.color=random.choice([white,pink])

code comment

self.color=white, the initial color of the food is white

x = random.randrange(0, 640,20), y = random.randrange(0, 480,20), this means that the food cannot exceed the size of the game interface, the X axis is 0 to 640 with a step size of 20, and the Y axis is 0 to 480 with a step size of 20,都是随机的

Knowledge advancement - double rewards self.color=random.choice([white,pink]), colors can be randomly selected

4. Finishing

food = Food()
snake = Snake()
while True:
    len_text = font.render("Length:  "+str(len(snake.body)),True,red)
    # 从队列中获取事件
    for event in pygame.event.get():
        # 判断是否为退出事件
        if event.type == pygame.QUIT:
            pygame.quit()
        # 按键事件
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                if  snake.direction != "left":
                    snake.direction = "right"
            if event.key == pygame.K_LEFT:
                if snake.direction != "right":
                    snake.direction = "left"
            if event.key == pygame.K_UP:
                if  snake.direction != "down":
                    snake.direction = "up"
            if event.key == pygame.K_DOWN:
                if snake.direction != "up":
                    snake.direction = "down"
    # 判断是否吃到食物
    if snake.head == food.postion:
        food.reset()
        snake.add_body()
        '''
        #知识进阶-双倍奖励
        if food.color==white:
            food.reset()
            snake.add_body()
        else:
            food.reset()
            snake.add_body()
            snake.add_body()
        '''
    # 判断是否碰到边缘
    if snake.head[0] > 620 or snake.head[0] < 0:
        break
    if snake.head[1] > 460 or snake.head[1] < 0:
        break
    # 移动头部和身体
    snake.move_head()
    snake.move_snake()
    # 绘制游戏界面
    sc.fill(violet)
    snake.draw_me()
    food.draw_me()
    sc.blit(len_text ,(50,20))
    pygame.display.update()

    # 控制游戏速度
    time_clock.tick(3)
# 动手实践-GAME OVER
len_text = font.render("GAME OVER",True,red)
sc.blit(len_text ,(200,200))
pygame.display.update()
input()

code comment

# Judging whether it touches the edge, this is to judge whether the snake moves out of the window, otherwise stop the game

if snake.head[0] > 620 or snake.head[0] < 0:
    break
if snake.head[1] > 460 or snake.head[1] < 0:
    break

sc.fill(violet): Game background color, you can change it by yourself

time_clock.tick(3): Control the game speed Control the game speed, the bigger the faster

5. Full version code:

import pygame, random,os
os.environ["SDL_VIDEO_WINDOW_POS"]="100,100"
# 初始化
pygame.init()
# 定义一个变量来控制速度
time_clock = pygame.time.Clock()

# 创建窗口,定义标题
sc = pygame.display.set_mode((640, 480))
pygame.display.set_caption("贪吃蛇")
# 实例化字体对象
font = pygame.font.SysFont("宋体", 48 , True)
# 定义颜色
pink = (255, 182, 193)
violet = (238,130,238)
white = (255, 255, 255)
green = (0,255,0)
red = (255,0,0)
class Snake():
    def __init__(self):
        self.direction = "right"
        # 定义一个贪吃蛇的长度列表,其中有几个元素就代表有几段身体
        self.body = [[100, 100], [80, 100]]
        self.head = list(self.body[0])  # 蛇头位置
    def draw_me(self):
        # 绘制身体
        for b in self.body:
            pygame.draw.rect(sc, green, (b[0], b[1], 20, 20))

    def move_head(self):
        # 根据方向移动蛇头
        if self.direction == "right":
            self.head[0] += 20
        elif self.direction == "left":
            self.head[0] -= 20
        elif self.direction == "up":
            self.head[1] -= 20
        elif self.direction == "down":
            self.head[1] += 20

    def add_body(self):
        self.body.insert(0, list(self.head))
    def cut_tail(self):
        self.body.pop()
    def move_snake(self):
        self.add_body()
        self.cut_tail()
 
# 食物类的设计
class Food():
    def __init__(self):
        self.color=white
        #知识进阶-双倍奖励
        #self.color=random.choice([white,pink])
        x = random.randrange(0, 640,20)
        y = random.randrange(0, 480,20)
        self.postion = [x,y]
    def draw_me(self):
        pygame.draw.rect(sc, self.color, (self.postion[0], self.postion[1], 20, 20))
    def reset(self):
        x = random.randrange(0, 640,20)
        y = random.randrange(0, 480,20)
        self.postion = [x,y]
        #知识进阶-双倍奖励
        #self.color=random.choice([white,pink])
 
food = Food()
snake = Snake()
while True:
    len_text = font.render("Length:  "+str(len(snake.body)),True,red)
    # 从队列中获取事件
    for event in pygame.event.get():
        # 判断是否为退出事件
        if event.type == pygame.QUIT:
            pygame.quit()
        # 按键事件
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                if  snake.direction != "left":
                    snake.direction = "right"
            if event.key == pygame.K_LEFT:
                if snake.direction != "right":
                    snake.direction = "left"
            if event.key == pygame.K_UP:
                if  snake.direction != "down":
                    snake.direction = "up"
            if event.key == pygame.K_DOWN:
                if snake.direction != "up":
                    snake.direction = "down"
    # 判断是否吃到食物
    if snake.head == food.postion:
        food.reset()
        snake.add_body()
        '''
        #知识进阶-双倍奖励
        if food.color==white:
            food.reset()
            snake.add_body()
        else:
            food.reset()
            snake.add_body()
            snake.add_body()
        '''
    # 判断是否碰到边缘
    if snake.head[0] > 620 or snake.head[0] < 0:
        break
    if snake.head[1] > 460 or snake.head[1] < 0:
        break
    # 移动头部和身体
    snake.move_head()
    snake.move_snake()
    # 绘制游戏界面
    sc.fill(violet)
    snake.draw_me()
    food.draw_me()
    sc.blit(len_text ,(50,20))
    pygame.display.update()

    # 控制游戏速度
    time_clock.tick(3)
# 动手实践-GAME OVER
len_text = font.render("GAME OVER",True,red)
sc.blit(len_text ,(200,200))
pygame.display.update()
input()

I hope everyone has to help

A little programmer dedicated to office automation#

I've seen this, follow + like + bookmark = don't get lost! !

If you want to know more about Python office automation, please pay attention!

Guess you like

Origin blog.csdn.net/weixin_42636075/article/details/132341210