当有三个Button
具有相同的符号时,是否可以在tictactoe中通过Button
生成一条直线,例如
如果是这样,怎么办呢?
答案 0 :(得分:2)
可以做的一种方法是使用一些boolean
逻辑和一个自定义JButton
类以及一些自定义绘画。例如,在下面的示例中,有一个leftRight
标志。如果有一个水平的tic tac toe,leftRight
标志将被抬起,导致该行在tic tac toe中的每个按钮中绘制
原谅我的tic tac toe编程逻辑,它不是最终的游戏产品。它只给出了O的顶行tic tac toe的一个例子。但我相信你可以找出其他类型的tic tac toe的逻辑。例如,对于对角线,您可以使用leftDiag
标记,如果引发,则会绘制drawLine(0, 0, getWidth(), getHeight())
玩它。享受!
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class TTTButtons {
ImageIcon oooIcon;
MyButton[][] buttons = new MyButton[3][3];
JPanel gamePanel;
public TTTButtons() {
oooIcon = new ImageIcon(getClass().getResource("/resources/ooooo.png"));
gamePanel = createGamePanel();
JFrame frame = new JFrame("TicTacToe");
frame.add(gamePanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createGamePanel() {
JPanel panel = new JPanel(new GridLayout(3, 3));
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
buttons[i][j] = new MyButton(oooIcon);
panel.add(buttons[i][j]);
}
}
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TTTButtons();
}
});
}
public class MyButton extends JButton {
Image oooImage;
boolean leftRight = false;
boolean clicked = false;
boolean ooo = false;
boolean tictactoe = false;
public MyButton(ImageIcon oooImage) {
this.oooImage = oooImage.getImage();
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clicked = true;
ooo = true;
if (buttons[0][0].clicked && buttons[0][1].clicked && buttons[0][2].clicked) {
for (int i = 0; i < 3; i++) {
buttons[0][i].leftRight = true;
buttons[0][i].tictactoe = true;
buttons[0][i].repaint();
}
return;
}
repaint();
}
});
setBorder(new LineBorder(Color.BLACK, 1));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (clicked) {
if (ooo) {
g.drawImage(oooImage, 0, 0, getWidth(), getHeight(), this);
}
} else {
g.setColor(Color.GRAY);
g.fillRect(0, 0, getWidth(), getHeight());
}
if (tictactoe) {
if (leftRight) {
g.drawLine(0, (int) (getHeight() / 2), getWidth(), (int) (getHeight() / 2));
}
}
}
@Override
public Dimension getPreferredSize() {
return oooImage == null ? new Dimension(100, 100)
: new Dimension(oooImage.getWidth(this), oooImage.getHeight(this));
}
}
}
答案 1 :(得分:0)
如果您使用的是JFrame,那么很容易。试试这个:
if(shape1==shape2 && shape2==shape3){
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
Line2D lin = new Line2D.Float(100, 100, 250, 260);
g2.draw(lin);
}
}
当然坐标取决于你的形状。