简体   繁体   English

使用1维阵列问题的Tic Tac Toe程序

[英]Tic Tac Toe program using 1 dimensional array issue

Hi I created a program that has one dimensional array that can hold 9 elements and enum mark(O,X). 嗨我创建了一个程序,它具有一维数组,可以容纳9个元素和枚举标记(O,X)。 this encoding scheme sets the first move to x and then o in the array etc... My problem is I want to make my getWinner() method that calculates the winner more efficient. 这个编码方案设置第一个移动到x然后在数组等中o ...我的问题是我想让我的getWinner()方法更有效地计算胜利者。 currently I just have a bunch of if else statements, how can I reduce the lines of code and make it in a more "smarter way". 目前我只有一堆if else语句,如何减少代码行并使其更“智能”。

Well, for starters, it'd be better to stop the execution of getWinner() as soon as it finds a Tic-Tac-Toe, instead of continuing searching even after it's been found. 好吧,对于初学者来说,最好在找到Tic-Tac-Toe后立即停止执行getWinner(),而不是在找到之后继续搜索。 You can do that by, within each of your if statements, including a return result; 您可以在每个if语句中执行此操作,包括return result; statement at the end. 最后的声明。

But anyway, here's an idea for efficiency: every time a player makes a move (X, for example), only check the other squares it could make a Tic-Tac-Toe with for other X's. 但无论如何,这是一个效率的想法:每次玩家进行移动(例如X)时,只检查其他方格,它可以为其他X制作Tic-Tac-Toe。 You'll have to do some thinking about how to implement the logic, but it would keep you from having to check every single set of 3 squares on the board, every time. 您将不得不考虑如何实现逻辑,但它会让您不必每次都检查电路板上每组3个方块。

You could very easily group the vertical and horizontal checks into a pair of loops. 您可以非常轻松地将垂直和水平检查分组为一对循环。 For example: 例如:

// Horizontal test
for (int i = 0; i < 3; i++) {
    if (getMark(i, 0) == getMark(i, 1)
        && getMark(i, 1) == getMark(i, 2) && getMark(i, 2) != null)
        result = getMark(i, 0)

// ...

// Vertical test
for (int i = 0; i < 3; i++) {
    if (getMark(0, i) == getMark(1, i)
        && getMark(1, i) == getMark(2, i) && getMark(2, i) != null)
        result = getMark(0, i)

This in and of itself takes six of your if statements and reduces them to two. 这本身就占用了你的六个if语句并将它们减少到两个。

I found a page that implements this game. 我找到了一个实现这个游戏的页面。 http://www.lightbluelab.com/enjoy/ai/tic-tac-toe/ I don't know the algorithm it uses, but I think it maybe a reference for you because it is written in JavaScript and the source codes should be available. http://www.lightbluelab.com/enjoy/ai/tic-tac-toe/我不知道它使用的算法,但我认为它可能是一个参考,因为它是用JavaScript编写的,源代码应该是能得到的。

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

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