初学python,跟着各种教程写了个贪吃蛇小游戏。
部分代码借鉴了以下视频中的内容:
【智源学院】Python实战案例 — 贪吃蛇 (pygame)_哔哩哔哩_bilibili
以下为代码:
# 初始框架
import pygame
import random
class Point: # 将每个小方格定义为类似于坐标的形式
col = 0
row = 0
def __init__(self, row, col):
self.row = row
self.col = col
def copy(self):
return Point(row=self.row, col=self.col)
# 初始化
pygame.init()
clock = pygame.time.Clock()
W = 800 # 游戏部分窗口宽度
W_W = 1000 # 窗口总宽度
H = 600
ROW = 30 # 小方格行数
COL = 40 # 小方格列数
size = (W_W, H)
window = pygame.display.set_mode(size) # 窗口大小
pygame.display.set_caption('贪吃蛇')
game_continue = True # 控制开始和暂停的变量
dead = False # 控制是否游戏结束的变量
score = 0 # 计分
# 定义坐标和颜色
head = Point(row=int(ROW / 2), col=int(COL / 2)) # 初始时蛇头位置
head_color = (0, 128, 128) # 蛇头颜色
bg_color = (255, 255, 255) # 背景颜色
bg_color_right = (0, 200, 200) # 右侧颜色
snake_color = (200, 200, 200) # 蛇身颜色
font_color = (0, 0, 0) # 字体颜色
direct = 'left' # 开始时向左出发
snakes = [] # 蛇身坐标以链表形式存储
# 生成食物的函数
def gen_food():
while True:
pos = Point(row=random.randint(0, ROW - 1), col=random.randint(0, COL - 1))