当前位置:   article > 正文

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

kitten.n的贪吃蛇代码怎么编


欢迎关注 『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()
  • 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
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154

总结

大家喜欢的话,给个

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