百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

C# winform 简单五子棋 200行代码实现双人对战

bigegpt 2024-08-03 11:33 7 浏览

1、需求

基于C# winform用200行代码实现简易五子棋双人对战,支持悔棋,需要的知识有C# winform界面,C#,以及几张素材图片。

2、界面

界面设计如图1所示,背景图是用Graphics自己画的,但在生成棋子图片的时候,消失了,知道的同学告诉我一下谢谢,因此自己截图做背影,把图片导入项目得到背景图,设想是可以有双人,人机,联网三个模式,后续会加入。


3、算法描述

由于只是双人对战,因此算法就是简单判断是否赢棋,五子棋规则是横竖斜三个方向有一个方向能有连续五个棋子即赢棋,所以分别判断感人方向,这里采用递归判断,思想非常简单。

(1)遍历每个棋子

(2)斜方向找相同棋子,如果找到就继续找,找到五个即赢棋,游戏结束转(5)

(3)横方向找相同棋子,如果找到就继续找,找到五个即赢棋,游戏结束转(5)

(4)竖方向找相同棋子,如果找到就继续找,找到五个即赢棋,游戏结束转(5)

(5)点击确实重新初始化游戏数据

4、代码实现

2中提到使用Graphics画棋盘,但生成棋子后却不能消失了,因此使用的画好后的截图,给出的代码有画棋盘的(draw_chess_grid函数),但在程序中没有调用。检测棋盘赢局用的是递归,为了思路清楚,把每个方向分开写成一个函数,在代码中有注释。详细代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsAppAnimalRegonize
{
    public partial class FormChess : Form
    {
        class Pos
        {
            public int X { get; set; }
            public int Y { get; set; }
            public bool Have_chess { get; set; }
            public int Type { get; set; }
            public Pos(int X, int Y, bool Have_chess, int Type)
            {
                this.X = X;
                this.Y = Y;
                this.Have_chess = Have_chess;
                this.Type = Type;
            }
        }
        private List<Pos> null_chess_pos_list;//棋子位置序列
        private Stack<Button> cur_chess_btn_list;//当前所下的棋子,悔棋时用
        private int game_type;//当前哪方下棋
        private string[] game_types = {"双人对战","人机对战","联网对战" };
        public FormChess()
        {
            InitializeComponent();
            comboBox1.Items.AddRange(game_types);
            comboBox1.SelectedIndex = 0;
        }
        private void init_game()
        {
            //黑棋先走
            game_type = 0;
            if (null_chess_pos_list == null)
            {
                null_chess_pos_list = new List<Pos>();
                for (int x = 0; x < 13; x++)
                {
                    for (int y = 0; y < 13; y++)
                    {
                        new_chess_pos(30 + 50 * x, 30 + 50 * y);
                        var pos = new Pos(x, y, false, -1);//-1代表此位置没有棋子,0代表黑棋,1代表白棋
                        null_chess_pos_list.Add(pos);
                    }
                }
            }
            else
            {
                for (int i = 0; i < null_chess_pos_list.Count; i++)
                {
                    null_chess_pos_list[i].Have_chess = false;
                    null_chess_pos_list[i].Type = -1;
                }
            }
            if (cur_chess_btn_list == null) cur_chess_btn_list = new Stack<Button>();
            else
            {
                while (cur_chess_btn_list.Count > 0)
                {
                    var btn = cur_chess_btn_list.Peek();
                    btn.BackgroundImage = Properties.Resources.chess_bg1;//设置背景色为透明
                    cur_chess_btn_list.Pop();
                }
            }
            set_game_type_label();
        }
        //绘制棋盘
        private void draw_chess_grid()
        {
            var graphics = this.CreateGraphics();
            this.Show();//一定要加这句,不然无法显示
            var pen = new Pen(Brushes.Black, 2.0f);
            for (int x = 0; x < 13; x++)
            {
                var p1 = new Point(50 + x * 50, 50);
                var p2 = new Point(50 + x * 50, 50 + 50 * 12);
                graphics.DrawLine(pen, p1, p2);
            }
            for (int y = 0; y < 13; y++)
            {
                var p1 = new Point(50, 50 + y * 50);
                var p2 = new Point(50 + 50 * 12, 50 + y * 50);
                graphics.DrawLine(pen, p1, p2);
            }
        }
        //右上方向判断
        private void right_up_check(Pos pos,int count)
        {
            if (count == 5) {
                if (pos.Type == 0)MessageBox.Show("黑方赢棋", "系统提示");
                else MessageBox.Show("白方赢棋", "系统提示");
                init_game();
                return;
            }
            if(pos.X + 1 <13 && pos.Y - 1 >0 && pos.Type != -1)
            {
                var index = get_pos_index_from_null_chess_list(pos.X + 1, pos.Y - 1);
                if (null_chess_pos_list[index].Type == pos.Type) right_up_check(null_chess_pos_list[index],count + 1);
            }
        }
        //左上方向判断
        private void left_up_check(Pos pos, int count)
        {
            if (count == 5)
            {
                if (pos.Type == 0) MessageBox.Show("黑方赢棋", "系统提示");
                else MessageBox.Show("白方赢棋", "系统提示");
                init_game();
                return ;
            }
            if (pos.X - 1 > 0 && pos.Y - 1 > 0 && pos.Type != -1)
            {
                var index = get_pos_index_from_null_chess_list(pos.X - 1, pos.Y - 1);
                if (null_chess_pos_list[index].Type == pos.Type ) left_up_check(null_chess_pos_list[index], count + 1);
            }
        }
        //横向方向判断
        private void horizontal_check(Pos pos, int count)
        {
            if (count == 5)
            {
                if (pos.Type == 0) MessageBox.Show("黑方赢棋", "系统提示");
                else MessageBox.Show("白方赢棋", "系统提示");
                init_game();
                return ;
            }
            if (pos.X + 1 < 13 && pos.Type != -1)
            {
                var index = get_pos_index_from_null_chess_list(pos.X + 1, pos.Y );
                if (null_chess_pos_list[index].Type == pos.Type) horizontal_check(null_chess_pos_list[index], count + 1);
            }
        }
        //竖向方向判断
        private void vertical_check(Pos pos, int count)
        {
            if (count == 5)
            {
                if (pos.Type == 0) MessageBox.Show("黑方赢棋", "系统提示");
                else MessageBox.Show("白方赢棋", "系统提示");
                init_game();
                return ;
            }
            if (pos.Y + 1 < 13 && pos.Type != -1)
            {
                var index = get_pos_index_from_null_chess_list(pos.X , pos.Y + 1);
                if (null_chess_pos_list[index].Type == pos.Type) vertical_check(null_chess_pos_list[index], count + 1);
            }
        }
        //判断赢局
        private void check_win()
        {
            for (int i = 0; i < null_chess_pos_list.Count; i++)
            {
                left_up_check(null_chess_pos_list[i], 1);
                right_up_check(null_chess_pos_list[i], 1);
                horizontal_check(null_chess_pos_list[i], 1);
                vertical_check(null_chess_pos_list[i], 1);
            }
        }
        //初始生成下棋位置
        private void new_chess_pos(int x,int y)
        {
            var button = new Button();
            button.Location = new Point(x, y);
            button.Size = new Size(40, 40);
            set_btn_style(button);
            this.Controls.Add(button);
            button.Click += new EventHandler(button1_Click);
        }
        //窗口坐标转点坐标
        private Point location_to_point(Button button)
        {
            return new Point((button.Location.X - 30)/50, (button.Location.Y - 30)/50);
        }
        //根据点坐标得到索引
        private int get_pos_index_from_null_chess_list(int x,int y)
        {
            for (int i = 0; i < null_chess_pos_list.Count; i++)
                if (null_chess_pos_list[i].X == x && null_chess_pos_list[i].Y == y)return i;
            return -1;
        }
        //走棋
        private void move_chess(Button button)
        {
            var point = location_to_point(button);
            var index = get_pos_index_from_null_chess_list(point.X, point.Y);
            if (null_chess_pos_list[index].Have_chess) return;
            null_chess_pos_list[index].Have_chess = true;
            if (game_type == 0)
            {
                button.BackgroundImage = Properties.Resources.black;
                null_chess_pos_list[index].Type = 0;
                game_type = 1;
            }
            else
            {
                button.BackgroundImage = Properties.Resources.white;
                null_chess_pos_list[index].Type = 1;
                game_type = 0;
            }
            set_game_type_label();
            //添加到下棋栈列
            cur_chess_btn_list.Push(button);
            check_win();
        }
        
        // 设置透明按钮样式
        private void set_btn_style(Button btn)
        {
            btn.FlatStyle = FlatStyle.Flat;//样式
            btn.ForeColor = Color.Transparent;//前景
            btn.BackColor = Color.Transparent;//去背景
            btn.FlatAppearance.BorderSize = 0;//去边线
            btn.FlatAppearance.MouseOverBackColor = Color.Transparent;//鼠标经过
            btn.FlatAppearance.MouseDownBackColor = Color.Transparent;//鼠标按下
        }
        //提示当前由哪方下棋
        private void set_game_type_label()
        {
            if (game_type == 0) label_game_type.Text = "黑方下棋";
            else label_game_type.Text = "白方下棋";
        }
        //悔棋
        private void back_chess()
        {
            if (cur_chess_btn_list==null) return;
            if (cur_chess_btn_list.Count == 0) return;
            var btn = cur_chess_btn_list.Peek();
            var p = location_to_point(btn);
            var index = get_pos_index_from_null_chess_list(p.X,p.Y);
            null_chess_pos_list[index].Type = -1;
            null_chess_pos_list[index].Have_chess = false;
            btn.BackgroundImage = Properties.Resources.chess_bg1;
            cur_chess_btn_list.Pop();
            if (game_type == 0) game_type = 1;
            else game_type = 0;
            set_game_type_label();
        }
        //下棋点击事件
        private void button1_Click(object sender, EventArgs e)
        {
            move_chess((Button)sender);
        }
        private void button_start_Click(object sender, EventArgs e)
        {
            switch (comboBox1.SelectedItem.ToString())
            {
                case "双人对战":
                    init_game();
                    break;
                case "人机对战":
                    break;
                case "联网对战":
                    break;
            }
        }
        //悔棋
        private void button_back_Click(object sender, EventArgs e)
        {
            back_chess();
        }
        //重置游戏
        private void button_reset_Click(object sender, EventArgs e)
        {
            switch (comboBox1.SelectedItem.ToString())
            {
                case "双人对战":
                    init_game();
                    break;
                case "人机对战":
                    break;
                case "联网对战":
                    break;
            }
        }
    }
}

