150行python代码实现贪吃蛇游戏
作者:Code进阶狼人 时间:2021-07-15 06:43:20
上篇博文我们实现了两百行代码实现贪吃蛇游戏,这次我们来实现一个代码量更加少,功能却更加完整的
python代码实现贪吃蛇游戏,具体代码与文件可以访问我的GitHub地址获取
游戏截图
动图
贪吃蛇python代码
"""贪吃蛇"""
import random
import sys
import time
import pygame
from pygame.locals import *
from collections import deque
SCREEN_WIDTH = 600 # 屏幕宽度
SCREEN_HEIGHT = 480 # 屏幕高度
SIZE = 20 # 小方格大小
LINE_WIDTH = 1 # 网格线宽度
# 游戏区域的坐标范围
SCOPE_X = (0, SCREEN_WIDTH // SIZE - 1)
SCOPE_Y = (2, SCREEN_HEIGHT // SIZE - 1)
# 食物的分值及颜色
FOOD_STYLE_LIST = [(10, (255, 100, 100)), (20, (100, 255, 100)), (30, (100, 100, 255))]
LIGHT = (100, 100, 100)
DARK = (200, 200, 200) # 蛇的颜色
BLACK = (0, 0, 0) # 网格线颜色
RED = (200, 30, 30) # 红色,GAME OVER 的字体颜色
BGCOLOR = (40, 40, 60) # 背景色
def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
imgText = font.render(text, True, fcolor)
screen.blit(imgText, (x, y))
# 初始化蛇
def init_snake():
snake = deque()
snake.append((2, SCOPE_Y[0]))
snake.append((1, SCOPE_Y[0]))
snake.append((0, SCOPE_Y[0]))
return snake
def create_food(snake):
food_x = random.randint(SCOPE_X[0], SCOPE_X[1])
food_y = random.randint(SCOPE_Y[0], SCOPE_Y[1])
while (food_x, food_y) in snake:
# 如果食物出现在蛇身上,则重来
food_x = random.randint(SCOPE_X[0], SCOPE_X[1])
food_y = random.randint(SCOPE_Y[0], SCOPE_Y[1])
return food_x, food_y
def get_food_style():
return FOOD_STYLE_LIST[random.randint(0, 2)]
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('贪吃蛇')
font1 = pygame.font.SysFont('SimHei', 24) # 得分的字体
font2 = pygame.font.Font(None, 72) # GAME OVER 的字体
fwidth, fheight = font2.size('GAME OVER')
# 如果蛇正在向右移动,那么快速点击向下向左,由于程序刷新没那么快,向下事件会被向左覆盖掉,导致蛇后退,直接GAME OVER
# b 变量就是用于防止这种情况的发生
b = True
# 蛇
snake = init_snake()
# 食物
food = create_food(snake)
food_style = get_food_style()
# 方向
pos = (1, 0)
game_over = True
start = False # 是否开始,当start = True,game_over = True 时,才显示 GAME OVER
score = 0 # 得分
orispeed = 0.5 # 原始速度
speed = orispeed
last_move_time = None
pause = False # 暂停
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_RETURN:
if game_over:
start = True
game_over = False
b = True
snake = init_snake()
food = create_food(snake)
food_style = get_food_style()
pos = (1, 0)
# 得分
score = 0
last_move_time = time.time()
elif event.key == K_SPACE:
if not game_over:
pause = not pause
elif event.key in (K_w, K_UP):
# 这个判断是为了防止蛇向上移时按了向下键,导致直接 GAME OVER
if b and not pos[1]:
pos = (0, -1)
b = False
elif event.key in (K_s, K_DOWN):
if b and not pos[1]:
pos = (0, 1)
b = False
elif event.key in (K_a, K_LEFT):
if b and not pos[0]:
pos = (-1, 0)
b = False
elif event.key in (K_d, K_RIGHT):
if b and not pos[0]:
pos = (1, 0)
b = False
# 填充背景色
screen.fill(BGCOLOR)
# 画网格线 竖线
for x in range(SIZE, SCREEN_WIDTH, SIZE):
pygame.draw.line(screen, BLACK, (x, SCOPE_Y[0] * SIZE), (x, SCREEN_HEIGHT), LINE_WIDTH)
# 画网格线 横线
for y in range(SCOPE_Y[0] * SIZE, SCREEN_HEIGHT, SIZE):
pygame.draw.line(screen, BLACK, (0, y), (SCREEN_WIDTH, y), LINE_WIDTH)
if not game_over:
curTime = time.time()
if curTime - last_move_time > speed:
if not pause:
b = True
last_move_time = curTime
next_s = (snake[0][0] + pos[0], snake[0][1] + pos[1])
if next_s == food:
# 吃到了食物
snake.appendleft(next_s)
score += food_style[0]
speed = orispeed - 0.03 * (score // 100)
food = create_food(snake)
food_style = get_food_style()
else:
if SCOPE_X[0] <= next_s[0] <= SCOPE_X[1] and SCOPE_Y[0] <= next_s[1] <= SCOPE_Y[1] \
and next_s not in snake:
snake.appendleft(next_s)
snake.pop()
else:
game_over = True
# 画食物
if not game_over:
# 避免 GAME OVER 的时候把 GAME OVER 的字给遮住了
pygame.draw.rect(screen, food_style[1], (food[0] * SIZE, food[1] * SIZE, SIZE, SIZE), 0)
# 画蛇
for s in snake:
pygame.draw.rect(screen, DARK, (s[0] * SIZE + LINE_WIDTH, s[1] * SIZE + LINE_WIDTH,
SIZE - LINE_WIDTH * 2, SIZE - LINE_WIDTH * 2), 0)
print_text(screen, font1, 30, 7, f'速度: {score//100}')
print_text(screen, font1, 450, 7, f'得分: {score}')
if game_over:
if start:
print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, 'GAME OVER', RED)
pygame.display.update()
if __name__ == '__main__':
main()
更多有趣的经典小游戏实现专题,分享给大家:
C++经典小游戏汇总
python经典小游戏汇总
python俄罗斯方块游戏集合
JavaScript经典游戏 玩不停
java经典小游戏汇总
javascript经典小游戏汇总
来源:https://blog.csdn.net/liuzuoping/article/details/103395517
标签:python,贪吃蛇
0
投稿
猜你喜欢
Servermanager启动连接数据库错误如何解决
2024-01-13 23:46:55
用面包屑来简化多层的tabs
2011-06-16 20:32:54
jupyter notebook读取/导出文件/图片实例
2022-01-05 00:28:45
如何在windows下安装Pycham2020软件(方法步骤详解)
2023-05-19 14:07:30
深入研究WINDOW.EVENT对象
2012-04-26 16:31:58
Python实现测试磁盘性能的方法
2022-01-31 19:00:46
javascript对select标签的控制(option选项/select)
2024-04-19 10:15:54
php curl登陆qq后获取用户信息时证书错误
2023-11-15 08:23:39
GO语言ini配置文件的读取的操作
2024-04-23 09:38:36
解决win10 vscode 无法激活python 虚拟环境的问题
2023-10-09 04:23:25
Python3计算三角形的面积代码
2022-06-20 21:03:54
基于node打包可执行文件工具_Pkg使用心得分享
2024-05-08 09:37:47
SQL查询服务器下所有数据库及数据库的全部表
2024-01-18 22:55:01
JS动态创建Table,Tr,Td并赋值的具体实现
2024-04-10 11:02:39
Python Pandas list列表数据列拆分成多行的方法实现
2021-04-20 18:56:01
ASP.NET MVC Bundles 用法和说明(打包javascript和css)
2023-07-17 01:20:59
Go使用协程批量获取数据加快接口返回速度
2024-05-21 10:23:38
解析MSSQL跨数据库查询的实现方法
2024-01-21 20:19:19
详解Vue.use自定义自己的全局组件
2024-05-02 17:02:59
MySQL索引类型Normal、Unique和Full Text的讲解
2024-01-20 09:56:19