簡體   English   中英

Java 中的井字游戲

[英]Tic Tac Toe game in Java

好吧伙計們......我又被難住了。 我設法讓游戲運行。 但是,現在我要嘗試編寫獲勝條件的代碼了。 我正在考慮為每個按鈕使用一個布爾數組,但無法弄清楚如何將按鈕 [] 交叉引用到 gameSquares[] 以將 gameSquares[] 的元素設置為真/假標志。

任何指針? (代碼復制如下)。

** 其他一些我覺得值得一提的有趣錯誤:1) 啟動和重置似乎無法正常工作 2) 當計算機在無效方塊中嘗試多次嘗試時,方塊似乎會跳動或跳舞。 這真的很奇怪。

package tictactoegame;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

class TicTacToeBoard extends JFrame implements ActionListener
{
    JButton[] buttons = new JButton[10];
    boolean player1 = false, player2 = false;
    boolean[] gameSquares = {false, false, false, 
                             false, false, false, 
                             false, false, false}; 
    boolean startPlayer = false;
    int turnCount = 0;

    public TicTacToeBoard()
    {
        JFrame gameWindow = new JFrame();
        gameWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
        gameWindow.setSize(300,400);
        gameWindow.setVisible(true);

        JPanel gamePanel = new JPanel();
        gamePanel.setSize(300,400);
        GridLayout grid = new GridLayout(4,3);
        gamePanel.setLayout(grid);



        for(int i = 0; i < 9; i++)
        {
            buttons[i] = new JButton("");
            buttons[i].addActionListener(this);

            gamePanel.add(buttons[i]);
        }

        JButton startButton = new JButton("Start");
        startButton.addActionListener(this);
        JButton resetButton = new JButton("Reset");
        resetButton.addActionListener(this);
        JButton helpButton = new JButton("Help");
        helpButton.addActionListener(this);

        gamePanel.add(startButton);
        gamePanel.add(helpButton);        
        gamePanel.add(resetButton);

        gameWindow.add(gamePanel);
        gameWindow.pack();

        while (turnCount < 9)
        {
            gamePlay();
        }
    }

    public void gamePlay()
    {
        while(!startPlayer)
        {
            int random = randomGenerator();

            if (random%2 == 0)
            {
                player1 = true;
                JOptionPane.showMessageDialog(null, "Player is first.");
                startPlayer = true;
            }
            else if (random%2 == 1)
            {
                player2 = true;
                JOptionPane.showMessageDialog(null, "Computer is first.");
                startPlayer = true;
            }
        }

        if (player2)
        {
            int index;

            Random randomGenerator = new Random();

            index = randomGenerator.nextInt(9);

            buttons[index].doClick();

            player2 = false;
            player1 = true;

        }

    }

    public int randomGenerator()
    {
        int randomNum;

        Random randomGenerator = new Random();

        randomNum = randomGenerator.nextInt(100);

        return randomNum;
    }

    @Override
    public void actionPerformed(ActionEvent e) 
    {
        Object source = e.getSource();


        if(source instanceof JButton)
        {
            JButton button = (JButton) source;

            if (button.getText() == "Start")
            {
                startPlayer = false;
                player1 = false;
                player2 = false;
                gamePlay();
            }
            else if (button.getText() == "Reset")
            {
                for(int i = 0; i < 9; i++)
                {
                    buttons[i].setText("");
                }
                startPlayer = false;
                player1 = false;
                player2 = false;
                gamePlay();
            }
            else if (button.getText() == "Help")
            {
                JOptionPane.showMessageDialog(null, "Help:\n\n" +
                        "How to play-\n" + 
                        "Select an empty square. The square will be filled with"
                       + "with your symbole, either X or O.\n" + 
                       "The game is won when either player gets three X's or"
                 + "O's in a row horizontally,\n vertically, or diagonally.");
            }
            if (button.getText() == "" && player1)
            {
                button.setText("X");
                turnCount += 1;
                player1 = false;
                player2 = true;
            }
            else if (button.getText() == "" && player2)
            {
                button.setText("O");
                turnCount+=1;
                player2 = false;
                player1 = true;
            }
            else if (button.getText() == "X" || button.getText() == "O")
            {
                if(player2 == true)
                {
                    gamePlay();
                }
                else
                {
                    JOptionPane.showMessageDialog(null, "Invalid choice. Select" 
                     + " another square.");
                }
            }
        }
    }
}

使用小程序檢查此井字游戲完整代碼...:

    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    /*
     <applet code="TicTacToe.class" width="300" height="300">
     </applet>
     */
public class TicTacToe extends Applet implements ActionListener {
Button[] btnarray = new Button[9];
private final static String PLAYER1 = "PLAYER1";
private final static String PLAYER2 = "PLAYER2";
private static String CURRENT_PLAYER = null;
Label lbl = new Label();

public void init() {
    CURRENT_PLAYER = PLAYER1;
    lbl.setText(CURRENT_PLAYER + " Turn!");
    setLayout(new BorderLayout());
    Panel p = new Panel();
    GridLayout gl = new GridLayout(3, 3);
    p.setLayout(gl);
    setBackground(Color.BLACK);
    setForeground(Color.WHITE);
    setSize(300, 300);
    Font myFont = new Font("TimesRoman", Font.BOLD, 80);
    for (int i = 0; i < 9; i++) {
        btnarray[i] = new Button(null);
        btnarray[i].setActionCommand("" + i);
        btnarray[i].addActionListener(this);
        btnarray[i].setFont(myFont);
        btnarray[i].setBackground(Color.white);
        p.add(btnarray[i]);
    }
    add(BorderLayout.CENTER, p);
    add(BorderLayout.NORTH, lbl);
    add(BorderLayout.SOUTH, new Label("Player 1 => X , Player 2 => 0"));

}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    int index = Integer.parseInt(e.getActionCommand());
    btnarray[index].disable();
    if (CURRENT_PLAYER == PLAYER1) {
        btnarray[index].setLabel("X");
        CURRENT_PLAYER = PLAYER2;

    } else {
        btnarray[index].setLabel("0");
        CURRENT_PLAYER = PLAYER1;
    }
    lbl.setText(CURRENT_PLAYER + " Turn!");
    check();
}

void check() {
    String[] pattern = new String[8];
    pattern[0] = btnarray[0].getLabel() + btnarray[1].getLabel()
            + btnarray[2].getLabel();
    pattern[1] = btnarray[3].getLabel() + btnarray[4].getLabel()
            + btnarray[5].getLabel();
    pattern[2] = btnarray[6].getLabel() + btnarray[7].getLabel()
            + btnarray[8].getLabel();
    pattern[3] = btnarray[0].getLabel() + btnarray[3].getLabel()
            + btnarray[6].getLabel();
    pattern[4] = btnarray[1].getLabel() + btnarray[4].getLabel()
            + btnarray[7].getLabel();
    pattern[5] = btnarray[2].getLabel() + btnarray[5].getLabel()
            + btnarray[8].getLabel();
    pattern[6] = btnarray[0].getLabel() + btnarray[4].getLabel()
            + btnarray[8].getLabel();
    pattern[7] = btnarray[2].getLabel() + btnarray[4].getLabel()
            + btnarray[6].getLabel();
    int j = 0;

    while (j < 8) {
        char[] array = pattern[j].toCharArray();
        if (array[0] == 'X' && array[1] == 'X' && array[2] == 'X') {
            lbl.setText(PLAYER1 + " Wins!");
        } else if (array[0] == '0' && array[1] == '0' && array[2] == '0') {
            lbl.setText(PLAYER2 + " Wins!");
        }
        j++;
    }

}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM