当前位置:   article > 正文

贪吃蛇大作战(面向对象)_import pygameimport random# 初始化 pygamepygame.init(

import pygameimport random# 初始化 pygamepygame.init()# 设定屏幕大小scre

贪吃蛇大作战

想要提高编程能力就要多敲代码,自己写一款小游戏是一个很不错的练习方式,接下来我们一起来完成一款经典的游戏贪吃蛇大作战, 在实践过程中体会面向对象的优点

游戏流程请添加图片描述

1.初始化游戏窗口

# 初始化 Pygame
pygame.init()
# 设置游戏界面大小、背景颜色和游戏标题
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('贪吃蛇')
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
snake_size = 20

# 定义一个计时器来控制蛇的移动速度
clock = pygame.time.Clock()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

2.定义相关类

定义snake类


class snake(object):
    # 初始化蛇的初始位置、大小和速度
    def __init__(self):

        self.snake_x = 100
        self.snake_y = 100
        self.snake_size = 20
        self.snake_speed = 5

    # 定义蛇的移动方向
    snake_direction = 'right'
    # 定义一个列表来保存蛇的身体坐标
    snake_body = []

    def move_(self, snake_direction):
        if snake_direction == 'up':
            self.snake_y -= self.snake_speed
        elif snake_direction == 'down':
            self.snake_y += self.snake_speed
        elif snake_direction == 'left':
            self.snake_x -= self.snake_speed
        elif snake_direction == 'right':
            self.snake_x += self.snake_speed
        self.snake_direction=snake_direction
        self.snake_body.insert(0, [self.snake_x, self.snake_y])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

每移动一步,将新的头部坐标加入snake_body[0],后面会有更新身体操作

定义food类


# 定义食物的大小
food_size = 20
#定义食物类
class food(object):
    def __init__(self,food_x,food_y):
        self.food_x = food_x
        self.food_y = food_y
  #检测食物是否被吃
    def ate(self, snake):
        snake_x = snake.snake_x
        snake_y = snake.snake_y
        food_x = self.food_x
        food_y = self.food_y
        if (snake_x == food_x and snake_y == food_y) or (snake_x == food_x and abs(snake_y - food_y) < snake_size) or (
                snake_y == food_y and abs(snake_x - food_x) < snake_size):
            self.food_x = random.randrange(0, screen_width - snake_size, 10)
            self.food_y = random.randrange(0, screen_height - snake_size, 10)

            snake.snake_body.append([snake_x, snake_y])

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

蛇吃到食物的3种情况

  1. 蛇头坐标和食物坐标重合(snake_x == food_x and snake_y == food_y)
  2. 蛇从左右两侧碰到食物(snake_x == food_x and abs(snake_y - food_y) < snake_size)
  3. 蛇从上下两侧碰到食物 snake_y == food_y and abs(snake_x - food_x) < snake_size)

3.游戏的主体部分

1.定义一个draw函数

# 定义一个函数来绘制蛇和食物
def draw(snake, food):
    screen.fill(BLACK)

    for pos in snake.snake_body:
        pygame.draw.rect(screen, GREEN, [pos[0], pos[1], snake_size, snake_size])
    print(food.food_x, food.food_y)
    pygame.draw.rect(screen, RED, [food.food_x, food.food_y, food_size, food_size])

    pygame.display.update()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

函数最开始一定要进行screen.fill(BLACK),清空整个窗口,因为pygame.display.update()是在原来的基础上进行更新,会保留蛇和食物的痕迹

2.main()函数

# 主循环
def main(snake,food):
    while True:
        snake_direction = snake.snake_direction
        # 处理事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # 退出游戏
                pygame.quit()
                quit()

            # 处理按键事件
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    snake_direction = 'up'
                elif event.key == pygame.K_DOWN:
                    snake_direction = 'down'
                elif event.key == pygame.K_LEFT:
                    snake_direction = 'left'
                elif event.key == pygame.K_RIGHT:
                    snake_direction = 'right'

            # 移动蛇的头部
        snake.move_( snake_direction)

        # 判断是否吃到食物
        food.ate(snake)


        # 更新蛇的身体坐标
        if len(snake.snake_body) > 1:
            snake.snake_body.pop()
        # 判断游戏是否结束
        snake_x = snake.snake_x
        snake_y = snake.snake_y
        food_x = food.food_x
        food_y = food.food_y
        snake_body = snake.snake_body
        if snake_x < 0 or snake_x > screen_width - snake_size or snake_y < 0 or snake_y > screen_height - snake_size or [
            snake_x, snake_y] in snake_body[1:]:
            # 游戏结束,显示分数并等待退出
            font = pygame.font.Font(None, 36)
            text = font.render('Score: ' + str(len(snake_body)), True, WHITE)
            screen.blit(text, ((screen_width - text.get_width()) / 2, (screen_height - text.get_height()) / 2))
            pygame.display.update()
            pygame.time.wait(2000)
            pygame.quit()
            quit()
        # 绘制蛇和食物

        draw(snake, food)

        # 控制蛇的移动速度
        clock.tick(20)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

