繁体   English   中英

如何使用 C# 在数独游戏中验证用户的输入

[英]How to Validate user's input in a Sudoku's game using C#

我正在尝试实现一个数独游戏,我已经能够用值填充游戏控件,但是我在验证输入字段时遇到了挑战,这是我的代码:

private void Populate()
    {
        List<string> num = new List<string>();

        foreach (string line in File.ReadLines("Sudoku Text File.txt"))
        {
            num.Add(line);
        }
        Random rnd = new Random();
        rand = rnd.Next(1, 5);
        var number = num[rand];
        listBox1.Items.Add(number);

        for (int i = 0; i < number.Length; i++)
        {

            if (number[i] == '0')
            {
                panel1.Controls[i].Text = "";
            }
            else
            {
                panel1.Controls[i].Text = number[i].ToString();
                panel1.Controls[i].Enabled = false;
            }               
        }

    }

数独文本文件具有以下值:

4000001002004021
0200002030204001
0040010220000423
4000000220041400
0200103201200001

我希望能够在错误或正确时验证并向用户显示。

游戏规则是,数字 1 到 4 在行、列和块中不得出现多次。

任何援助将不胜感激。

为了简化验证,您应该使用视图 model 来处理您的游戏逻辑,然后在表单上显示数字。 这将使您的游戏反应: user input => game logic processing => display 这是游戏逻辑处理器的非常基本的示例:

    class SudokuViewModel
    {
        private readonly int[,] field;
        public int[,] Field  { get => field; }

        private readonly (int, int)[][] blocks = new [] 
        {
            new [] {(0,0), (0,1), (1, 0), (1, 1)},
            new [] {(0,2), (0,3), (1, 2), (1, 3)},
            new [] {(2,0), (2,1), (3, 0), (3, 1)},
            new [] {(2,2), (2,3), (3, 2), (3, 3)}
        };

        public SudokuViewModel()
        {
            field = new int[4,4];
        }

        public bool ChangeCell(int x, int y, int val)
        {
            for (var i = 0; i < field.GetLength(0); i++)
            {
                if (field[i, y] == val)
                    return false;
            }
            for (var i = 0; i < field.GetLength(1); i++)
            {
                if (field[x, i] == val)
                    return false;
            }
            var blockNum = GetBlockNumber(x, y);
            var block = blocks[blockNum];
            foreach (var (xx, yy) in block)
            {
                if (!(x == xx && y == yy)) //don't check self
                {
                    if (field[xx, yy] == val)
                        return false;
                }
            }

            field[x,y] = val;
            return true;
        }

        private int GetBlockNumber(int x, int y)
        {
            // find in which block we landed
            throw new NotImplementedException();
        }
    }

因此,您可以调用ChangeCell并查看用户输入是否有效。 如果不是,那么您将显示一些内容,让用户知道此移动无效。 如果输入有效,则字段已更改,您可以更新表单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM