用python写一个简单的贪吃蛇游戏(附代码)

Pygame经典小游戏--贪吃蛇(完整代码+部分代码讲解) 通过本次对贪吃蛇游戏的改进和优化,提升了游戏的可玩性和趣味性,为玩家带来更加丰富和多样的游戏体验。如果你也对这款游戏感兴趣,不妨自己动手尝试一下,相信你会在编程的过程中找到无尽的乐趣和成就感! 阅读详情
AI摘要

本文分享了一个使用pygame库编写的Python贪吃蛇小游戏。通过分析游戏机制,讲解了如何表示和移动蛇、如何判断游戏结束。代码简洁,适合作为初学者练习Python和数据结构的项目。

不知道有多少同学跟我一样,最初接触编程的动机就是为了自己做个游戏玩?
今天要给大家分享的是一个 pygame 写的“贪吃蛇”小游戏:请添加图片描述
“贪吃蛇”这个小游戏在编程学习中的常客,因为:

  1. 简单,最基本的游戏元素只需要蛇和食物两个就可以进行了。(打飞机还需要三个元素呢,想想分别是什么?)方向的话只要上下左右4个固定方向就可以了。
  2. 有基本的数据结构和面向对象的思想在其中。游戏开发本身就会用到很多面向对象的概念,而蛇的身体又是一个天然的“链表”结构,太适合用来练习数据结构了。另外比较有趣的一点是,Python 这个单词在英语里就是蟒蛇的意思,贪吃蛇可以算是“同名游戏”了。很多学校里程序开发课程的作业都会有贪吃蛇的选题,也经常会有同学问到我们相关的代码。(诺基亚手机对这款游戏也是情有独钟。)之前我做过一个《贪吃蛇大作战》的 Python 版本,基于 cocos2d-python 开发。但那个对于初学者来说有些复杂了。
    这里我们做个简要介绍:
    此代码基于 pygame 开发,所以运行前请确保你的 Python 里已成功安装 pygame。然后直接运行代码中的 game2.py 即可开始游戏。除了最终的代码外,我们还特意分解了几个过程中的 py 文件,供想要自己开发的同学参考。
    我们先来分析一下,要写出这个游戏来需要注意哪些点。
    1、蛇怎么表示?
    我们可以将整个游戏区域划分成一个个的小格子,由一组连在一起的小格子组成“蛇”,我们可以用不同的颜色来表示,如上图中,我以深色表示背景,浅色表示“蛇”。
    我们可以用坐标来表示每一个小方格,X 轴和 Y 轴的范围都是可以设定好的。用一个列表来存放“蛇身”的坐标,那么一条“蛇”就出来了,最后只要显示的时候以不同的颜色表示即可。
    2、蛇怎么移动?
    第一反应就是像蚯蚓蠕动一样,每一个小方块向前移动一格,但这样实现起来很麻烦。一开始就是被这里卡住了。
    想象一下我们玩过的贪吃蛇,每次“蛇”的移动感觉上是整体往前移动了一格,排除掉脑子中“蛇”的“动作”,细想移动前和移动后“蛇”的位置变化,其实除了头尾,其他部分根本就没有变。那就简单了,将下一格的坐标添加到列表开头,并移除列表的最后一个元素,就相当于蛇向前移动了一格。
    3、如何判定游戏结束?
    “蛇”移动超出了游戏区的范围或者碰到了自己就算输了,轴坐标的范围是事先定好的,超出范围很容易判断。那么如何判断碰到自己呢?
    如果脑子里想的是“蛇”动的画面,那真的比较难了,但是放到代码中,我们的“蛇”是一个列表,那么只要判断下一格的坐标是否已经包含在“蛇”的列表中岂不就可以了?
    理清了这些问题,我们就可以开始编码了。
    定义游戏元素及界面
