昨天下午我把《C#仿魔兽世界密保卡简单实现》 中的代码用面向对象的方法重构了一遍,引入了2个类:MatrixCard和Cell。MatrixCard描述的是密保卡,构造函数中会随机生成一个二 维矩阵,所以每次new一个MatrixCard对象,就已经生成了一张密保卡。Cell是单元格的意思,将行号、列号、列名做了封装。 MatrixCard类中保留了之前的大部分静态方法,以便灵活调用。
由于本人水平有限,这次的设计并不是非常完美,并且也有一些遗憾。比如现在只能通过Cell[i]的方式来访问单元格,而不可以像Cell["A0"]这样写。有空的时候哥去研究一下重载索引器,争取把它实现。下面发代码:
MatrixCard类:
using System; using System.Collections.Generic; namespace GeekStudio.Common { ////// 矩阵卡类 /// public class MatrixCard { private int _cardId; private int _randomStart; private int _randomEnd; private List_cell; /// | /// 卡号 /// public int CardId { get { return _cardId; } set { _cardId = value; } } ////// 下界 /// public int RandomStart { get { return _randomStart; } set { _randomStart = value; } } ////// 上界 /// public int RandomEnd { get { return _randomEnd; } set { _randomEnd = value; } } ////// 单元格集合 /// public ListCell { get { return _cell; } set { _cell = value; } } /// | /// 保存到数据库 /// ///public bool Save() { string str = this.ToString(); if (!String.IsNullOrEmpty(str)) { try { /* SAVE INTO DB */ return true; } catch { return false; } } return false; } /// /// 验证用户输入 /// /// 用户输入的Cell集合 ///是否成功 public bool Validate(ListcellsToValidate) { if (cellsToValidate.Count < 3) { return false; } int col1 = cellsToValidate[0].ColIndex; int row1 = cellsToValidate[0].RowIndex; int col2 = cellsToValidate[1].ColIndex; int row2 = cellsToValidate[1].RowIndex; int col3 = cellsToValidate[2].ColIndex; int row3 = cellsToValidate[2].RowIndex; int cellIndex1 = row1 * 5 + col1; int cellIndex2 = row2 * 5 + col2; int cellIndex3 = row3 * 5 + col3; bool OK1 = this.Cell[cellIndex1].Value == cellsToValidate[0].Value; bool OK2 = this.Cell[cellIndex2].Value == cellsToValidate[1].Value; bool OK3 = this.Cell[cellIndex3].Value == cellsToValidate[2].Value; if (OK1 && OK2 && OK3) { return true; } return false; } /// | /// 随机选择单元格让用户验证 /// /// 单元格个数 /// 上界 /// 下界 ///Cell集合 public ListPickUpRandomCells(int howMany, int colUpper, int rowUpper) { Random r = new Random(); List | cells = new List | (); for (int i = 0; i < howMany; i++) { int randomCol = r.Next(0, colUpper); int randomRow = r.Next(0, rowUpper); Cell c = new Cell(randomRow, randomCol); cells.Add(c); } return cells; } /// | /// 重写ToString方法,将Cell集合输出为矩阵字符串 /// ///public override string ToString() { // 我希望MatrixCard.ToString()能输出 卡号、矩阵字符串, // 而MatrixCard.Cell.ToString()只输出矩阵字符串。 // 如何实现? int[,] arr = ConvertCellListToMatrixArray(this.Cell); return ConvertMatrixArrayToString(arr); } /// /// 由字符串给Cell集合赋值 /// /// 矩阵字符串 ///是否成功 public bool Fill(string strMatrix) { try { int[,] temparr = ConvertStringToMatrixArray(strMatrix); Fill(temparr); return true; } catch (Exception) { return false; } } ////// 由数组给Cell集合赋值 /// /// 矩阵数组 ///是否成功 public bool Fill(int[,] array) { try { Listcells = ConvertMatrixArrayToCellList(array); this.Cell = cells; return true; } catch { return false; } } /// | /// 构造函数,随机生成一张5x5矩阵卡,数值范围[0,100) /// public MatrixCard() { int[,] arr = GenerateRandomMatrix(5, 5, 0, 100); Fill(arr); } ////// 构造函数,由字符串生成矩阵卡 /// /// 矩阵字符串 public MatrixCard(string strMatrix) { Fill(strMatrix); } // -------------------------------静态方法-------------------------------- #region Static Methods // ----------------------------死不要脸的分割线---------------------------- ////// 将矩阵数组转换为Cell集合(以便在MatrixCard对象中操作) /// /// 矩阵数组 ///Cell集合 public static ListConvertMatrixArrayToCellList(int[,] array) { List | cells = new List | (); int[] lineArr = new int[25]; int k = 0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { lineArr[k] = array[i, j]; Cell c = new Cell(i, j); c.Value = lineArr[k]; cells.Add(c); k++; } } return cells; } /// | /// 将Cell集合转换为矩阵数组 /// /// Cell集合 ///矩阵数组 public static int[,] ConvertCellListToMatrixArray(Listcells) { int[,] arr = new int[5, 5]; int k = 0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { arr[i, j] = cells[k].Value; k++; } } return arr; } /// | /// 生成随机矩阵 /// /// 行数 /// 列数 /// 下界 /// 上界 ///矩阵数组 public static int[,] GenerateRandomMatrix(int rows, int cols, int randomStart, int randomEnd) { Random r = new Random(); int[,] arr = new int[5, 5]; // control rows for (int i = 0; i < rows; i++) { // control cols for (int j = 0; j < cols; j++) { arr[i, j] = r.Next(randomStart, randomEnd); } } return arr; } ////// 由矩阵字符串生成矩阵数组 /// /// 矩阵字符串 ///矩阵数组 public static int[,] ConvertStringToMatrixArray(string matrixStr) { int[,] arr = new int[5, 5]; int[] tempArr = new int[25]; int k = 0; string[] tempArrStr = matrixStr.Split(','); for (int i = 0; i < tempArr.Length; i++) { tempArr[i] = Convert.ToInt32(tempArrStr[i]); } for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { arr[i, j] = tempArr[k]; k++; } } return arr; } ////// 将矩阵数组保存为矩阵字符串 /// /// 矩阵数组 ///矩阵字符串 public static string ConvertMatrixArrayToString(int[,] arr) { string matrixStr = String.Empty; int[] lineArr = new int[25]; int k = 0; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { lineArr[k] = arr[i, j]; k++; } } for (int i = 0; i < lineArr.Length; i++) { matrixStr += lineArr[i]; if (i < 24) { matrixStr += ","; } } return matrixStr; } ////// 验证用户输入 /// /// 矩阵数组 /// 列号1 /// 行号1 /// 列号2 /// 行号2 /// 列号3 /// 行号3 /// 用户输入的字符串 ///是否成功 public static bool Validate(int[,] arr, int colIndex1, int rowIndex1, int colIndex2, int rowIndex2, int colIndex3, int rowIndex3, string userInput) { try { string[] inputArr = userInput.Split(','); bool OK0 = arr[rowIndex1, colIndex1] == Convert.ToInt32(inputArr[0]); bool OK1 = arr[rowIndex2, colIndex2] == Convert.ToInt32(inputArr[1]); bool OK2 = arr[rowIndex3, colIndex3] == Convert.ToInt32(inputArr[2]); if (OK0 && OK1 && OK2) { return true; } else { return false; } } catch (Exception) { Console.WriteLine("Oh, Shit!"); } return false; } #endregion } }
Cell类:
namespace GeekStudio.Common { ////// 单元格类 /// public class Cell { private int _rowIndex; private int _colIndex; private ColCodeEnum _colCode; private int _value; ////// 行号 /// public int RowIndex { get { return _rowIndex; } set { _rowIndex = value; } } ////// 列号 /// public int ColIndex { get { return _colIndex; } set { _colIndex = value; } } ////// 列名 /// public ColCodeEnum ColCode { get { return _colCode; } set { _colCode = value; } } ////// 值 /// public int Value { get { return _value; } set { _value = value; } } ////// 列名枚举 /// public enum ColCodeEnum { A = 0, B = 1, C = 2, D = 3, E = 4 }; public Cell() { this._value = 0; } public Cell(int rowIndex, int colIndex) { this._rowIndex = rowIndex; this._colIndex = colIndex; this._colCode = GetColCode(colIndex); this._value = 0; } public Cell(int rowIndex, ColCodeEnum colCode) { this._rowIndex = rowIndex; this._colIndex = GetColIndex(colCode); this._colCode = colCode; this._value = 0; } ////// 根据列名获取列号 /// /// 列名 ///列号 public static int GetColIndex(ColCodeEnum colCode) { return (int)colCode; } ////// 根据列号获取列名 /// /// 列号 ///列名 public static ColCodeEnum GetColCode(int colIndex) { ColCodeEnum colCode = ColCodeEnum.A; switch (colIndex) { case 0: colCode = ColCodeEnum.A; break; case 1: colCode = ColCodeEnum.B; break; case 2: colCode = ColCodeEnum.C; break; case 3: colCode = ColCodeEnum.D; break; case 4: colCode = ColCodeEnum.E; break; default: break; } return colCode; } } }
ASP.NET调用:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using GeekStudio.Common; using System.Text; public partial class MatrixCardTest : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { MatrixCard mc = new MatrixCard(); StringBuilder sb = PrintMatrixToHtmlTable(mc); ltrMatrixCard.Text = sb.ToString(); Session["mc"] = mc; // 随机选择3个单元格给用户验证 ListcellsToValidate = mc.PickUpRandomCells(3, 5, 5); lblCellText = String.Format("{0}{1}", cellsToValidate[0].ColCode, cellsToValidate[0].RowIndex); lblCellText = String.Format("{0}{1}", cellsToValidate[1].ColCode, cellsToValidate[1].RowIndex); lblCellText = String.Format("{0}{1}", cellsToValidate[2].ColCode, cellsToValidate[2].RowIndex); Session["cellsToValidate"] = cellsToValidate; } } private static StringBuilder PrintMatrixToHtmlTable(MatrixCard mc) { StringBuilder sb = new StringBuilder(); sb.Append(" | "); sb.Append("
"); return sb; } protected void btnSubmit_Click(object sender, EventArgs e) { MatrixCard mc = null; if (Session["mc"] != null) { mc = (MatrixCard)Session["mc"]; } List"); int i = 0; for (int k = 0; k < 5; k++) { sb.Append(" A B C D E "); sb.Append(String.Format(" "); } sb.Append("{0} ", k)); for (int l = 0; l < 5; l++) { sb.Append(String.Format("{0} ", mc.Cell[i].Value)); i++; } sb.Append("cellsToValidate = null; if (Session["cellsToValidate"] != null) { cellsToValidate = (List | )Session["cellsToValidate"]; } cellsToValidate[0].Value = Convert.ToInt32(txtCellText.Trim()); cellsToValidate[1].Value = Convert.ToInt32(txtCellText.Trim()); cellsToValidate[2].Value = Convert.ToInt32(txtCellText.Trim()); bool OK = mc.Validate(cellsToValidate); if (OK) { lblStatus.Text = "Your input were correct!"; } else { lblStatus.Text = "Sorry, your input were wrong!"; } } } |
有图有真相: