Tic Tac Toe Java游戏

时间:2015-04-08 00:04:42

标签: java tic-tac-toe

我在java中制作了一个Tic Tac Toe游戏。我已经完成了代码,但我不确定如何查看对角线中是否有赢家。我试图提出的是:

win[x] += (board[0][2] + board[1][1] + board[2][0]);
x++;
win[x] += (board[0][0] + board[1][1] + board[2][2]);

然而它似乎没有起作用。非常感谢帮助解决这个问题!

Tic Tac课程

import java.util.Scanner;
import java.util.Random;

public class TicTac
{
    public static void main(String[]args)
    {
        Scanner reader = new Scanner(System.in);
        TTTBoard board = new TTTBoard();

        System.out.println(board);

        Random gen = new Random();
        char player;
        if(gen.nextInt(2) == 1)
        {
            player = 'O';
        }
        else
        {
            player = 'X';
        }
        System.out.println("Would you like to play against the computer?");
        String computer = reader.nextLine();

        while(board.getWinner() == '-' && !board.full())
        {
            int row = 0;
            int column = 0;
            boolean success = false;
            System.out.println(player + "'s turn.");

            if(computer.equals("No")||player=='X')
            {
                System.out.print("Enter the row and column[1-3, space, 1-3]");

                row = reader.nextInt();
                column = reader.nextInt();
                success = board.placeXorO(player, row, column);
            }
            else
            {
                while(!success)
                {
                    row = gen.nextInt(3) +1;
                    column = gen.nextInt(3) +1;
                    success = board.placeXorO(player, row, column);
                }
            }
            if(!success)
            {
                System.out.println("Error: cell already occupied");
            }
            else
            {
                System.out.println(board);
                if(player == 'X')
                {
                    player = 'O';
                }
                else
                {
                    player = 'X';
                }
            }
        }
        char winner = board.getWinner();
        if(winner != '-')
        {
            System.out.println(winner + "'s wins!");
        }
        else
        {
            System.out.println("It's a draw!");
        }

    }
}

TTTBoard Class

public class TTTBoard{
    private char[][]board;

    public TTTBoard()
    {
        board = new char[3][3];
        reset();
    }

    public void reset()
    {
        for(int row = 0; row < 3; row++)
        {
            for(int col = 0; col < 3; col++)
            {
                board[row][col]= '-';
            }
        }
    }

    public String toString()
    {
        String result = "\n";
        for(int row = 0; row < 3; row++)
        {
            for (int col = 0; col < 3; col++)
            {
                result += board[row][col] + " ";
            }
            result += "\n";
        }
        return result;
    }

    public boolean placeXorO(char player, int row, int col)
    {
        if(board[row-1][col-1]=='-')
        {
            board[row-1][col-1] = player;
            return true;
        }
        else
        {
            return false;
        }
    }

    public boolean full()
    {
        for(int row = 0; row < 3; row++)
        {
            for(int col = 0; col < 3; col++)
            {
                if(board[row][col] == '-')
                {
                    return false;
                }
            }
        }
        return true;
    }

    public char getWinner()
    {
        String[]win = new String[8];
        int x =0;
        for(int y =0; y < 8; y++)
        {
            win[y] = "";
        }

        for(int row = 0; row <3; row++)
        {
            for (int col = 0; col < 3; col++)
            {
                win[x] += board[row][col];
            }
            x++;
        }

        for(int col = 0; col <3; col++)
        {
            for (int row = 0; row < 3; row++)
            {
                win[x] += board[row][col];
            }
            x++;
        }

        win[x] += (board[0][2] + board[1][1] + board[2][0]);
        x++;
        win[x] += (board[0][0] + board[1][1] + board[2][2]);

        char winner = '-';
        for(int i = 0; i < 8; i++)
        {
            if (win[i].equals("XXX"))
            {
                winner = 'X';
            }
            if(win[i].equals("OOO"))
            {
                winner = 'O';
            }
        }
        return winner;
    }
}

2 个答案:

答案 0 :(得分:1)

在Java中,由于char是基本类型,因此它被存储为数字。因此,当你执行('O' + 'O' + 'O')时,实际上最终会将o的ascii值加在一起3次,结果只会产生一个字符。要解决此问题,您可以强制Java将+运算符视为连接而不是添加:("" + 'O' + 'O' + 'O')

答案 1 :(得分:-1)

