您好,欢迎访问一九零五行业门户网

如何使用C#来编写的一个完整字谜游戏的示例代码分享

介绍字谜游戏,可能你在许多益智书中都曾看到过。试着在电脑上用不同类别的内容写字谜游戏,并且有自定义字词去玩也是很有意思的。
背景我很早以前使用turbo c编码游戏,但我丢失了代码。我觉得用c#.net让它复活将是一件很伟大的事情。该语言在内存、gc、图形方面提供了很多灵活性,而这些是我在使用c语言的时候必须小心处理的。但是在c语言中的明确关注,会让我们学到很多(这就是为什么c语言被称为“上帝的编程语言”的原因)。另一方面,因为c#.net照顾到了这些,所以我可以专注于其他地方的增强,例如字的方向,重叠,作弊码,计分,加密等。所以在欣赏两种语言的时候需要有一个平衡。
在题目中我之所以说它是“完整的”,原因如下:
1)它有一些类别的预设词。
2)它在加密文件中保存单词和分数,这样就没有人可以篡改文件。如果要篡改,那么它将恢复到预设并从头开始计分。
3)它有作弊码,但作弊会不利于得分,且显然作弊一旦应用会使分数归零。
4)它有一个计分机制。
使用代码游戏提供以下功能,具体我将在随后的章节中讨论:
1)载入类别和单词:从程序中硬编码的预设中加载单词。然而,如果玩家提供自定义的单词,那么游戏将自动把所有这些(连同预设)存储在文件中并从那里读取。
2)放在网格上:游戏将所有的单词随机地放在18×18的矩阵中。方向可以是水平,垂直,左下和右下,如上图中所示。
3)计分:对于不同类别,分数单独存储。分数的计算方式是单词的长度乘以乘法因子(这里为10)。与此同时,在找到所有的单词之后,剩余时间(乘以乘法因子)也会加到分数中。
4)显示隐藏的单词:如果时间用完之后,玩家依然找不到所有的单词,那么游戏会用不同的颜色显示没找到的单词。
5)作弊码:游戏在游戏板上提作弊码(mambazamba)。作弊码只简单地设置了一整天的时间(86,400秒)。但是,应用作弊码也会应用让此次运行的计分为零的惩罚。
1)载入类别和单词:载入预设
我们有一个简单的用于持有类别和单词的类:
class wordentity { public string category { get; set; } public string word { get; set; } }
我们有一些预设的类别和单词如下。预设都是管道分隔的,其中每第15个单词是类别名称,后面的单词是该类别中的单词。
private string preset_words = "countries|bangladesh|gambia|australia|england|nepal|india|pakistan|tanzania|srilanka|china|canada|japan|brazil|argentina|" + "music|pinkfloyd|metallica|ironmaiden|nova|artcell|feedback|orthohin|defleppard|beatles|adams|jackson|parton|houston|shakira|" + ...
我们使用加密在文件中写这些单词。所以没有人可以篡改文件。对于加密我使用了一个从这里借鉴的类。使用简单——你需要传递字符串和用于加密的加密密码。对于解密,你需要传递加密的字符串和密码。
如果文件存在,那么我们从那里读取类别和单词,否则我们保存预设(以及玩家自定义的单词)并从预设那里读取。这在下面的代码中完成:
if (file.exists(file_name_for_storing_words)) // if words file exists, then read it. readfromfile(); else { // otherwise create the file and populate from there. string encryptedwords = stringcipher.encrypt(preset_words, encryption_password); using (streamwriter outputfile = new streamwriter(file_name_for_storing_words)) outputfile.write(encryptedwords); readfromfile(); }
readfromfile()方法简单地从存储单词的文件中读取。它首先尝试解密从文件读取的字符串。如果失败(由返回的空白字符串确定),它将显示关于问题的一条消息,然后从内置预设重新加载。否则它从字符串读取并将它们分成类别和单词,并把它们放在单词列表中。每第15个词是类别,后续词是该类别下的单词。
string str = file.readalltext(file_name_for_storing_words); string[] decryptedwords = stringcipher.decrypt(str, encryption_password).split('|'); if (decryptedwords[0].equals("")) // this means the file was tampered. { messagebox.show("the words file was tampered. any categories/words saved by the player will be lost."); file.delete(file_name_for_storing_words); populatecategoriesandwords(); // circular reference. return; } string category = ""; for (int i = 0; i <= decryptedwords.getupperbound(0); i++) { if (i % (max_words + 1) == 0) // every 15th word is the category name. { category = decryptedwords[i]; categories.add(category); } else { wordentity word = new wordentity(); word.category = category; word.word = decryptedwords[i]; wordslist.add(word); } }
保存玩家的自定义词
游戏可供应由玩家提供的自定义词。设备位于相同的加载窗口。单词应该最少3个字符长,最多10个字符长,并且需要14个单词——不多也不能不少。指示在标签中。另外单词不能是任何其他词的子部分。例如:不能有如’japan’和’japanese’这样两个词,因为前者包含在后者中。
我将简要介绍一下有效性检查。有3个关于最大长度、最小长度和space输入(不允许空格)的即时检查。这通过将我们自定义的处理程序control_keypress添加到单词条目网格的editingcontrolshowingevent中来完成。
private void wordsdatagridview_editingcontrolshowing(object sender, datagridvieweditingcontrolshowingeventargs e) { e.control.keypress -= new keypresseventhandler(control_keypress); e.control.keypress += new keypresseventhandler(control_keypress); }
每当用户输入东西时,处理程序就被调用并检查有效性。完成如下:
textbox tb = sender as textbox; if (e.keychar == (char)keys.enter) { if (tb.text.length <= min_length) // checking length { messagebox.show("words should be at least " + max_length + " characters long."); e.handled = true; return; } } if (tb.text.length >= max_length) // checking length { messagebox.show("word length cannot be more than " + max_length + "."); e.handled = true; return; } if (e.keychar.equals(' ')) // checking space; no space allowed. other invalid characters check can be put here instead of the final check on save button click. { messagebox.show("no space, please."); e.handled = true; return; } e.keychar = char.toupper(e.keychar);
最后,在输入所有单词并且用户选择保存和使用自定义单词之后存在有效性检查。首先它检查是否输入了14个单词。然后它遍历所有的14个单词,并检查它们是否有无效字符。同时它也检查重复的单词。检查成功就把单词添加到列表中。最后,提交另一次迭代,以检查单词是否包含在另一个单词中(例如,不能有如’japan’和’japanese’这样的两个单词,因为前者包含在后者中)。通过下面的代码完成:
public bool checkuserinputvalidity(datagridview wordsdatagridview, list<string> wordsbytheplayer) { if (wordsdatagridview.rows.count != max_words + 1) { messagebox.show("you need to have " + max_words + " words in the list. please add more."); return false; } char[] noletterslist = { ':', ';', '@', '\'', '"', '{', '}', '[', ']', '|', '\\', '<', '>', '?', ',', '.', '/', '`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', '~', '!', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+'}; //' foreach (datagridviewrow itm in wordsdatagridview.rows) { if (itm.cells[0].value == null) continue; if (itm.cells[0].value.tostring().indexofany(noletterslist) >= 0) { messagebox.show("should only contain letters. the word that contains something else other than letters is: '" + itm.cells[0].value.tostring() + "'"); return false; } if (wordsbytheplayer.indexof(itm.cells[0].value.tostring()) != -1) { messagebox.show("can't have duplicate word in the list. the duplicate word is: '" + itm.cells[0].value.tostring() + "'"); return false; } wordsbytheplayer.add(itm.cells[0].value.tostring()); } for (int i = 0; i < wordsbytheplayer.count - 1; i++) // for every word in the list. { string str = wordsbytheplayer[i]; for (int j = i + 1; j < wordsbytheplayer.count; j++) // check existence with every other word starting from the next word if (str.indexof(wordsbytheplayer[j]) != -1) { messagebox.show("can't have a word as a sub-part of another word. such words are: '" + wordsbytheplayer[i] + "' and '" + wordsbytheplayer[j] + "'"); return false; } } return true; }
玩家的列表与现有单词一起保存,然后游戏板与该类别中的那些单词一起被打开。
2)放在网格上:在网格上放置单词
单词通过initializeboard()方法被放置在网格上。我们在字符矩阵(二维字符数组)words_in_board中先放置单词。然后我们在网格中映射这个矩阵。遍历所有的单词。每个单词获取随机方向(水平/垂直/左下/右下)下的随机位置。此时,如果我们可视化的话,单词矩阵看起来会有点像下面这样。
放置通过placethewords()方法完成,获得4个参数——单词方向,单词本身,x坐标和y坐标。这是一个关键方法,所以我要逐个解释这四个方向。
水平方向
对于整个单词,逐个字符地运行循环。首先它检查这个词是否落在网格之外。如果这是真的,那么它返回到调用过程以生成新的随机位置和方向。
然后,它检查当前字符是否可能与网格上的现有字符重叠。如果发生这种情况,那么检查它是否是相同的字符。如果不是相同的字符,那就返回到调用方法,请求另一个随机位置和方向。
在这两个检查之后,如果放置是一种可能,那么就把单词放置在矩阵中,并且通过方法storewordposition()将列表中的位置和方向存储在wordpositions中。
for (int i = 0, j = placementindex_x; i < word.length; i++, j++) // first we check if the word can be placed in the array. for this it needs blanks there. { if (j >= gridsize) return false; // falling outside the grid. hence placement unavailable. if (words_in_board[j, placementindex_y] != '\0') if (words_in_board[j, placementindex_y] != word[i]) // if there is an overlap, then we see if the characters match. if matches, then it can still go there. { placeavailable = false; break; } } if (placeavailable) { // if all the cells are blank, or a non-conflicting overlap is available, then this word can be placed there. so place it. for (int i = 0, j = placementindex_x; i < word.length; i++, j++) words_in_board[j, placementindex_y] = word[i]; storewordposition(word, placementindex_x, placementindex_y, orientationdecision); return true; } break;
垂直/左下/右下方向
相同的逻辑适用于为这3个方向找到单词的良好布局。它们在矩阵位置和边界检查的增量/减量方面不同。
在所有的单词被放置在矩阵中之后,fillinthegaps()方法用随机字母填充矩阵的其余部分。此时窗体打开并触发paint()事件。在这个事件上,我们绘制最终显示为40×40像素矩形的线。然后我们将我们的字符矩阵映射到board上。
pen pen = new pen(color.fromargb(255, 0, 0, 0)); colourcells(colouredrectangles, color.lightblue); if (failedrectangles.count > 0) colourcells(failedrectangles, color.forestgreen); // draw horizontal lines. for (int i = 0; i <= gridsize; i++) e.graphics.drawline(pen, 40, (i + 1) * 40, gridsize * 40 + 40, (i + 1) * 40); // draw vertical lines. for (int i = 0; i <= gridsize; i++) e.graphics.drawline(pen, (i + 1) * 40, 40, (i + 1) * 40, gridsize * 40 + 40); maparraytogameboard();
maparraytogameboard()方法简单地把我们的字符矩阵放在board上。我们使用来自msdn的绘图代码。这遍历矩阵中的所有字符,将它们放置在40×40矩形的中间,边距调整为10像素。
graphics formgraphics = creategraphics(); font drawfont = new font("arial", 16); solidbrush drawbrush = new solidbrush(color.black); string charactertomap; for (int i = 0; i < gridsize; i++) for (int j = 0; j < gridsize; j++) { if (words_in_board[i, j] != '\0') { charactertomap = "" + words_in_board[i, j]; // "" is needed as a means for conversion of character to string. formgraphics.drawstring(charactertomap, drawfont, drawbrush, (i + 1) * 40 + 10, (j + 1) * 40 + 10); } }
单词发现和有效性检查
鼠标点击位置和释放位置存储在点列表中。对鼠标按钮释放事件(gameboard_mouseup())调用checkvalidity()方法。同时,当用户在左键按下的同时拖动鼠标时,我们从起始位置绘制一条线到鼠标指针。这在gameboard_mousemove()事件中完成。
if (points.count > 1) points.pop(); if (points.count > 0) points.push(e.location); // form top = x = distance from top, left = y = distance from left. // however mouse location x = distance from left, y = distance from top. // need an adjustment to exact the location. point topleft = new point(top, left); point drawfrom = new point(topleft.y + points.toarray()[0].x + 10, topleft.x + points.toarray()[0].y + 80); point drawto = new point(topleft.y + points.toarray()[1].x + 10, topleft.x + points.toarray()[1].y + 80); controlpaint.drawreversibleline(drawfrom, drawto, color.black); // draw new line
单词的有效性在checkvalidity()方法中检查。它通过抓取所有的字母来制定单词,字母通过使用鼠标查看相应的字符矩阵来绘制。然后检查是否真的匹配单词列表中的单词。如果匹配,则通过将单元格着色为浅蓝色并使单词列表中的单词变灰来更新单元格。
以下是抓取行开始和结束位置的代码片段。首先它检查行是否落在边界之外。然后它制定单词并且存储矩阵的坐标。类似地,它检查垂直,左下和右下单词,并尝试相应地匹配。如果这真的匹配,那么我们通过addcoordinates()方法将临时矩形存储在我们的colouredrectangles点列表中。
if (points.count == 1) return; // this was a doble click, no dragging, hence return. int startx = points.toarray()[1].x / 40; // retrieve the starting position of the line. int starty = points.toarray()[1].y / 40; int endx = points.toarray()[0].x / 40; // retrieve the ending position of the line. int endy = points.toarray()[0].y / 40; if (startx > gridsize || endx > gridsize || starty > gridsize || endy > gridsize || // boundary checks. startx <= 0 || endx <= 0 || starty <= 0 || endy <= 0) { statuslabel.text = "nope!"; statustimer.start(); return; } stringbuilder thewordintended = new stringbuilder(); list<point> temprectangles = new list<point>(); thewordintended.clear(); if (starty == endy) // horizontal line drawn. for (int i = startx; i <= endx; i++) { thewordintended.append(words_in_board[i - 1, starty - 1].tostring()); temprectangles.add(new point(i * 40, starty * 40)); }
3)计分:对于计分,我们有计分文件。如果缺少,则使用当前分数和类别创建一个。这里,再次,所有的分数被组合在一个大的管道分隔的字符串中,然后该字符串被加密并放入文件。我们有四个实体。
class scoreentity { public string category { get; set; } public string scorer { get; set; } public int score { get; set; } public datetime scoretime { get; set; } .............. ..............
最多允许一个类别14个分数。首先加载分数列表中的所有分数,然后获得当前分类分数的排序子集。在该子集中,检查当前分数是否大于任何可用的分数。如果是,则插入当前分数。之后,检查子集数是否超过14,如果超过了,就消除最后一个。所以最后的得分消失了,列表总是有14个分数。这在checkandsaveiftopscore()方法中完成。
这里,再次,如果有人篡改得分文件,那么它只会开始一个新的得分。不允许篡改。
4)显示隐藏的单词:如果时间用完了,那么游戏用绿色显示单词。首先,获取玩家找不到的单词。可以是这样的
list<string> failedwords = new list<string>(); foreach (string word in word_array) if (words_found.indexof(word) == -1) failedwords.add(word);
然后,遍历这些失败的单词位置并制定相应的失败的矩阵。最后,它通过无效来调用窗体的paint方法。
foreach (string word in failedwords) { wordposition pos = wordpositions.find(p => p.word.equals(word)); if (pos.direction == direction.horizontal) // horizontal word. for (int i = pos.placementindex_x + 1, j = pos.placementindex_y + 1, k = 0; k < pos.word.length; i++, k++) failedrectangles.add(new point(i * 40, j * 40)); else if (pos.direction == direction.vertical) // vertical word. for (int i = pos.placementindex_x + 1, j = pos.placementindex_y + 1, k = 0; k < pos.word.length; j++, k++) failedrectangles.add(new point(i * 40, j * 40)); else if (pos.direction == direction.downleft) // down left word. for (int i = pos.placementindex_y + 1, j = pos.placementindex_x + 1, k = 0; k < pos.word.length; i--, j++, k++) failedrectangles.add(new point(i * 40, j * 40)); else if (pos.direction == direction.downright) // down right word. for (int i = pos.placementindex_x + 1, j = pos.placementindex_y + 1, k = 0; k < pos.word.length; i++, j++, k++) failedrectangles.add(new point(i * 40, j * 40)); } invalidate();
5)作弊码:这是一件小事了。这工作在keyup事件上,这个事件抓取所有的击键到cheatcode变量。实际上,我们合并玩家在游戏窗口上输入的击键,并看看代码是否与我们的cheat_code(mambazamba)匹配。例如,如果玩家按下“m”和“a”,那么我们在cheatcode变量中将它们保持为’ma’(因为,ma仍然匹配cheatcode模式)。类似地,如果它匹配cheat_code的模式,则添加连续变量。然而,一旦它不能匹配模式(例如,’mambi’),则重新开始。
最后,如果匹配,则激活作弊码(将剩余时间提高到完整一天,即86,400秒),并应用惩罚。
cheatcode += e.keycode.tostring().toupper(); if (cheat_code.indexof(cheatcode) == -1) // cheat code didn't match with any part of the cheat code. cheatcode = ("" + e.keycode).toupper(); // hence erase it to start over. else if (cheatcode.equals(cheat_code) && words_found.count != max_words) { clock.timeleft = 86400; // cheat code applied, literally unlimited time. 86400 seconds equal 1 day. scorelabel.text = "score: 0"; statuslabel.text = "cheated! penalty applied!!"; statustimer.start(); currentscore = 0; invalidate();
这里有趣的是,我们必须使用wordslistview的keyup事件而不是窗体。这是因为在加载游戏窗口后,列表框有焦点,而不是窗体。
以上就是如何使用c#来编写的一个完整字谜游戏的示例代码分享的详细内容。
其它类似信息

推荐信息