首页 > Python资料 博客日记
Python版贪吃蛇游戏(开源)
2025-01-12 14:00:06Python资料围观18次
本篇文章分享Python版贪吃蛇游戏(开源),对你有帮助的话记得收藏一下,看Python资料网收获更多编程知识
我将整个贪吃蛇游戏的代码分割成了几个部分进行讲解,内容较长,建议细心观看!(注:全程没几个文字,不喜勿喷)
结尾会有完整版源码!
1.导入模块
游戏游戏,肯定得有游戏模块pygame,随后便是random模块了,代码如下:
import pygame
import random
导入好模块后下面就是基础设置了
一、基础设置部分
1.屏幕高度与宽度的设置
这个就不用多说了吧,懂得都懂
SCREEN_HEIGHT = 480
SCREEN_WIDTH = 600
2.小方格的大小与颜色的定义
GRID_SIZE = 20
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
初始化pygame
pyame.init()
创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
创建游戏时钟
clock = pygame.time.Clock()
二、贪吃蛇类
1.贪吃蛇主体
class Snake:
def __init__(self):
self.positions = [(100, 100)]
self.direction = (1, 0)
def move(self):
cur = self.positions[0]
x, y = cur
dx, dy = self.direction
new = ((x + dx * GRID_SIZE) % SCREEN_WIDTH, (y + dy * GRID_SIZE) % SCREEN_HEIGHT)
if new in self.positions[1:]:
return False
else:
self.positions.insert(0, new)
if new[0] == food_pos[0] and new[1] == food_pos[1]:
return True
else:
self.positions.pop()
return True
def change_direction(self, direction):
if (direction[0] * -1, direction[1] * -1)!= self.direction:
self.direction = direction
2.食物类
class Food:
def __init__(self):
self.position = (random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE,
random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE)
def generate_new(self):
while True:
new_pos = (random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE,
random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE)
if new_pos not in snake.positions:
self.position = new_pos
break
三、游戏主循环
1.主循环部分
def game_loop():
global snake, food
snake = Snake()
food = Food()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake.direction!= (0, 1):
snake.change_direction((0, -1))
elif event.key == pygame.K_DOWN and snake.direction!= (0, -1):
snake.change_direction((0, 1))
elif event.key == pygame.K_LEFT and snake.direction!= (1, 0):
snake.change_direction((-1, 0))
elif event.key == pygame.K_RIGHT and snake.direction!= (-1, 0):
snake.change_direction((1, 0))
if not snake.move():
running = False
if snake.positions[0] == food.position:
food.generate_new()
screen.fill(BLACK)
for pos in snake.positions:
pygame.draw.rect(screen, GREEN, [pos[0], pos[1], GRID_SIZE, GRID_SIZE])
pygame.draw.rect(screen, WHITE, [food.position[0], food.position[1], GRID_SIZE, GRID_SIZE])
pygame.display.flip()
clock.tick(10)
pygame.quit()
if __name__ == "__main__":
game_loop()
四、完整版代码
如下:
import pygame
import random
# 基础设置
# 屏幕高度
SCREEN_HEIGHT = 480
# 屏幕宽度
SCREEN_WIDTH = 600
# 小方格大小
GRID_SIZE = 20
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
# 初始化 pygame
pygame.init()
# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
# 游戏时钟
clock = pygame.time.Clock()
# 贪吃蛇类
class Snake:
def __init__(self):
self.positions = [(100, 100)]
self.direction = (1, 0)
def move(self):
cur = self.positions[0]
x, y = cur
dx, dy = self.direction
new = ((x + dx * GRID_SIZE) % SCREEN_WIDTH, (y + dy * GRID_SIZE) % SCREEN_HEIGHT)
if new in self.positions[1:]:
return False
else:
self.positions.insert(0, new)
if new[0] == food_pos[0] and new[1] == food_pos[1]:
return True
else:
self.positions.pop()
return True
def change_direction(self, direction):
if (direction[0] * -1, direction[1] * -1)!= self.direction:
self.direction = direction
# 食物类
class Food:
def __init__(self):
self.position = (random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE,
random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE)
def generate_new(self):
while True:
new_pos = (random.randint(0, SCREEN_WIDTH // GRID_SIZE - 1) * GRID_SIZE,
random.randint(0, SCREEN_HEIGHT // GRID_SIZE - 1) * GRID_SIZE)
if new_pos not in snake.positions:
self.position = new_pos
break
# 游戏主循环
def game_loop():
global snake, food
snake = Snake()
food = Food()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake.direction!= (0, 1):
snake.change_direction((0, -1))
elif event.key == pygame.K_DOWN and snake.direction!= (0, -1):
snake.change_direction((0, 1))
elif event.key == pygame.K_LEFT and snake.direction!= (1, 0):
snake.change_direction((-1, 0))
elif event.key == pygame.K_RIGHT and snake.direction!= (-1, 0):
snake.change_direction((1, 0))
if not snake.move():
running = False
if snake.positions[0] == food.position:
food.generate_new()
screen.fill(BLACK)
for pos in snake.positions:
pygame.draw.rect(screen, GREEN, [pos[0], pos[1], GRID_SIZE, GRID_SIZE])
pygame.draw.rect(screen, WHITE, [food.position[0], food.position[1], GRID_SIZE, GRID_SIZE])
pygame.display.flip()
clock.tick(10)
pygame.quit()
if __name__ == "__main__":
game_loop()
Python版贪吃蛇就到这里结束了,感谢您的观看,我们下期再见!
版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签:
上一篇:墙裂建议收藏,100道Python练手题目
下一篇:编写工具模块
相关文章
最新发布
- 光流法结合深度学习神经网络的原理及应用(完整代码都有Python opencv)
- Python 图像处理进阶:特征提取与图像分类
- 大数据可视化分析-基于python的电影数据分析及可视化系统_9532dr50
- 【Python】入门(运算、输出、数据类型)
- 【Python】第一弹---解锁编程新世界:深入理解计算机基础与Python入门指南
- 华为OD机试E卷 --第k个排列 --24年OD统一考试(Java & JS & Python & C & C++)
- Python已安装包在import时报错未找到的解决方法
- 【Python】自动化神器PyAutoGUI —告别手动操作,一键模拟鼠标键盘,玩转微信及各种软件自动化
- Pycharm连接SQL Sever(详细教程)
- Python编程练习题及解析(49题)
点击排行
- 版本匹配指南:Numpy版本和Python版本的对应关系
- 版本匹配指南:PyTorch版本、torchvision 版本和Python版本的对应关系
- Python 可视化 web 神器:streamlit、Gradio、dash、nicegui;低代码 Python Web 框架:PyWebIO
- 相关性分析——Pearson相关系数+热力图(附data和Python完整代码)
- Anaconda版本和Python版本对应关系(持续更新...)
- Python与PyTorch的版本对应
- Windows上安装 Python 环境并配置环境变量 (超详细教程)
- Python pyinstaller打包exe最完整教程