这段代码最容易! 这有赢得逻辑,损失逻辑,绘制逻辑以及分数,重置和新游戏!

package com.pervacio.ex;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;


class TicTacToe implements ActionListener {

    JCheckBox cb1= new JCheckBox("vs friend");
    JFrame jf= new JFrame("TicTacToe by Anand");
    JButton jb[][]= new JButton[3][3];
    JButton reset= new JButton();
    JLabel xjl= new JLabel();
    JLabel ojl= new JLabel();
    JLabel xwin= new JLabel();
    JLabel owin= new JLabel();
    JMenu menu1, menu2;
    JMenuBar bar;
    JMenuItem i1,i2,i3;
    JTextArea tf;
    int corX=0, corY=0;
    int flag=0;
    int xScore=0;
    int oScore=0;
    int comp=0;
    public void selectGame() {
        jf.setLayout(null);
        jf.add(cb1);
        cb1.setBounds(100,50,100,100);
        jf.add(cb1);
        cb1.setBounds(100, 150, 100, 100);
        cb1.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                jf.remove(cb1);
                setUpFrame();

            }
        });

        jf.setSize(318, 510);
        jf.setVisible(true);

    }



    public void setUpFrame() {
        jf.setSize(500, 500);
        for(int i=0; i< 3; i++) {
            for(int j=0; j<3 ;j++) {
                jb[i][j]= new JButton(" ");
                jb[i][j].setSize(100, 100);
                jb[i][j].setBounds(corX, corY, 100, 100);
                jf.add(jb[i][j]);
                jb[i][j].addActionListener(this);


                corX=corX+100;
            }

            corX=0;
            corY=corY+100;
        }
        reset.setBounds(100, 350, 100, 50);
        xjl.setBounds(0,400,80,80);
        ojl.setBounds(200,400,80,80);
        xwin.setBounds(80,400,200,80);
        owin.setBounds(280,400, 200, 80);
        jf.setLayout(null);
        jf.setSize(318, 510);
        jf.setVisible(true);
        jf.add(ojl);
        jf.add(xjl);
        jf.add(xwin);
        jf.add(owin);
        reset.setText("Reset");
        reset.setBackground(Color.GREEN);
        bar= new JMenuBar();
        menu1= new JMenu("Game");
        menu2= new JMenu("Help");
        i1= new JMenuItem("New Game");
        i1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(e.getSource()==i1) {
                    for(int i=0; i<3 ;i++) {
                        for(int j=0;j<3;j++) {
                            jb[i][j].setText(" ");
                        }
                    }
                    xwin.setText(" ");
                    owin.setText(" ");
                    xScore=0; oScore=0;
                    flag=0;
                }

            }
        });
        i2=new JMenuItem("Exit");
        i2.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(e.getSource()==i2) {
                    jf.dispose();
                }


            }
        });
        i3=new JMenuItem("Help");
        i3.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
            if(e.getSource()==i3) {
                help();
            }

            }
        });
        menu1.add(i1);
        menu1.add(i2);
        menu2.add(i3);

        bar.add(menu1);
        bar.add(menu2);
        jf.setJMenuBar(bar);

        reset.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                if(e.getSource()==reset) {
                    for(int i=0; i<3 ;i++) {
                        for(int j=0;j<3;j++) {
                            jb[i][j].setText(" ");
                        }
                    }
                    flag=0;
                }
            }
        });
        jf.add(reset);
        xjl.setText("XWINS: ");
        ojl.setText("O WINS:");
        String str= "THIS GAME IS DEVELOPED BY ANAND, THIS IS SIMPLE TIC TAC TOE \n 1)THERE ARE TWO PLAYERS X AND O"
                + "\n 2)IF WE PRESS THE BUTTON, WE GET X OR O DEPENDING ON PREVIOUS ACTION"
                + "\n 3) IF X IS PRINTED 3 TIMES IN A ROW IN ANY DIRECTION, X IS WINNER, SAME FOR 0";
        tf= new JTextArea();
        tf.setText(str);
        tf.setEditable(false);
        jf.add(tf);
        jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
    }

    public static void main(String args[]) {
        TicTacToe tt= new TicTacToe();
        tt.selectGame();


    }

    public void help() {
        JOptionPane.showMessageDialog(jf, tf);
    }
    public void winLogic() {


        boolean xwc1= jb[0][0].getText().equals("X")&&jb[1][1].getText().equals("X")&&jb[2][2].getText().equals("X")
                ?true:false;
        boolean xwc2=jb[0][2].getText().equals("X")&&jb[1][1].getText().equals("X")&&jb[2][0].getText().equals("X")
                ?true:false;
        boolean xwc3=jb[0][0].getText().equals("X")&&jb[1][0].getText().equals("X")&&jb[2][0].getText().equals("X")
                ?true:false;
        boolean xwc4=jb[0][0].getText().equals("X")&&jb[0][1].getText().equals("X")&&jb[0][2].getText().equals("X")
                ?true:false;
        boolean xwc5=jb[0][1].getText().equals("X")&&jb[1][1].getText().equals("X")&&jb[2][1].getText().equals("X")
                ?true:false;
        boolean xwc6=jb[0][2].getText().equals("X")&&jb[1][2].getText().equals("X")&&jb[2][2].getText().equals("X")
                ?true:false;
        boolean xwc7= jb[1][0].getText().equals("X")&&jb[1][1].getText().equals("X")&&jb[1][2].getText().equals("X")
                ?true:false;
        boolean xwc8=jb[2][0].getText().equals("X")&&jb[2][1].getText().equals("X")&&jb[2][2].getText().equals("X")
                ?true:false;


        boolean owc1= jb[0][0].getText().equals("O")&&jb[1][1].getText().equals("O")&&jb[2][2].getText().equals("O")
                ?true:false;
        boolean owc2=jb[0][2].getText().equals("O")&&jb[1][1].getText().equals("O")&&jb[2][0].getText().equals("O")
                ?true:false;
        boolean owc3=jb[0][0].getText().equals("O")&&jb[1][0].getText().equals("O")&&jb[2][0].getText().equals("O")
                ?true:false;
        boolean owc4=jb[0][0].getText().equals("O")&&jb[0][1].getText().equals("O")&&jb[0][2].getText().equals("O")
                ?true:false;
        boolean owc5=jb[0][1].getText().equals("O")&&jb[1][1].getText().equals("O")&&jb[2][1].getText().equals("O")
                ?true:false;
        boolean owc6=jb[0][2].getText().equals("O")&&jb[1][2].getText().equals("O")&&jb[2][2].getText().equals("O")
                ?true:false;
        boolean owc7= jb[1][0].getText().equals("O")&&jb[1][1].getText().equals("O")&&jb[1][2].getText().equals("O")
                ?true:false;
        boolean owc8=jb[2][0].getText().equals("O")&&jb[2][1].getText().equals("O")&&jb[2][2].getText().equals("O")
                ?true:false;
         boolean xw=xwc1||xwc2||xwc3||xwc4||xwc5||xwc6||xwc7||xwc8;
         boolean ow=owc1||owc2||owc3||owc4||owc5||owc6||owc7||owc8;
        if(flag!=2) {
         if(xwc1||xwc2||xwc3||xwc4||xwc5||xwc6||xwc7||xwc8) {
            JOptionPane.showMessageDialog(jf, "X WON...");
            xScore++;
            xwin.setText(""+xScore);
            flag=2;

        }
        else if(owc1||owc2||owc3||owc4||owc5||owc6||owc7||owc8) {
            JOptionPane.showMessageDialog(jf, "O WON...");
            oScore++;
            owin.setText(""+oScore);
            flag=2;
        } 
        }
        int num=0; 
        int X= xw?0:1;
        int O= ow?0:1;
        for(int i=0; i<3;i ++) {
            for(int j=0;j<3;j++) {
                if(!jb[i][j].getText().equals(" "))
                    num++;
            }
        }
        if((num==9)&&((X==1)&&(O==1))) {
            JOptionPane.showMessageDialog(jf, "DRAW");
            flag=2;

        }
    }
    @Override
    public void actionPerformed(ActionEvent e) {


            for(int i=0; i<3; i++) {
                for(int j=0 ;j<3; j++) {


                    if(e.getSource()==jb[i][j]) {
                        if(jb[i][j].getText().equals(" ")) {
                            if(flag==0) {
                                jb[i][j].setText("X");
                                flag=1;

                            }
                            else if(flag==1){
                                jb[i][j].setText("O");
                                flag=0;
                            }
                            else if(flag==2) {
                                JOptionPane.showMessageDialog(jf, "This game is already over, please click reset!");
                            }
                        } else {
                            ;
                        }
                    }
                }

            }
            winLogic(); 
        }


}