[java]代码库
package day04;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class Gobang
{
BufferedImage table;
BufferedImage black;
BufferedImage white;
BufferedImage selected;
private static int BOARD_SIZE = 15;
private final int TABLE_WIDTH = 535;
private final int TABLE_HETGHT = 536;
private final int RATE = TABLE_WIDTH / BOARD_SIZE;
private final int X_OFFSET = 5;
private final int Y_OFFSET = 6;
private String[][] board = new String[BOARD_SIZE][BOARD_SIZE];
JFrame f = new JFrame("五子棋游戏");
ChessBoard chessBoard = new ChessBoard();
private int selectedX = -1;
private int selectedY = -1;
public void init()throws Exception
{
table = ImageIO.read(new File("image/board.jpg"));
black = ImageIO.read(new File("image/black.gif"));
white = ImageIO.read(new File("image/white.gif"));
selected = ImageIO.read(new File("image/selected.gif"));
for (int i = 0 ; i < BOARD_SIZE ; i++)
{
for ( int j = 0 ; j < BOARD_SIZE ; j++)
{
board[i][j] = "╋";
}
}
chessBoard.setPreferredSize(new Dimension(
TABLE_WIDTH , TABLE_HETGHT));
chessBoard.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
int xPos = (int)((e.getX() - X_OFFSET) / RATE);
int yPos = (int)((e.getY() - Y_OFFSET ) / RATE);
board[xPos][yPos] = "●";
chessBoard.repaint();
}
public void mouseExited(MouseEvent e)
{
selectedX = -1;
selectedY = -1;
chessBoard.repaint();
}
});
chessBoard.addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseMoved(MouseEvent e)
{
selectedX = (e.getX() - X_OFFSET) / RATE;
selectedY = (e.getY() - Y_OFFSET) / RATE;
chessBoard.repaint();
}
});
f.add(chessBoard);
f.pack();
f.setVisible(true);
}
public static void main(String[] args)throws Exception
{
Gobang gb = new Gobang();
gb.init();
}
class ChessBoard extends JPanel
{
public void paint(Graphics g)
{
g.drawImage(table , 0 , 0 , null);
if (selectedX >= 0 && selectedY >= 0)
g.drawImage(selected , selectedX * RATE + X_OFFSET ,
selectedY * RATE + Y_OFFSET, null);
for (int i = 0 ; i < BOARD_SIZE ; i++)
{
for ( int j = 0 ; j < BOARD_SIZE ; j++)
{
if (board[i][j].equals("●"))
{
g.drawImage(black , i * RATE + X_OFFSET
, j * RATE + Y_OFFSET, null);
}
if (board[i][j].equals("○"))
{
g.drawImage(white, i * RATE + X_OFFSET
, j * RATE + Y_OFFSET, null);
}
}
}
}
}
}
初级程序员
by: 代码王 发表于:2018-01-10 18:37:46 顶(0) | 踩(0) 回复
回复评论