java 帮助基本的井字游戏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4020757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:25:36  来源:igfitidea点击:

help with basic tic tac toe program

java

提问by Bill

i've never been this frustrated in my life. cant even do the basics here.. just need to make a simple tic tac toe program. i feel so alone in this world right now.. i get the basic idea, but can't put it together logically.

我一生中从未如此沮丧。甚至不能在这里做基础......只需要制作一个简单的井字游戏程序。我现在在这个世界上感到很孤独..我明白了基本的想法,但不能合乎逻辑地把它放在一起。

Class instance variables:

类实例变量:

  • private char[][] board; private char
  • player; // 'X' or 'O'
  • 私人 char[][] 板;私人字符
  • 播放器;// 'X' 或 'O'

Methods:

方法:

  • public TicTacToe()
  • public void print()
  • public boolean play(String s)
  • public boolean won()
  • public boolean stalemate()
  • 公共井字游戏()
  • 公共无效打印()
  • 公共布尔播放(字符串)
  • 公共布尔赢()
  • 公共布尔僵局()

Here's what i've got for code:

这是我的代码:

import java.util.Scanner;

public class Six1
{
    public static void main(String[] args)
    {   
    TicTacToe ttt = new TicTacToe();
    ttt.TicTacToe();
    ttt.print();
    }

    static class TicTacToe
    {
        private char player; // 'X' or 'O'
        private char[][] board;

        // make board
        public TicTacToe()
        {
            // construct board
            board = new char[3][3];

            // initialize elements
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    board[i][j] = ' ' ;
                }
            }
        }

        // print board
        public void print()
        {  
            for ( int i = 0; i < 3; i++)
            {
                System.out.println("  ");   
                for( int j = 0; j < 3; j++)
                {
                    System.out.print(board[i][j] + " ");
                }
                System.out.println("\n------");
            }
        }
    }
}

回答by Brad Mace

You don't have a lot done yet, but what you have seems mostly reasonable. You may be over-complicating things by using an inner class. And you'll need to put something in mainif you want something to happen.

你还没有做很多事情,但你所做的似乎大多是合理的。使用内部类可能会使事情变得过于复杂。main如果你想让某事发生,你就需要投入一些东西。

You can't write the whole program all at once. You can either start at the top and work down to the details, or work on the details and then assemble them into a working whole.

你不能一次编写整个程序。您可以从顶部开始并深入研究细节,也可以处理细节,然后将它们组合成一个工作整体。

Working top-down

自上而下工作

If you're not sure where to start, this can be a good way to get things moving. Write the main body of the code using whatever functions you wish existed. Maybe you'd start with

如果您不确定从哪里开始,这可能是推动事情进展的好方法。使用您希望存在的任何函数编写代码的主体。也许你会开始

public static void main(String[] args) {
    printBoard();

    while (!isWinner()) {
        readMove(); // get move from stdin and mark on board
        printBoard(); // redraw board
    }

    printWinner(); // say who won
}

It's ok that these functions don't exist yet. Once you've got the main level, start implementing these made-up functions, using more made-up functions if necessary. Repeat until you get down to simple functions that you doknow how to implement.

没关系,这些功能尚不存在。获得主关卡后,开始实现这些组合函数,必要时使用更多组合函数。重复操作,直至坐下来简单的功能,你知道如何实现。

If you want to compile your code without implementing every method, you can use throw new UnsupportedOperationException("not implemented");as the body of any methods that need to return values.

如果您想在不实现每个方法的情况下编译代码,您可以将其throw new UnsupportedOperationException("not implemented");用作任何需要返回值的方法的主体。

Working bottom-up

自下而上工作

If you know you'll need certain pieces but aren't sure how they'll fit together, start with this method.

如果您知道需要某些部件但不确定它们如何组合在一起,请从这种方法开始。

