【Python黑科技】tkinter库实战“贪吃蛇”小游戏(保姆级图文+实现代码)


欢迎关注 『Python黑科技』 系列,持续更新中
欢迎关注 『Python黑科技』 系列,持续更新中

实现效果

在这里插入图片描述


实现思路

  • 初始状态的蛇的长 3个像素点,食物 1 个像素点,
  • 蛇长度增加:蛇吃到了食物,蛇头的坐标等于食物的坐标,那么在第 2 点的坐标不用去掉,视觉上就增长了蛇身
  • 吃到食物的声音提示

离开空间或是碰撞到自己身体都会算失败。

#功能逻辑
if path.exists(‘eat.wav’):
sound_wav = pygame.mixer.Sound(“eat.wav”)
sound = True
title_font = pygame.font.SysFont(‘simsunnsimsun’, 32)
welcome_words = title_font.render(
‘贪吃蛇’, True, (0, 0, 0), (255, 255, 255))
tips_font = pygame.font.SysFont(‘simsunnsimsun’, 20)
start_game_words = tips_font.render(
‘点击开始’, True, (0, 0, 0), (255, 255, 255))
close_game_words = tips_font.render(
‘按ESC退出’, True, (0, 0, 0), (255, 255, 255))
gameover_words = title_font.render(
‘游戏结束’, True, (205, 92, 92), (255, 255, 255))
win_words = title_font.render(
‘蛇很长了,你赢了!’, True, (0, 0, 205), (255, 255, 255))
screen = pygame.display.set_mode((640, 480), 0, 32)

  • 控制贪吃蛇运动方向

#控制贪吃蛇运动方向
def direction_check(moving_direction, change_direction):
directions = [[‘up’, ‘down’], [‘left’, ‘right’]]
if moving_direction in directions[0] and change_direction in directions[1]:
return change_direction
elif moving_direction in directions[1] and change_direction in directions[0]:
return change_direction
return moving_direction


实现代码

通过w|s|a|d控制贪吃蛇的上下左右运动

# @Time    : 2022/2/9 20:13
# @Author  : 南黎
# @FileName: 贪吃蛇.py

import pygame
from os import path
from sys import exit
from time import sleep
from random import choice
from itertools import product
from pygame.locals import QUIT, KEYDOWN


def direction_check(moving_direction, change_direction):
    directions = [['up', 'down'], ['left', 'right']]
    if moving_direction in directions[0] and change_direction in directions[1]:
        return change_direction
    elif moving_direction in directions[1] and change_direction in directions[0]:
        return change_direction
    return moving_direction