def main():
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption('贪吃蛇')

    light = (100, 100, 100)  # 蛇的颜色
    dark = (200, 200, 200)  # 食物颜色

    font1 = pygame.font.SysFont('SimHei', 24)  # 得分的字体
    font2 = pygame.font.Font(None, 72)  # GAME OVER 的字体
    red = (200, 30, 30)  # GAME OVER 的字体颜色
    fwidth, fheight = font2.size('GAME OVER')
    line_width = 1  # 网格线宽度
    black = (0, 0, 0)  # 网格线颜色
    bgcolor = (40, 40, 60)  # 背景色

    # 方向,起始向右
    pos_x = 1
    pos_y = 0
    # 如果蛇正在向右移动,那么快速点击向下向左,由于程序刷新没那么快,向下事件会被向左覆盖掉,导致蛇后退,直接GAME OVER
    # b 变量就是用于防止这种情况的发生
    b = True
    # 范围
    scope_x = (0, SCREEN_WIDTH // SIZE - 1)
    scope_y = (2, SCREEN_HEIGHT // SIZE - 1)
    # 蛇
    snake = deque()
    # 食物
    food_x = 0
    food_y = 0

初始化蛇及食物

  # 初始化蛇
    def _init_snake():
        nonlocal snake
        snake.clear()
        snake.append((2, scope_y[0]))
        snake.append((1, scope_y[0]))
        snake.append((0, scope_y[0
Python贪吃蛇游戏教程:免费源码,简单易懂的Python游戏开发指导 游戏主循环:游戏的主要循环,处理用户输入、蛇的移动、食物的生成和碰撞检测。print("贪吃蛇的位置: ", snake_pos)print("食物的位置: ", food_pos)食物随机重新生成:当蛇身体增长后,食物在新的位置生成。定义蛇的初始位置和长度:设定蛇的起始位置和初始长度。定义食物的位置:在游戏区域内随机生成食物的位置。确定蛇的方向:根据用户的输入改变蛇的移动方向。print("游戏结束!定义蛇的方向:设定蛇的初始移动方向。显示蛇和食物:打印出蛇和食物的位置。移动蛇:根据方向移动蛇的位置。 阅读详情

相关推荐

Python小游戏:100行代码实现贪吃蛇小游戏

今天来尝试下用python写一个贪吃小游戏,哈哈哈哈,毕竟贪吃蛇,大家小时候都玩过,但现在却有机会自己实现一个!!!

程序员小芽的博客 4707

Python贪吃蛇简单的代码

在自学Python的过程中在网上查询资料时发现了一些好玩的东西,python的游戏库模块,它可以自己弄一个小游戏来玩玩,然后我在网上找了一些游戏的代码,,自己改了一些,弄出了一个简单贪吃蛇,代码也是照着敲的只是稍微的改了一下 import pygame, sys, random, time from pygame.locals import * # 从pygame模块导入常用的函数和常量 #定义...

刘旭濠的博客 2万+

Python100行实现一个简单的贪吃蛇小游戏(附代码)

贪吃蛇是个非常简单的游戏,适合练手。

Modeler_xiaoyu的博客 4268

光电振荡器(OEO):从原理到应用,解锁高频微波信号新纪元

本文深入解析了光电振荡器(OEO)的核心原理与前沿应用。OEO通过巧妙的光-电-光转换机制,利用光学谐振腔产生高频、高纯度、低相位噪声的微波信号,有效突破了传统电子电路的频率瓶颈。文章详细拆解了其工作流程,并探讨了在雷达系统、高速光通信及精密测量等领域的硬核应用价值。

weixin_29231027的博客 365

MySQL安装最后启动报错--Job for mysqld.service failed because the control process exited with error code. See

MySQL安装最后启动报错: [root@localhost mysql]# systemctl start mysqld Warning: mysqld.service changed on disk. Run 'systemctl daemon-reload' to reload units. Job for mysqld.service failed because the control process exited with error code. See "systemctl status m

chenchen的博客 2746

redhawk-sc使用简介

数据完整性对结果的准确性有很大影响,所以一定要保证数据完整性,Redhawk-sc在跑完后,Report里有Data Integrity界面,在这个界面会看到设计数据和库文件的数据完整性,在相应的报告中会有没有覆盖到的数据情况,要对每一项仔细检查,保证输入数据没有问题。文件一般加密,用户唯一需要选择的是文件的corner。其中,cell lef除了常规的standard cell,还有如DTCD,BTSV和clamp等cell的lef,不可缺失,否则data integrity将不是100%。

weixin_48518726的博客 3139

C2000 CLA协处理器:嵌入式实时控制性能优化与实战指南

在嵌入式实时控制系统中,主CPU常因高频率、低延迟的控制算法而面临性能瓶颈。为解决此问题,协处理器技术应运而生,它通过硬件并行架构分担计算密集型任务,从而提升系统整体性能。其核心原理在于独立的计算单元与总线设计,能够实现近乎零延迟的响应,这对于电机驱动、数字电源等闭环控制场景具有极高的技术价值。本文聚焦于德州仪器C2000系列微控制器中的控制律加速器(CLA),深入解析其作为独立浮点协处理器如何通过任务调度与消息RAM通信机制,有效实现性能倍增,并提供了从内存配置到代码调试的完整工程实践方案。

weixin_29192211的博客 305

TL3562/3568内核驱动移植实战:解决无锡沐创N500L-AM4网口异常问题

本文详细介绍了在TL3562/3568平台上移植无锡沐创N500L-AM4网卡驱动的实战经验,重点解决了第四个网口通讯异常问题。通过升级驱动版本至rnpgbe-0.2.3,生成关键头文件并正确配置内核,最终实现四个网口稳定工作。文章还提供了性能优化建议和避坑指南,为类似硬件驱动移植项目提供参考。

weixin_28273593的博客 180

RK3566添加ffpeg【Buildroot系统】

有很多人都发现了RK3566系列的芯片是不可以直接使用ffmpeg官网源码的!会报错: Not a video capture device. /dev/video0: No such device 接下来我们就来解决这个问题!!

honmy18的博客 4070

sift、surf、orb 特征提取——三维重建

参考文章:[sift、surf、orb 特征提取及最优特征点匹配] 最近刚刚入门三维重建,在SFM算法的代码中注意到了feature_type( feature extraction method)这个参数,想细致了解一下这几种特征提取算法,在这里做一下笔记。 SIFT 简介 SIFT(Scale-Invariant Feature Transform)——尺度不变特征变换,是一种计算机视觉的特征提取算法,用来侦测与描述图像中的局部特征。 实质上,它是在不同的尺度空间上查找关键点(特征点),并计算出关键点的

bb_sy_w的博客 4362

YOLO11-Seg优化:注意力魔改 | 具有切片操作的SimAM注意力,魔改SimAM

问题点:SimAM计算整张特征图的像素差平均值时加权可能会忽略小目标的重要性,同时与整体平均值相比可能和背景信息相似,导致加权增强较弱;

会AI的学姐 458

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

上一篇: 10 个 Python 项目简单又超有趣
下一篇: 使用 python 的单人AI 扫雷游戏
python2021_
博客等级 码龄6年 1730粉丝 157原创
评论 44
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值