You know you'll need some way to ask the user what move they want to make. So create a function that does that and test it on it's own. You know you'll need a way to check if there's a winner. Hardcode some values into board[]and test your isWinner()function. Once you've got some working pieces you can assemble them into larger and larger chunks until you've got a functioning program.

您知道您需要某种方式来询问用户他们想要做什么。因此,创建一个执行此操作的函数并自行对其进行测试。你知道你需要一种方法来检查是否有赢家。将一些值硬编码到board[]您的isWinner()函数中并进行测试。一旦你有了一些工作部件,你就可以将它们组装成越来越大的块,直到你有了一个可以运行的程序。

回答by chiccodoro

You say you don't know what to do in main:

你说你不知道主要做什么:

public static void main(String[] args)
{   
// what the hell do i need here?!?!
// TicTacToe() <--???
// print() <-????
}

Simply calling the methods won't work for two reasons:

由于两个原因,简单地调用这些方法是行不通的:

  1. mainis a static method which runs without an instance of an object. The methods you want to call are instance methods, i.e. you need an object to call them on.

  2. You have defined an inner class. The methods are part of that inner class.

  1. main是一个静态方法,它在没有对象实例的情况下运行。您要调用的方法是实例方法,即您需要一个对象来调用它们。

  2. 您已经定义了一个内部类。方法是该内部类的一部分。

You can solve both of these issues, of course, although as bemace said, the 2. makes your program more complicated than necessary. You could just drop the "class TicTacToe" definition. If you want to keep it, you can create an instance of it like follows:

当然,您可以解决这两个问题,尽管正如 bemace 所说,2. 使您的程序比必要的更复杂。您可以删除“类井字游戏”定义。如果你想保留它,你可以创建一个它的实例,如下所示:

TicTacToe ttt = new TicTacToe();

Edit: Note that as NamshubWriter commented, this won't work unless you declare your inner class as static:

编辑:请注意,正如 NamshubWriter 所评论的,除非您将内部类声明为static

static class TicTacToe

static class TicTacToe

Then you can call methods on it:

然后你可以调用它的方法:

ttt.print();

The TicTacToe()you tried to call is actually a constructor. It is automatically called when you do a new TicTacToe()to create a new object.

TicTacToe()你试图调用实际上是一个构造函数。当您执行 anew TicTacToe()创建新对象时,它会自动调用。

If you put the above two lines in your main method, you should be a step further.

如果你把上面两行放在你的main方法中,你应该更进一步。

回答by NamshubWriter

One thing that is confusing things is the inner/nested class. I'm assuming that the assignment requires you to have a class named Six1. I would make TicTacToea top-level class. So you would have two source files in the same directory:

令人困惑的一件事是内部/嵌套类。我假设作业要求你有一个名为Six1. 我会做TicTacToe一个顶级的班级。因此,您将在同一目录中有两个源文件:

begin Six1.java

开始 Six1.java

public class Six1 {
  public static void main(String[] args)
    TicTacToe ttt = new TicTacToe();
    ttt.play();
  }
}

end Six1.java

结束 Six1.java

begin TicTacToe.java

开始井字游戏.java

public class TicTacToe {
  private char[][] board;
  private char player; // 'X' or 'O'

  /**
   * Constructs a new Tic Tac Toe object
   */
  public TicTacToe() {
    // initialize board
  }

  /**
   * Plays a game
   */
  public void play() {
    // play the game
    print();
  }

  /**
   * Prints the board
   */
  public void print() {
  }
}

end TicTacToe.java

结束井字游戏.java

回答by oadams

Break this problem down a bit and try not to tackle it as a whole.

把这个问题分解一下,尽量不要把它作为一个整体来解决。

For now focus on a method to test for a win. What do you want the function to return in each instances (Draw, unfinished game, player 1 won or player 2 won)?

现在专注于测试获胜的方法。您希望函数在每种情况下返回什么(平局、未完成的游戏、玩家 1 获胜或玩家 2 获胜)?

