C# Winform翻牌子记忆小游戏

效果

源码

新建一个winform项目命名为Matching Game,选用.net core 6框架

并把Form1.cs代码修改为

using Timer = System.Windows.Forms.Timer;

namespace Matching_Game
{
    public partial class Form1 : Form
    {
        private const int row = 4;
        private const int col = 4;
        private TableLayoutPanel panel = new()
        {
            RowCount = row,
            ColumnCount = col,
        };
        private Label[,] labels = new Label[row, col];

        private readonly Random random = new();

        private readonly List<string> icons = new()
        {
            "!", "!", "N", "N", ",", ",", "k", "k",
            "b", "b", "v", "v", "w", "w", "z", "z"
        };

        private readonly Timer timer = new()
        {
            Interval = 750,
        };

        private Label? firstClicked = null;
        private Label? secondClicked = null;

        public Form1()
        {
            InitializeComponent();

            InitializeControls();
            timer.Tick += Timer_Tick;

            AssignIconsToSquares();

        }

        /// <summary>
        /// 窗体和它的子窗体都开启双缓冲,防止重新开始游戏时重新绘制控件闪屏
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        /// <summary>
        /// 初始化控件
        /// </summary>
        public void InitializeControls()
        {
            #region initialize form
            Text = "Matching Game";
            Size = new Size(550, 550);
            StartPosition = FormStartPosition.CenterScreen;
            Controls.Clear();
            #endregion

            #region initialize panel
            panel.BackColor = Color.CornflowerBlue;
            for (int i = 0; i < row; i++)
            {
                panel.RowStyles.Add(new RowStyle(SizeType.Percent, 25));
            }
            for (int j = 0; j < col; j++)
            {
                panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 25));
            }
            panel.Dock = DockStyle.Fill;
            panel.CellBorderStyle = TableLayoutPanelCellBorderStyle.Inset;
            panel.Padding = new Padding(0, 0, 0, 0);
            Controls.Add(panel);
            #endregion

            #region initialize labels
            for (int i = 0; i < row; i++)
            {
                for (int j = 0; j < col; j++)
                {
                    Label label = new()
                    {
                        BackColor = Color.CornflowerBlue,
                        ForeColor = Color.CornflowerBlue,
                        AutoSize = false,
                        Dock = DockStyle.Fill,
                        TextAlign = ContentAlignment.MiddleCenter,
                        Font = new Font("Webdings", 64, FontStyle.Regular),
                        //Font = new Font("Times New Roman", 48, FontStyle.Bold),
                        Margin = new Padding(0, 0, 0, 0)
                    };
                    labels[i, j] = label;
                    label.Click += Label_Click;

                    panel.Controls.Add(label);
                    panel.SetCellPosition(label, new TableLayoutPanelCellPosition(j, i));
                }
            }
            #endregion

        }

        /// <summary>
        /// 定时器任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Tick(object? sender, EventArgs e)
        {
            timer.Stop();

            CheckForWinner();

            if (firstClicked != null)
            {
                firstClicked.ForeColor = firstClicked.BackColor;
            }
            if (secondClicked != null)
            {
                secondClicked.ForeColor = secondClicked.BackColor;
            }

            firstClicked = null;
            secondClicked = null;

        }

        /// <summary>
        /// 标签被点击时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Label_Click(object? sender, EventArgs e)
        {
            // The timer is only on after two non-matching 
            // icons have been shown to the player, 
            // so ignore any clicks if the timer is running
            if (timer.Enabled == true)
                return;

            if (sender is Label clickedLabel)
            {
                // If the clicked label is black, the player clicked
                // an icon that's already been revealed --
                // ignore the click
                if (clickedLabel.ForeColor == Color.Black)
                    return;

                // If firstClicked is null, this is the first icon
                // in the pair that the player clicked, 
                // so set firstClicked to the label that the player 
                // clicked, change its color to black, and return
                if (firstClicked == null)
                {
                    firstClicked = clickedLabel;
                    firstClicked.ForeColor = Color.Black;
                    return;
                }

                // If the player gets this far, the timer isn't
                // running and firstClicked isn't null,
                // so this must be the second icon the player clicked
                // Set its color to black
                secondClicked = clickedLabel;
                secondClicked.ForeColor = Color.Black;

                if (firstClicked.Text == secondClicked.Text)
                {
                    firstClicked = null;
                    secondClicked = null;
                }

                // If the player gets this far, the player 
                // clicked two different icons, so start the 
                // timer (which will wait three quarters of 
                // a second, and then hide the icons)
                timer.Start();
            }
        }

        /// <summary>
        /// Assign each icon from the list of icons to a random square
        /// </summary>
        private void AssignIconsToSquares()
        {
            List<string> iList = icons.ToList();
            // The TableLayoutPanel has 16 labels,
            // and the icon list has 16 icons,
            // so an icon is pulled at random from the list
            // and added to each label
            foreach (Control control in panel.Controls)
            {
                if (control is Label iconLabel)
                {
                    int randomNumber = random.Next(iList.Count);
                    iconLabel.Text = iList[randomNumber];
                    // iconLabel.ForeColor = iconLabel.BackColor;
                    iList.RemoveAt(randomNumber);
                }
            }
        }

        /// <summary>
        /// Check every icon to see if it is matched, by 
        /// comparing its foreground color to its background color. 
        /// If all of the icons are matched, the player wins
        /// </summary>
        private void CheckForWinner()
        {
            // Go through all of the labels in the TableLayoutPanel, 
            // checking each one to see if its icon is matched
            foreach (Control control in panel.Controls)
            {
                if (control is Label iconLabel)
                {
                    if (iconLabel.ForeColor == iconLabel.BackColor)
                        return;
                }
            }

            // If the loop didn’t return, it didn't find
            // any unmatched icons
            // That means the user won. Show a message and close the form
            DialogResult result = MessageBox.Show("You matched all the icons! Restart?", "Congratulations", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result != DialogResult.Yes)
            {
                Close();
            }
            else
            {
                panel = new TableLayoutPanel() { RowCount = row, ColumnCount = col };
                labels = new Label[row, col];
                InitializeControls();
                AssignIconsToSquares();
            }
        }
    }
}