游戏结束的2种情况
1.蛇撞墙(snake_x < 0 or snake_x > screen_width - snake_size or snake_y < 0 or snake_y > screen_height - snake_size)
2.蛇吃自己 ([ snake_x, snake_y] in snake_body[1:])

4.成果展示

 到这里游戏以及圆满完成了,来看看运行效果
  • 1

请添加图片描述
完整代码

import pygame
import random

# 初始化 Pygame
pygame.init()

# 设置游戏界面大小、背景颜色和游戏标题
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('贪吃蛇')

# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
snake_size = 20

# 定义一个计时器来控制蛇的移动速度
clock = pygame.time.Clock()


class snake(object):
    # 初始化蛇的初始位置、大小和速度
    def __init__(self):

        self.snake_x = 100
        self.snake_y = 100
        self.snake_size = 20
        self.snake_speed = 5

    # 定义蛇的移动方向
    snake_direction = 'right'
    # 定义一个列表来保存蛇的身体坐标
    snake_body = []

    def move_(self, snake_direction):
        if snake_direction == 'up':
            self.snake_y -= self.snake_speed
        elif snake_direction == 'down':
            self.snake_y += self.snake_speed
        elif snake_direction == 'left':
            self.snake_x -= self.snake_speed
        elif snake_direction == 'right':
            self.snake_x += self.snake_speed
        self.snake_direction=snake_direction
        self.snake_body.insert(0, [self.snake_x, self.snake_y])


# 定义食物的大小
food_size = 20
#定义食物类
class food(object):
    def __init__(self,food_x,food_y):
        self.food_x = food_x
        self.food_y = food_y

    def ate(self, snake):
        snake_x = snake.snake_x
        snake_y = snake.snake_y
        food_x = self.food_x
        food_y = self.food_y
        if (snake_x == food_x and snake_y == food_y) or (snake_x == food_x and abs(snake_y - food_y) < snake_size) or (
                snake_y == food_y and abs(snake_x - food_x) < snake_size):
            self.food_x = random.randrange(0, screen_width - snake_size, 10)
            self.food_y = random.randrange(0, screen_height - snake_size, 10)

            snake.snake_body.append([snake_x, snake_y])


# 定义一个函数来绘制蛇和食物
def draw(snake, food):
    screen.fill(BLACK)

    for pos in snake.snake_body:
        pygame.draw.rect(screen, GREEN, [pos[0], pos[1], snake_size, snake_size])
    print(food.food_x, food.food_y)
    pygame.draw.rect(screen, RED, [food.food_x, food.food_y, food_size, food_size])

    pygame.display.update()


# 主循环
def main(snake,food):
    while True:
        snake_direction = snake.snake_direction
        # 处理事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # 退出游戏
                pygame.quit()
                quit()

            # 处理按键事件
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    snake_direction = 'up'
                elif event.key == pygame.K_DOWN:
                    snake_direction = 'down'
                elif event.key == pygame.K_LEFT:
                    snake_direction = 'left'
                elif event.key == pygame.K_RIGHT:
                    snake_direction = 'right'

            # 移动蛇的头部

        snake.move_( snake_direction)
        print(1)
        # 判断是否吃到食物
        food.ate(snake)
        print(2)

        # 更新蛇的身体坐标
        if len(snake.snake_body) > 1:
            snake.snake_body.pop()
        # 判断游戏是否结束
        snake_x = snake.snake_x
        snake_y = snake.snake_y
        food_x = food.food_x
        food_y = food.food_y
        snake_body = snake.snake_body
        if snake_x < 0 or snake_x > screen_width - snake_size or snake_y < 0 or snake_y > screen_height - snake_size or [
            snake_x, snake_y] in snake_body[1:]:
            # 游戏结束,显示分数并等待退出
            font = pygame.font.Font(None, 36)
            text = font.render('Score: ' + str(len(snake_body)), True, WHITE)
            screen.blit(text, ((screen_width - text.get_width()) / 2, (screen_height - text.get_height()) / 2))
            pygame.display.update()
            pygame.time.wait(2000)
            pygame.quit()
            quit()
        # 绘制蛇和食物
        print(3)
        draw(snake, food)

        # 控制蛇的移动速度
        clock.tick(20)


if __name__ == "__main__":
    main( snake(),food(random.randrange(0, screen_width - snake_size, 20),random.randrange(0, screen_width - snake_size, 20)))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142

感谢你的观看,如果对你有帮助的话,请点个赞哦,最后,祝我们一起迈向更高的目标,共同追求卓越与进步!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/303673
推荐阅读
相关标签
  

闽ICP备14008679号