How will you test for this win?

你将如何测试这场胜利?

Once you have that method the rest should fit into place a lot more easily.

一旦你有了这种方法,其余的应该更容易适应。

回答by dganesh2002

This is what I have come up with. Hope this helps if anybody is still interested!

这是我想出的。如果有人仍然感兴趣,希望这会有所帮助!

public class TicTacToe {
static int SIZE = 3;
static int MAX_MOVES = SIZE * SIZE;
static char[][] matrix = new char[SIZE][SIZE];
static int[][] moveMatrix = new int[][] { { 1, 2, 3 }, { 4, 5, 6 },
        { 7, 8, 9 } };

public static void printState() {
    System.out.println("Current State:");
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++)
            if ((matrix[i][j] == 'x') || (matrix[i][j] == 'o'))
                System.out.print(" " + matrix[i][j]);
            else
                System.out.print(" -");
        System.out.println();
    }
}

public static int enterMove() {
    System.out.println("Enter your move as follows:");
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++)
            if ((matrix[i][j] == 'x') || (matrix[i][j] == 'o'))
                System.out.print(" -");
            else
                System.out.print(" " + moveMatrix[i][j]);
        System.out.println();
    }
    System.out.println("Enter your move :");
    int move = 0;
    move = Integer.parseInt(System.console().readLine());
    return move;
}

public static boolean updateMatrix(int move, char ch) {
    int i = 0;
    int j = 0;
    boolean status;
    switch (move) {
    case 1:
        break;
    case 2:
        i = 0;
        j = 1;
        break;
    case 3:
        i = 0;
        j = 2;
        break;
    case 4:
        i = 1;
        j = 0;
        break;
    case 5:
        i = 1;
        j = 1;
        break;
    case 6:
        i = 1;
        j = 2;
        break;
    case 7:
        i = 2;
        j = 0;
        break;
    case 8:
        i = 2;
        j = 1;
        break;
    case 9:
        i = 2;
        j = 2;
        break;
    default:
        System.out.println("Invalid entry");
        status = false;
        break;
    }
    if (moveMatrix[i][j] == -1) {
        System.out
                .println("Entry already marked,please re-enter your move.");
        status = false;
    } else {
        matrix[i][j] = ch;
        moveMatrix[i][j] = -1;
        status = true;
    }
    return status;
}

public static boolean isGameOver() {
    boolean status = false;
    if ((matrix[0][0] == matrix[1][1]) && (matrix[1][1] == matrix[2][2])
            && ((matrix[1][1] == 'x') || (matrix[1][1]) == 'o'))
        status = true;
    else if ((matrix[2][0] == matrix[1][1])
            && (matrix[1][1] == matrix[0][2])
            && ((matrix[1][1] == 'x') || (matrix[1][1]) == 'o'))
        status = true;
    for (int i = 0; i < SIZE; i++)
        if ((matrix[i][0] == matrix[i][1])
                && (matrix[i][1] == matrix[i][2])
                && ((matrix[i][1] == 'x') || (matrix[i][1]) == 'o'))
            status = true;
        else if ((matrix[0][i] == matrix[1][i])
                && (matrix[1][i] == matrix[2][i])
                && ((matrix[1][i] == 'x') || (matrix[1][i]) == 'o'))
            status = true;
    return status;
}

public static void main(String[] args) {
    char ch;
    int k = 0;
    int player;
    do {
        player = k % 2 + 1;
        k++;
        if (player == 1)
            ch = 'x';
        else
            ch = 'o';
        printState();
        System.out.println("Player" + player + " [" + ch + "]:");
        if (!updateMatrix(enterMove(), ch))
            k--;
    } while ((!isGameOver()) && (k < MAX_MOVES));
    printState();
    if (isGameOver())
        System.out.println("Game Over. Player" + player + " [" + ch
                + "] wins!");
    else
        System.out.println("Game Tied. No winner!");
    }
}