目录
本文的贪吃蛇小游戏根据从零开始用 Python 打造经典贪吃蛇游戏:代码+详解_pygame贪吃蛇游戏代码-CSDN博客进行改进优化,在原有的基础功能上增加了通过界面按钮可选择难度、历史最高分显示、结束游戏可选择继续游戏等功能,进一步优化了小游戏的体验感受。
一.运行效果
游戏开始界面:
游戏界面:
游戏结束界面:
二.使用说明
首先我们打开Pycharm,没有安装的小伙伴可以看这个安装教程。新建一个项目,在项目里新建一个main.py文件,再把完整代码粘贴到main.py文件中,注意:
①.在终端输入以下命令安装pygame库:
pip install pygame
②.修改第31行的save_path为“你项目的地址/score.txt”;
再运行main.py即可。
三.完整代码
话不多少,直接上完整代码:
import pygame
import random
import os
import sys
# 初始化 pygame
pygame.init()
# 屏幕大小
WIDTH, HEIGHT = 600, 400
CELL_SIZE = 20
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
TURQUOISE=(187,255,255)
CYAN=(0,229,238)
CYANA=(0,255,255)
# 创建屏幕
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 初始化时钟
clock = pygame.time.Clock()
#最高分保存地址
save_path = 'D:/pycharm/project/test/score.txt'
#按钮类
class Button:
def __init__(self, text, x, y, width, height, font_size, font_color):
self.text = text
self.rect = pygame.Rect(x, y, width, height)
self.font = pygame.font.Font(None, font_size)
self.text_surf = self.font.render(self.text, True, font_color)
self.text_rect = self.text_surf.get_rect(center=self.rect.center)
def draw(self, screenn,bg_color):
pygame.draw.rect(screenn, bg_color, self.rect)
screen.blit(self.text_surf, self.text_rect)
def is_clicked(self, pos):
if self.rect.collidepoint(pos):
return True
#创建按钮
play_again_button = Button('Play Again', WIDTH // 2 - 100, HEIGHT // 2 + 70, 200, 50, 30, WHITE)
game_over_button = Button('Exit', WIDTH // 2 - 100, HEIGHT // 2 + 20, 200, 50, 30, WHITE)
easy_button = Button('Easy', WIDTH // 2 - 100, HEIGHT // 2 - 50, 200, 30, 30, WHITE)
common_button = Button('Common', WIDTH // 2 - 100, HEIGHT // 2 -20, 200, 30, 30, WHITE)
difficult_button = Button('Diffcult', WIDTH // 2 - 100, HEIGHT // 2 +10, 200, 30, 30, WHITE)
play_button = Button('play', WIDTH // 2 - 100, HEIGHT // 2 +50, 200, 50, 30, WHITE)
def draw_snake(snake_body):
"""绘制蛇的身体"""
for segment in snake_body:
pygame.draw.rect(screen