Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.BorderLayout;
- import java.awt.Color;
- import java.awt.Container;
- import java.awt.GridLayout;
- import java.awt.event.MouseAdapter;
- import java.awt.event.MouseEvent;
- import javax.swing.Icon;
- import javax.swing.ImageIcon;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- public class KonjicevSkok extends JFrame {
- private ChessField[][] board = new ChessField[8][8];
- private Icon knightIcon = new ImageIcon("konjic.png");
- private ChessField knight;
- private class ChessField extends JPanel {
- private JLabel label;
- private int x, y;
- public ChessField(Color color, int x, int y) {
- this.x = x;
- this.y = y;
- setBackground(color);
- label = new JLabel();
- setLayout(new BorderLayout());
- add(label);
- addMouseListener(
- new MouseAdapter() {
- @Override
- public void mouseClicked(MouseEvent arg0) {
- move();
- }
- }
- );
- }
- private void move() {
- int xDiff = Math.abs(x - knight.x);
- int yDiff = Math.abs(y - knight.y);
- if ((xDiff == 1 && yDiff == 2) || (xDiff == 2 && yDiff == 1)) {
- knight.reset();
- knight.setVisited();
- knight = this;
- setKnight();
- }
- }
- public void setKnight() {
- label.setIcon(knightIcon);
- }
- public void reset() {
- label.setIcon(null);
- }
- public void setVisited() {
- setBackground(Color.GREEN);
- }
- }
- public KonjicevSkok() {
- JPanel chessBoard = new JPanel();
- chessBoard.setLayout(new GridLayout(8, 8));
- for (int i = 0; i < 8; i++) {
- for (int j = 0; j < 8; j++) {
- boolean gray = (i + j) % 2 == 1;
- ChessField f = null;
- if (gray) {
- f = new ChessField(Color.GRAY, i, j);
- } else {
- f = new ChessField(Color.WHITE, i, j);
- }
- board[i][j] = f;
- if (i == 0 && j == 0) {
- f.setKnight();
- knight = f;
- }
- chessBoard.add(f);
- }
- }
- Container c = getContentPane();
- c.add(chessBoard);
- }
- public static void main(String[] args) {
- KonjicevSkok g = new KonjicevSkok();
- g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- g.setSize(400, 400);
- g.setTitle("Konjicev skok");
- g.setVisible(true);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement