【发布时间】:2017-01-24 18:10:05
【问题描述】:
为了这个学期的独立学习,我制作了 Oh-Mok 游戏,它基本上是井字游戏,但在 15 x 15 棋盘上。我使用具有开关功能的二维按钮阵列来加载黑色图片、白色图片和 null(这只是未点击的按钮)。
我已经完成了一切,但现在我想实现一个方法,当用户获胜时会显示一条消息。 (人们与其他人对抗,而不是计算机)。问题是,我不知道如何根据点击次数不断更新。我将在下面附上主要的游戏类和按钮类。 (我在加载开始屏幕的主方法中调用新开始)。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class OhMok
{
//declaring variables
JPanel mainPanel = new JPanel();
WhiteBlackButton board[][] = new WhiteBlackButton[15][15];
//constructor
public OhMok()
{
//creating frame
JFrame mainFrame = new JFrame("Oh-Mok v1.2 by Adam Romano");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(new Dimension(600,600));
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
mainPanel.setLayout(new GridLayout(15,15));
//adding buttons to frame
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[i].length; j++ )
{
board[i][j] = new WhiteBlackButton();
board[i][j].setBackground(new Color(238,221,130));
mainPanel.add(board[i][j]);
}
}
mainFrame.add(mainPanel);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Start();
}
});
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class WhiteBlackButton extends JButton implements ActionListener
{
//setting variables
ImageIcon white, black;
int value = 0;
//constructors
public WhiteBlackButton()
{
//instantiating Image Icons with black/white
white = new ImageIcon(this.getClass().getResource("white.png"));
black = new ImageIcon(this.getClass().getResource("black.png"));
this.addActionListener(this);
}
//on click-event handling
public void actionPerformed(ActionEvent e)
{
value++;
value %= 3;
//switching between black, white, nothing
switch(value)
{
case 0:
setIcon(null);
break;
case 1:
setIcon(white);
break;
case 2:
setIcon(black);
break;
}
}
}
【问题讨论】:
-
看看下面我的解决方案。
-
“我的问题是我不知道如何检查二维数组中的水平、垂直和对角线获胜。”:那么你还没有“完成所有事情”跨度>
标签: java arrays algorithm swing