利用Python写个开心消消乐小游戏,并没有想象中的复杂

用 Python 写个消消乐小游戏 提到开心消消乐这款小游戏,相信大家都不陌生,其曾在 2015 年获得过玩家最喜爱的移动单机游戏奖,受欢迎程度可见一斑,本文我们使用 Python 来做个简单的消消乐小游戏。 很多人学习python,不知道从何学起。 很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。 很多已经做案例的人,却不知道如何去学习更加高深的知识。 那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码! QQ群:1097524789 实现 消消乐的构成主要包括三部分:游 阅读详情

提到开心消消乐这款小游戏,相信大家都不陌生,其曾在 2015 年获得过玩家最喜爱的移动单机游戏奖,受欢迎程度可见一斑,本文我们使用 Python 来做个简单的消消乐小游戏。

很多人学习python,不知道从何学起。
很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
很多已经做案例的人,却不知道如何去学习更加高深的知识。
那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!??¤
QQ群:828010317

实现

消消乐的构成主要包括三部分:游戏主体、计分器、计时器,下面来看一下具体实现。

先来看一下游戏所需 Python 库。

import os
import sys
import time
import pygame
import random

定义一些常量,比如:窗口宽高、网格行列数等,代码如下:

WIDTH = 400
HEIGHT = 400
NUMGRID = 8
GRIDSIZE = 36
XMARGIN = (WIDTH - GRIDSIZE * NUMGRID) // 2
YMARGIN = (HEIGHT - GRIDSIZE * NUMGRID) // 2
ROOTDIR = os.getcwd()
FPS = 30

接着创建一个主窗口,代码如下:

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('消消乐')

看一下效果:

再接着在窗口中画一个 8 x 8 的网格,代码如下:

