如何判断游戏结束,在井字棋? [英] How to determine game end, in tic-tac-toe?
问题描述
我开发井字棋游戏,我需要算法来检查时,游戏结束(谁赢)。 在3×3的比赛,我会检查每一个可能的双赢的局面(有8功能)。但是,在7×7(4所需的迹象在一排或collumn,或对角线)是一个很大的可能取胜的模式。
I'm developing tic-tac-toe game, and I need algorithm to check when game ends(and who win). In 3x3 game I would check each possible win-situation(there is 8 capabilities). But in 7x7(needed 4 signs in a row or collumn, or diagonal)is a lot of possible win patterns.
推荐答案
在一个非常基本的方法是看运行在所有方向的每一个细胞,这里有一种方法则永远只能检查单个单元格行一次。 A线是一个行,列或对角线都不可能赢,就像在拉斯维加斯的老虎机:)
While a very basic approach is to look at runs in all the directions from every single cell, here are an approach then only ever checks a cell in a single "line" once. A "line" is a row, column, or diagonal that can possibly win, like in a Vegas slot machine :)
- 对于每个线,移动的启动的是行的和;
- 设置计数器为0。
- 对于每个单元中的行(穿越,才能行):
- 如果该细胞是P1和计数器> = 0,添加一个反击
- 如果计数器= 4,则P1胜。
- 如果该细胞是P1和计数器> = 0,添加一个反击
- For each "line", move to start of that "line" and;
- Set counter to 0.
- For each cell in the "line" (traversing the line in order):
- If the cell is P1 and counter is >= 0, add one to counter
- If counter = 4 then P1 wins.
- If the cell is P1 and counter is >= 0, add one to counter
- 如果计数器= -4然后P2胜
重要编辑::如果单元格中包含既不P1或P2,重置计数器为0(DOH!)。我忽略这个简单,但需要一步。否则,11-11将被算作一场胜利。
Important If the cell contains neither P1 or P2, reset counter to 0 (doh!). I omitted this trivial but required step. Otherwise "11-11" would be counted as a win.
的线可以被穿越给定起点和行/列每次迭代偏移量(例如开始于(0,0)和提前(1,1),用于最长对角线从NW至SE)。对角线长度与小于4可避免被检查,当然完全。
The "lines" can be traversed given a starting point and row/column offset per iteration (e.g. start at (0,0) and advance (1,1) for longest diagonal from NW to SE). Diagonals with lengths less than 4 can avoid being checked entirely, of course.
快乐编码。
这篇关于如何判断游戏结束,在井字棋?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!