5、结果

测试结果之一如图2,其他方向与悔棋均能通过测试。

相关推荐

【机器学习】数据挖掘神器LightGBM详解(附代码)

来源:机器学习初学者本文约11000字,建议阅读20分钟本文为你介绍数据挖掘神器LightGBM。LightGBM是微软开发的boosting集成模型,和XGBoost一样是对GBDT...

3分钟,用DeepSeek全自动生成语音计算器,还带括号表达式!

最近,大家慢慢了解到了DeepSeek的强大功能,特别是它在编程领域也同样强大。编程零基础小白,一行代码不用写,也能全自动生成一个完整的、可运行的软件来!很多程序员一直不相信小白不写代码也能编软件!下...

python学习笔记 3.表达式

在Python中,表达式是由值、变量和运算符组成的组合。以下是一些常见的Python表达式:算术表达式:由数值和算术运算符组成的表达式,如加减乘除等。例如:5+3、7*2、10/3等。字符...

5.7 VS 8.x,为什么用户不升级MySql

一般来说为了更好的功能和性能,都需要将软件升级到最新的版本,然而在开源软件中,由于一些开发商变化或其他的问题(开源授权变化),致使人们不愿使用最新的版本,一个最典型的问题就是CentOS操作系统。还有...

大厂高频:讲一下MySQL主从复制