修改完代码后直接启动即可。

有兴趣可以到微软官网查看相关细节教程:创建匹配游戏 - Visual Studio (Windows) | Microsoft Learn

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/319444.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

yolov5口罩检测模型

1 项目背景及意义 全球范围内的公共卫生安全和人脸识别技术的发展。在面对新型冠状病毒等传染病的爆发和传播风险时&#xff0c;佩戴口罩成为一种重要的防护措施。然而&#xff0c;现有的人脸识别系统在识别戴口罩的人脸时存在一定的困难。 通过口罩识别技术&#xff0c;可以…

分布式系统中的CAP原理

分布式系统中的CAP原理 本文已收录至我的个人网站&#xff1a;程序员波特&#xff0c;主要记录Java相关技术系列教程&#xff0c;共享电子书、Java学习路线、视频教程、简历模板和面试题等学习资源&#xff0c;让想要学习的你&#xff0c;不再迷茫。 简介 在分布式系统中&…

LeetCode刷题(ACM模式)-05栈与队列

参考引用&#xff1a;代码随想录 注&#xff1a;每道 LeetCode 题目都使用 ACM 代码模式&#xff0c;可直接在本地运行&#xff0c;蓝色字体为题目超链接 0. 栈与队列理论基础 21天学通C读书笔记&#xff08;二十三&#xff1a;自适应容器&#xff1a;栈和队列&#xff09; 堆…

利用GraalVM将java文件变成exe可执行文件

上期文章已经配置好了环境&#xff1a;Springboot3新特性&#xff1a;开发第一个 GraalVM 本机应用程序(完整教程)-CSDN博客 在桌面上创建一个HelloWorld.java的文件。 public class HelloWorld{public static void main (String[] args){System.out.println("Hello,Wor…

Clickhouse表引擎之CollapsingMergeTree引擎的原理与使用

前言 继续上次关于clickhouse的一些踩坑点&#xff0c;今天讲讲另外一个表引擎——CollapsingMergeTree。这个对于引擎对于数据量较大的场景是个不错的选择。注意&#xff0c;选择clickhouse的一般原因都是为了高效率查询&#xff0c;提高用户体验感&#xff0c;说白了就是以空…

blender 导入到 Marvelous Designer

1&#xff09; 将模型的所有部分合并为一个单独的mesh 2&#xff09; 先调整计量单位&#xff1a; 3&#xff09;等比缩放&#xff0c;身高调整到180cm左右 4&#xff09;应用当前scale 首先&#xff0c;选中你要修改的物体&#xff0c;然后按下Ctrl-A键&#xff0c;打开应用…

蓝桥杯练习题(九)

&#x1f4d1;前言 本文主要是【算法】——蓝桥杯练习题&#xff08;九&#xff09;的文章&#xff0c;如果有什么需要改进的地方还请大佬指出⛺️ &#x1f3ac;作者简介&#xff1a;大家好&#xff0c;我是听风与他&#x1f947; ☁️博客首页&#xff1a;CSDN主页听风与他 …

数据结构学习笔记——查找算法中的树形查找(红黑树)

