用Python找到童年的乐趣,制作一款贪吃蛇小游戏。新手教程!

开发工具


  • python版本:3.6.8

  • 编辑器:pycharm

相关模块

import copy

import random

import pygame

模块安装

pip install -i https://pypi.doubanio.com/simple/ --trusted-host pypi.doubanio.com pygame

实现效果


在这里插入图片描述

这个就是代码运行的效果了。以前就是这样一个极为枯燥的游戏都能很多人抢着玩,一人一条命,能玩十几二十分钟!本来很小的屏幕都被挤满了!下面直接把代码分享给你们!

完整源代码


完整代码

import copy

import random

游戏模块

import pygame

蛇的模型

snake_list = [[10, 10]]

500x500 背景大小

食物的模型 随机生成

x = random.randint(10, 490)

y = random.randint(10, 490)

food_point = [x, y]

上下左右的方位 初始小蛇方向

move_up = False

move_down = False

move_left = False

move_right = True

画布

初始化游戏组件

pygame.init()

设置画布大小

screen = pygame.display.set_mode((500, 500))

设置名字

title = pygame.display.set_caption(‘贪吃蛇游戏’)

设置游戏时钟

clock = pygame.time.Clock()

while True:

电影 是一帧一帧 30fps

clock.tick(20)

游戏循环

把背景填充为白色

screen.fill([255, 255, 255])

“”“贪吃蛇移动 获取键盘事件”“”

获取电脑的时间

确定移动方位

for event in pygame.event.get():

获取键盘事件

print(event)

if event.type == pygame.KEYDOWN:

向下移动

if event.key == pygame.K_DOWN:

move_up = False

move_down = True

move_left = False

move_right = False

if event.key == pygame.K_UP:

move_up = True

move_down = False

move_left = False

move_right = False

if event.key == pygame.K_LEFT:

move_up = False

move_down = False

move_left = True

move_right = False

if event.key == pygame.K_RIGHT:

move_up = False

move_down = False

move_left = False

move_right = True

身子的移动

snake_len = len(snake_list) - 1

while snake_len > 0:

snake_list[snake_len] = copy.deepcopy(snake_list[snake_len - 1])

snake_len -= 1

蛇头的移动

if move_up:

snake_list[snake_len][1] -= 10

if snake_list[snake_len][1] < 0:

snake_list[snake_len][1] = 500

if move_down:

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

img

img

img

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注:Python)

img_convert/9f49b566129f47b8a67243c1008edf79.png)

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注:Python)

  • 23
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,制作贪吃游戏需要用到 Pygame 这个库,首先需要安装它。 安装 Pygame: ``` pip install pygame ``` 接下来就可以开始编写代码了,下面是贪吃游戏的代码,注释中有详细的说明: ```python import pygame import random # 初始化 Pygame pygame.init() # 定义窗口大小和标题 WINDOW_WIDTH = 600 WINDOW_HEIGHT = 600 WINDOW_TITLE = 'Snake Game' WINDOW = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption(WINDOW_TITLE) # 定义颜色 WHITE_COLOR = (255, 255, 255) BLACK_COLOR = (0, 0, 0) RED_COLOR = (255, 0, 0) GREEN_COLOR = (0, 255, 0) # 定义贪吃的属性 SNAKE_SIZE = 10 SNAKE_SPEED = 15 # 定义食物的属性 FOOD_SIZE = 10 FOOD_COLOR = RED_COLOR # 定义字体 FONT_SIZE = 30 FONT = pygame.font.SysFont('Arial', FONT_SIZE) # 定义方向 UP = 1 DOWN = 2 LEFT = 3 RIGHT = 4 # 定义游戏结束标志 GAME_OVER = False # 定义贪吃类 class Snake: def __init__(self): self.length = 1 self.positions = [(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)] self.direction = random.choice([UP, DOWN, LEFT, RIGHT]) self.color = GREEN_COLOR self.score = 0 # 贪吃移动 def move(self): x, y = self.positions[0] if self.direction == UP: y -= SNAKE_SPEED elif self.direction == DOWN: y += SNAKE_SPEED elif self.direction == LEFT: x -= SNAKE_SPEED elif self.direction == RIGHT: x += SNAKE_SPEED self.positions = [(x, y)] + self.positions[:-1] # 贪吃改变方向 def change_direction(self, direction): if self.direction == UP and direction == DOWN: return if self.direction == DOWN and direction == UP: return if self.direction == LEFT and direction == RIGHT: return if self.direction == RIGHT and direction == LEFT: return self.direction = direction # 贪吃增加长度 def grow(self): x, y = self.positions[0] if self.direction == UP: y -= SNAKE_SIZE elif self.direction == DOWN: y += SNAKE_SIZE elif self.direction == LEFT: x -= SNAKE_SIZE elif self.direction == RIGHT: x += SNAKE_SIZE self.length += 1 self.score += 1 self.positions = [(x, y)] + self.positions # 贪吃绘制 def draw(self): for position in self.positions: x, y = position pygame.draw.rect(WINDOW, self.color, (x, y, SNAKE_SIZE, SNAKE_SIZE)) # 定义食物类 class Food: def __init__(self): self.position = (0, 0) self.color = FOOD_COLOR self.randomize_position() # 食物随机位置 def randomize_position(self): x = random.randint(0, WINDOW_WIDTH - FOOD_SIZE) y = random.randint(0, WINDOW_HEIGHT - FOOD_SIZE) self.position = (x, y) # 食物绘制 def draw(self): x, y = self.position pygame.draw.rect(WINDOW, self.color, (x, y, FOOD_SIZE, FOOD_SIZE)) # 定义游戏主循环 def main(): global GAME_OVER # 创建贪吃和食物对象 snake = Snake() food = Food() # 定义游戏时钟 clock = pygame.time.Clock() # 游戏循环 while not GAME_OVER: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: GAME_OVER = True break elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: snake.change_direction(UP) elif event.key == pygame.K_DOWN: snake.change_direction(DOWN) elif event.key == pygame.K_LEFT: snake.change_direction(LEFT) elif event.key == pygame.K_RIGHT: snake.change_direction(RIGHT) # 贪吃移动 snake.move() # 判断是否吃到食物 if snake.positions[0] == food.position: snake.grow() food.randomize_position() # 判断是否游戏结束 for position in snake.positions[1:]: if snake.positions[0] == position: GAME_OVER = True break if snake.positions[0][0] < 0 or snake.positions[0][0] > WINDOW_WIDTH - SNAKE_SIZE: GAME_OVER = True break if snake.positions[0][1] < 0 or snake.positions[0][1] > WINDOW_HEIGHT - SNAKE_SIZE: GAME_OVER = True break # 绘制游戏界面 WINDOW.fill(BLACK_COLOR) snake.draw() food.draw() score_text = FONT.render('Score: {}'.format(snake.score), True, WHITE_COLOR) WINDOW.blit(score_text, (10, 10)) pygame.display.update() # 控制游戏帧率 clock.tick(30) # 游戏结束 game_over_text = FONT.render('Game Over', True, WHITE_COLOR) game_over_rect = game_over_text.get_rect() game_over_rect.center = (WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2) WINDOW.fill(BLACK_COLOR) WINDOW.blit(game_over_text, game_over_rect) pygame.display.update() pygame.time.wait(2000) # 退出 Pygame pygame.quit() # 启动游戏 if __name__ == '__main__': main() ``` 运行程序后即可开始游戏,按上下左右键控制贪吃的方向,吃到食物后贪吃会变长,碰到边界或自己身体时游戏结束。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值