class Snake:
    colors = list(product([0, 64, 128, 192, 255], repeat=3))[1:-1]

    def __init__(self):
        self.map = {(x, y): 0 for x in range(32) for y in range(24)}
        self.body = [[100, 100], [120, 100], [140, 100]]
        self.head = [140, 100]
        self.food = []
        self.food_color = []
        self.moving_direction = 'right'
        self.speed = 4
        self.generate_food()
        self.game_started = False

    def check_game_status(self):
        if self.body.count(self.head) > 1:
            return True
        if self.head[0] < 0 or self.head[0] > 620 or self.head[1] < 0 or self.head[1] > 460:
            return True
        return False

    def move_head(self):
        moves = {
            'right': (20, 0),
            'up': (0, -20),
            'down': (0, 20),
            'left': (-20, 0)
        }
        step = moves[self.moving_direction]
        self.head[0] += step[0]
        self.head[1] += step[1]

    def generate_food(self):
        self.speed = len(
            self.body) // 16 if len(self.body) // 16 > 4 else self.speed
        for seg in self.body:
            x, y = seg
            self.map[x // 20, y // 20] = 1
        empty_pos = [pos for pos in self.map.keys() if not self.map[pos]]
        result = choice(empty_pos)
        self.food_color = list(choice(self.colors))
        self.food = [result[0] * 20, result[1] * 20]


def main():
    key_direction_dict = {
        119: 'up',  # W
        115: 'down',  # S
        97: 'left',  # A
        100: 'right',  # D
        273: 'up',  # UP
        274: 'down',  # DOWN
        276: 'left',  # LEFT
        275: 'right',  # RIGHT
    }

    fps_clock = pygame.time.Clock()
    pygame.init()
    pygame.mixer.init()
    snake = Snake()
    sound = False
    if path.exists('eat.wav'):
        sound_wav = pygame.mixer.Sound("eat.wav")
        sound = True
    title_font = pygame.font.SysFont('simsunnsimsun', 32)
    welcome_words = title_font.render(
        '贪吃蛇', True, (0, 0, 0), (255, 255, 255))
    tips_font = pygame.font.SysFont('simsunnsimsun', 20)
    start_game_words = tips_font.render(
        '点击开始', True, (0, 0, 0), (255, 255, 255))
    close_game_words = tips_font.render(
        '按ESC退出', True, (0, 0, 0), (255, 255, 255))
    gameover_words = title_font.render(
        '游戏结束', True, (205, 92, 92), (255, 255, 255))
    win_words = title_font.render(
        '蛇很长了,你赢了!', True, (0, 0, 205), (255, 255, 255))
    screen = pygame.display.set_mode((640, 480), 0, 32)
    pygame.display.set_caption('贪吃蛇')
    new_direction = snake.moving_direction
    while 1:
        for event in pygame.event.get():
            if event.type == QUIT:
                exit()
            elif event.type == KEYDOWN:
                if event.key == 27:
                    exit()
                if snake.game_started and event.key in key_direction_dict:
                    direction = key_direction_dict[event.key]
                    new_direction = direction_check(
                        snake.moving_direction, direction)
            elif (not snake.game_started) and event.type == pygame.MOUSEBUTTONDOWN:
                x, y = pygame.mouse.get_pos()
                if 213 <= x <= 422 and 304 <= y <= 342:
                    snake.game_started = True
        screen.fill((255, 255, 255))
        if snake.game_started:
            snake.moving_direction = new_direction  # 在这里赋值,而不是在event事件的循环中赋值,避免按键太快
            snake.move_head()
            snake.body.append(snake.head[:])
            if snake.head == snake.food:
                if sound:
                    sound_wav.play()
                snake.generate_food()
            else:
                snake.body.pop(0)
            for seg in snake.body:
                pygame.draw.rect(screen, [0, 0, 0], [
                    seg[0], seg[1], 20, 20], 0)
            pygame.draw.rect(screen, snake.food_color, [
                snake.food[0], snake.food[1], 20, 20], 0)
            if snake.check_game_status():
                screen.blit(gameover_words, (241, 310))
                pygame.display.update()
                snake = Snake()
                new_direction = snake.moving_direction
                sleep(3)
            elif len(snake.body) == 512:
                screen.blit(win_words, (33, 210))
                pygame.display.update()
                snake = Snake()
                new_direction = snake.moving_direction
                sleep(3)
        else:
            screen.blit(welcome_words, (240, 150))
            screen.blit(start_game_words, (246, 310))
            screen.blit(close_game_words, (246, 350))
        pygame.display.update()
        fps_clock.tick(snake.speed)


if __name__ == '__main__':
    main()

总结

大家喜欢的话,给个👍,点个关注!给大家分享更多有趣好玩的Python黑科技!

欢迎关注 『Python黑科技』 系列,持续更新中
欢迎关注 『Python黑科技』 系列,持续更新中
【Python黑科技】tkinter库实战7个小项目合集(保姆级图文+实现代码)
【Python黑科技】tkinter库实战制作一个计算器(保姆级图文+实现代码)
【Python黑科技】tkinter库实战制作一个记事本(保姆级图文+实现代码)
【Python黑科技】tkinter库实战用户的注册和登录(保姆级图文+实现代码)
【Python黑科技】tkinter库实战“2048”小游戏(保姆级图文+实现代码)
【Python黑科技】tkinter库实战“俄罗斯方块”小游戏(保姆级图文+实现代码)
【Python黑科技】tkinter库实战“贪吃蛇”小游戏(保姆级图文+实现代码)
【Python黑科技】tkinter库实战“连连看”小游戏(保姆级图文+实现代码)

【Python安装第三方库一行命令永久提高速度】
【使用PyInstaller打包exe】
【免登陆爬虫一键下载知乎文章图片(保姆级图文+实现代码)】
【孤独的程序员和AI机器人朋友聊天解闷(免费接口+保姆级图文+实现代码注释)】
【几行代码绘制gif动图(保姆级图文+实现代码)】
【几行代码实现网课定时循环截屏,保存重要知识点(保姆级图文+实现代码)】
【常用的user_agent 浏览器头爬虫模拟用户(保姆级图文+实现代码)】
【更多内容敬请期待】


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发现你走远了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值