目录 一、红黑树的定义&#xff08;一&#xff09;黑/红结点、叶子节点&#xff08;二&#xff09;黑色完美平衡 二、红黑树的性质&#xff08;一&#xff09;黑高和高度&#xff08;二&#xff09;叶子结点个数 三、红黑树与AVL对比 一、红黑树的定义 红黑树是一棵二叉排序树…

【OpenGauss源码学习 —— 执行器(execMain)】

执行器&#xff08;execMain&#xff09; 概述文件内容作用执行的操作主要函数概述 部分函数详细分析ExecutorStart 函数standard_ExecutorStart 函数 ExecutorRun 函数standard_ExecutorRun 函数 ExecutorFinish 函数standard_ExecutorFinish 函数 ExecutorEnd 函数standard_E…

数据库单表查询

1、显示所有职工的基本信息。 2、查询所有职工所属部门的部门号&#xff0c;不显示重复的部门号。 3、求出所有职工的人数。 4、列出最高工和最低工资。 5、列出职工的平均工资和总工资。 6、创建一个只有职工号、姓名和参加工作的新表&#xff0c;名为工作日期表…

基于PyQT的图片批处理系统

项目背景&#xff1a; 随着数字摄影技术的普及&#xff0c;人们拍摄和处理大量图片的需求也越来越高。为了提高效率&#xff0c;开发一个基于 PyQt 的图片批处理系统是很有意义的。该系统可以提供一系列图像增强、滤波、水印、翻转、放大缩小、旋转等功能&#xff0c;使用户能够…

单容水箱液位定值控制实验

实验1 单容水箱液位定值控制实验 一、实验目的 1、通过实验熟悉单回路反馈控制系统的组成和工作原理。 2、分析分别用P、PI和PID调节时的过程图形曲线。 3、定性地研究P、PI和PID调节器的参数对系统性能的影响。 二、实验设备 A3000现场系统&#xff0c;任何一个控制系统…

Java项目:03 基于Springboot的销售培训考评管理系统

项目介绍 企业的销售要进行培训&#xff0c;由技术人员进行辅导并考评检测培训效果&#xff0c;所以有了这个小系统。实现了系统的登录验证、请求拦截验证、基础模块&#xff08;用户管理、角色管理、销售管理&#xff09;、业务模块&#xff08;评分管理、评分结果&#xff0…

springboot 企业微信 网页授权

html 引入jquery $(function () {// alert("JQ onready");// 当前企业的 corp_idconst corp_id xxxxxx;// 重定向 URL → 最终打开的画面地址&#xff0c;域名是在企业微信上配置好的域名const redirect_uri encodeURI(http://xxxxx.cn);//企业的agentId 每个应用都…

基于SpringBoot的房屋交易平台的设计与实现

&#x1f345;点赞收藏关注 → 私信领取本源代码、数据库&#x1f345; 本人在Java毕业设计领域有多年的经验&#xff0c;陆续会更新更多优质的Java实战项目希望你能有所收获&#xff0c;少走一些弯路。&#x1f345;关注我不迷路&#x1f345;一 、设计说明 1.1 研究背景 互…

Nightingale 夜莺监控系统 - 部署篇(1)

Author&#xff1a;rab 官方文档&#xff1a;https://flashcat.cloud/docs 目录 一、概述二、架构2.1 中心机房架构2.2 边缘下沉式混杂架构 三、环境四、部署4.1 中心机房架构部署4.1.1 MySQL4.1.2 Redis4.1.3 Prometheus4.1.4 n9e4.1.5 Categraf4.1.6 验证4.1.7 配置数据源 4…

安装、运行和控制AI apps在您的计算机上一键式

pinokio 你是否曾为安装、运行和自动化 AI 应用程序和大模型而感到困惑&#xff1f;是否希望有一个简单而强大的工具来满足你的需求&#xff1f;如果是这样&#xff0c;那么 Pinokio 将会是你的理想选择&#xff01;Pinokio 是一款革命性的人工智能浏览器&#xff0c;是一个开…

专业课140+总分410+电子科技大学858信号与系统考研经验,电子信息通信

我的初试备考从4月末&#xff0c;持续到初试前&#xff0c;这中间没有中断。 我是二战考生&#xff0c;准备的稍微晚一些&#xff0c;如果是一战考生&#xff0c;建议在2、3月份开始。 总的时间分配上&#xff0c;是数学>专业课>英语>政治&#xff0c;虽然大家可支配…

Python如何免费调用微软Bing翻译API

一、引言 现在免费的机器翻译越来越少了&#xff0c;随着有道翻译开始收费&#xff0c;百度降低用户的免费机器翻译额度(目前只有实名认证过的高级用户才能获得100万字符的免费翻译额度)&#xff0c;而亚马逊、腾讯等机器翻译调用相对比较麻烦&#xff0c;需要下载各种插件包&…
最新文章