screen.fill((255, 255, 220))
# 游戏界面的网格绘制
def drawGrids(self):
    for x in range(NUMGRID):
        for y in range(NUMGRID):
            rect = pygame.Rect((XMARGIN+x*GRIDSIZE, YMARGIN+y*GRIDSIZE, GRIDSIZE, GRIDSIZE))
            self.drawBlock(rect, color=(255, 165, 0), size=1
# 画矩形 block 框
def drawBlock(self, block, color=(255, 0, 0), size=2):
    pygame.draw.rect(self.screen, color, block, size)

看一下效果:

再接着在网格中随机放入各种拼图块,代码如下:

while True:
    self.all_gems = []
    self.gems_g
python代码写开心消消乐 python写小游戏--开心消消乐 阅读详情

相关推荐

用Python制作开心消消乐游戏|附源码

制作一个完整的“开心消消乐”风格的游戏在Python中是一个相对复杂的项目,因为它涉及到图形界面、游戏逻辑、动画效果以及用户交互等多个方面。不过,我可以为你提供一个简化的版本和概念框架,帮助你理解如何开始这个项目,并提供一个基础的源码示例。

Python_00001的博客 3362

Python Pygame消消乐开发:从零实现游戏核心算法与状态机

游戏开发的核心在于将复杂交互抽象为可管理的逻辑模型,其中状态机是描述游戏流程的经典设计模式。它通过定义有限状态(如等待输入、交换、检查匹配、消除、下落填充等)及状态间的转换规则,将动态的游戏过程结构化。在2D游戏开发中,Pygame作为轻量级框架,以其直观的API和即时反馈特性,成为初学者实践游戏原理的理想工具。通过实现消消乐这类经典游戏,开发者能深入理解事件驱动编程、实时渲染与游戏逻辑解耦等工程实践。本文以Pygame为技术栈,详细拆解了如何利用二维列表数据结构构建棋盘模型,并实现匹配检测、重力下落等核心

weixin_33816300的博客 303

Python小游戏开发实战:消消乐完整源码解析

图形用户界面(Graphical User Interface,简称GUI)是一种通过图形化方式与用户进行交互的技术。在游戏开发中,GUI不仅仅是用户与游戏之间的桥梁,更是实现视觉呈现、交互响应和逻辑反馈的核心组件。在小游戏的开发过程中,GUI的作用尤为关键,主要体现在以下几个方面:可视化展示:将游戏元素(如角色、背景、动画、按钮等)以图形方式呈现在屏幕上。事件驱动:处理用户的输入事件(如鼠标点击、键盘按键、触摸操作等),并将其转化为游戏逻辑的触发信号。交互反馈。

weixin_36073714的博客 866

Python消消乐小游戏开发与实战资源

本章从基础的行列匹配判断出发,逐步构建出完整的消除逻辑,并引入了递归消除机制。通过代码实现和流程图展示,我们清晰地呈现了消除算法的执行流程。下一章将进入 Tkinter 图形界面开发部分,实现这些逻辑的可视化与用户交互,使整个游戏系统更加完整。后续章节中,我们将进一步讨论如何将上述消除逻辑集成到图形界面中,实现点击交换、动画反馈等功能,使游戏更加生动有趣。graph TDA[创建Tkinter主窗口] --> B[添加Canvas画布]B --> C[加载图片资源]

weixin_35749440的博客 670

Pygame开发的消消乐记分游戏实战指南

Pygame是一个开源的Python库,专门用于编写视频游戏。它包括图形和声音库,可以让你处理图像,播放声音,管理用户输入,并且还可以让你制作2D游戏。Pygame是用Python编写游戏的一个很好的起点,因为它相对容易上手,并且文档丰富。游戏状态指的是在某一特定时刻游戏内部环境的快照,包括玩家的得分、玩家的当前状态(如生命值、能量)、游戏世界的状态、敌人的状态等。在多状态游戏中,游戏状态可描述为一个状态机,不同的状态可以触发不同的游戏逻辑和表现。

weixin_42577735的博客 418

FPGA驱动OV5640:从SCCB协议到图像数据采集的实战解析

本文详细解析了使用FPGA驱动OV5640摄像头模组的完整流程,从SCCB协议通信、寄存器配置到图像数据采集。重点阐述了SCCB(与I2C类似)协议的实现细节、关键的上电复位时序,以及如何通过状态机解析视频流时序并捕获图像数据,为嵌入式视觉开发提供了实战指南。

weixin_29191761的博客 187

HBuilderx连接微信开发者工具

系列文章目录 文章目录系列文章目录前言一、环境1.HBuilerx 工具2.微信开发者工具二、关联微信开发者工具1.HBuilderx新建项目2.关联微信开发者工具3.运行微信小程序出现异常解决方法3.最终效果总结 前言 使用HBuilderx工具关联微信开发者工具,进行小程序开发 提示:以下是本篇文章正文内容,下面案例可供参考 一、环境 1.HBuilerx 工具 HBuilderx 2.微信开发者工具 微信开发者工具 二、关联微信开发者工具 1.HBuilderx新建项目 2.关联微信开发者工具

拥有必珍惜 3075

MTK Tunning ISP 模块面试总结

ISP面试问答

m0_72053187的博客 4537

网安保研避坑指南:中科院信工所各研究室真实体验与导师选择建议

本文为中科院信工所网络安全保研生提供深度指南,详细解析了信工所六个研究室的研究方向、真实氛围与导师选择策略。文章特别强调,选择导师是决定研究生体验的关键,并提供了针对各研究室的避坑建议与实战调研方法,帮助学生做出明智选择。

weixin_29210727的博客 1578

Siemens SIMATIC软件二次开发:使用C#进行SIMATIC软件二次开发

通过使用OPC-UA通信协议和S7通信库,可以有效地在C#应用程序中与Siemens SIMATIC软件进行数据交换。OPC-UA提供了一个标准化的平台,而S7通信库则提供了直接访问PLC数据的能力。掌握这两种通信方式,将极大地增强在工业自动化领域的二次开发能力。在Siemens SIMATIC软件中,自定义功能块开发是实现二次开发的关键步骤之一。通过C#,可以创建高度定制化的功能块,以满足特定的控制需求。下面,我们将通过一个示例来展示如何使用C#开发一个自定义功能块。OPC-UA通信。

kkchenjj的博客 1414

RK3568笔记十七:LVGL v8.2移植

若该文为原创文章,转载请注明原文出处。本文介绍嵌入式图形库移植到Linux开发板ATK-RK3568上的步骤。

4230

104、线缆与终端匹配:特性阻抗、双绞线规格与端接电阻优化策略

摘要: CAN总线物理层可靠性取决于线缆特性阻抗、双绞线规格与终端电阻的精准匹配。核心要点包括: 特性阻抗须严格匹配120Ω(±10%),反射系数需≤0.05,线缆建议选用Belden 3086A等实测达标型号,避免网线替代; 双绞线应选AWG22~24纯铜线,绞距≤30mm,工业环境需屏蔽层单端接地,杜绝铜包铝线; 终端电阻需选用金属膜电阻(0.5W以上),阻值按实测线缆阻抗微调,长距离可采用分裂终端(60Ω+4.7nF)优化信号完整性; 拓扑适配:星型/树型拓扑需控制分支长度,环型拓扑必须断开; 实测验

2401_88858637的博客 51

基于STM32L4XX、HAL库的RTL8201F 以太网收发器(PHY)驱动程序设计

define PHY_RESET_DELAY 1000 // PHY复位延迟(ms)#define PHY_AUTONEGO_DELAY 3000 // 自动协商延迟(ms)/* 检查PHY ID (RTL8201F的ID为0x001CC816) *//* 系统时钟配置,确保ETH有50MHz时钟 *//* 初始化CPU, AHB和APB总线时钟 */

zhusl6688的博客 804

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

深度学习工具包 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")

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

上一篇: 手把手教你使用Python轻松搞定发邮件
下一篇: 利用Python将PDF文档转为MP3音频
Python_sn
博客等级 码龄6年 324粉丝 290原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值