C# Winform翻牌子记忆小游戏

这篇具有很好参考价值的文章主要介绍了C# Winform翻牌子记忆小游戏。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

效果

C# Winform翻牌子记忆小游戏,c#,开发语言

源码

新建一个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文章来源地址https://www.toymoban.com/news/detail-795853.html

到了这里,关于C# Winform翻牌子记忆小游戏的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C#课程设计 ——小游戏打地鼠

    课程设计说明书 代码(32条消息) C#课程设计-打地鼠小游戏-C#文档类资源-CSDN文库 设计题目: 打地鼠小游戏 院(系) 软件工程学院 专业年级 19级计科1班 学生姓名 学号 同组同学姓名 学号 指导教师 日 期 2021年12月 目 录 1 引 言 3 1.1课程设计的目的 3 1.2本选题的内容要求 3 1.

    2024年02月10日
    浏览(39)
  • 基于C#制作一个贪吃蛇小游戏

    基于C#制作一个贪吃蛇小游戏,简单耐玩,操作简单。

    2024年02月08日
    浏览(36)
  • 【Pygame小游戏】史上最全:《唐诗三百首》合集,每一首都是精华,果断收藏~(学诗+锻炼记忆+Python诗句填空小程序上线啦)

      岁岁年龄岁岁心,不负时光不负卿 哈喽!我是你们的栗子同学,今天给大家来点儿有趣的—— 有句话说:“读史使人明智,读诗使人灵秀。” 唐诗本来就是中国文化的绚丽瑰宝,是每个人都 该学习的人生必修课。栗子今天特意为大家整理了《唐诗三百首》合集,带你品读

    2024年02月09日
    浏览(33)
  • [C语言][小游戏][猜拳游戏]

    前言: 给大家演示一个简单小游戏,真的非常详细。 模块化编程:把各个模块的代码放在不同的.c文件里,在.h文件里提供外部可调用函数的声明,其它.c文件想使用其中的代码时,只需要#include \\\"XXX.h\\\"文件即可。使用模块化编程可极大的提高代码的可阅读性、可维护性、可移

    2024年02月15日
    浏览(31)
  • [C语言][小游戏][猜数游戏]

    带着梦想,带着好奇,带着执着,在C语言的世界里旅行。亲爱的朋友们,一起加油。 显示玩家从键盘输入的值和计算机事先准备的“目标数字”进行比较 1)本游戏的“目标数字”是7,用变量ans表示,从键盘输入的值则用变量no表示。 2)程序通过if来判断no和ans两个变量值的大

    2024年02月13日
    浏览(32)
  • 小游戏:人生中写的第一个小游戏——贪吃蛇(C语言)

            小编开了一个关于游戏的专栏,主要是运用easyx图形库进行的。        第一章:人生中写的第一个小游戏——贪吃蛇(C语言)         这个游戏的代码我在gitee上发布了,大家如果不嫌弃,可以进入这个网址进行查看和复制:https://gitee.com/rising-sun-1。      

    2024年02月09日
    浏览(46)
  • C语言扫雷小游戏

    扫雷的玩法:在一个9×9(初级)、16×16(中级)、16×30(高级)或自定义大小的方块矩阵中随机布置一定量的地雷(初级为10个,中级为40个,高级为99个),再由玩家逐个翻开方块,翻开的地方将显示周围八个雷的个数。以找出所有地雷为最终游戏目标。如果玩家翻开的方块

    2024年02月05日
    浏览(35)
  • C语言简易小游戏

    本篇博客将带领大家自己动手写一下一些C语言小游戏;以增加对于C语言的兴趣😀😀😀😀😀 首先呢我们先来简单介绍一下这个小游戏: 通常由两个人玩,一方出数字,一方猜。出数字的人要想好一个没有重复数字,不能让猜的人知道。猜的人就可以开始猜。 如正确答案为

    2024年02月07日
    浏览(31)
  • 扫雷小游戏【C语言】

    目录 前言 一、基本实现逻辑 二、实现步骤 1. 我们希望在进入游戏时有一个菜单让我们选择 2. 我们希望可以重复的玩(一把玩完了还可以接着玩) 3. 采用多文件形式编程  4.要扫雷先得有棋盘(创建棋盘R*N) 5.初始化棋盘  6.打印棋盘 7.设置雷 8.排查雷 三、全部源码: 上期

    2024年02月11日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包