大家经常听说主从复制,那么主从复制的意义?能解决的问题有哪些?主从复制能解决的问题就是在我们平时开发的程序中操作数据库的时候,大多数的情况查询的操作大大超过了写的操作,也就说对数据库读取数据的压力比较...

MYSQL数据库的五大安全防护措施

以技术为基础的企业里最有价值的资产莫过于是客户或者其数据库中的产品信息了。因此,在这样的企业中,保证数据库免受外界攻击是数据库管理的重要环节。很多数据库管理员并没有实施什么数据库保护措施,只是因为觉得...

docker安装mysql

准备工作已安装Docker环境(官方安装文档)终端/命令行工具(Linux/macOS/WSL)步骤1:拉取MySQL镜像打开终端执行以下命令,拉取官方MySQL镜像(默认最新版本):d...

Zabbix监控系统系列之六:监控 mysql

zabbix监控mysql1、监控规划在创建监控项之前要尽量考虑清楚要监控什么,怎么监控,监控数据如何存储,监控数据如何展现,如何处理报警等。要进行监控的系统规划需要对Zabbix很了解,这里只是...

详解MySQL的配置文件及优化

#头条创作挑战赛#在Windows系统中,MySQL服务器启动时最先读取的是my.ini这个配置文件。在Linux系统中,配置文件为my.cnf,其路径一般为/etc/my.cnf或/etc/mysq...

Mysql 几个批处理执行脚本

学习mysql过程中,需要创建测试数据,并让多人每人一个数据库连接并进行作业检查。整合部分批处理创建数据批量创建数据库DELIMITER$CREATEPROCEDURECreateDatab...

MySQL学到什么程度?才有可以在简历上写精通

前言如今互联网行业用的最多就是MySQL,然而对于高级Web面试者,尤其对于寻找30k下工作的求职者,很多MySQL相关知识点基本都会涉及,如果面试中,你的相关知识答的模糊和不切要点,基...

mysql 主、从服务器配置“Slave_IO_Running: Connecting” 问题分析

#在进行mysql主、从服务器配置时,”SHOWSLAVESTATUS;“查看从库状态Slave_IO_Runing,出现错误:“Slave_IO_Running:Connectin...

MYSQL数据同步

java开发工程师在实际的开发经常会需要实现两台不同机器上的MySQL数据库的数据同步,要解决这个问题不难,无非就是mysql数据库的数据同步问题。但要看你是一次性的数据同步需求,还是定时数据同步,亦...

「MySQL 8」MySQL 5.7都即将停只维护了,是时候学习一波MySQL 8了

MySQL8新特性选择MySQL8的背景:MySQL5.6已经停止版本更新了,对于MySQL5.7版本,其将于2023年10月31日停止支持。后续官方将不再进行后续的代码维护。另外,...

Prometheus监控mysql

通过Prometheus监控Mysql,我们需要在Mysql端安装一个mysql-exporter,然后Prometheus通过mysql-exporter暴露的端口抓取数据。1.安装一个MYSQL配...