/*java第二次实验 * 移动小方块 */ import javax.swing.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.*; public class Game { public static void main(String[] args) { GameFrame MyFrame = new GameFrame(); MyFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MyFrame.setVisible(true); } } class GameFrame extends JFrame { private int flag = 0; private double xPos[] = { 0, 0, 270, 0, 270 }; private double yPos[] = { 0, 0, 0, 270, 270 }; private double arriver[] = { 0, 0, 0, 0, 0 }; private Rectangle2D rect[] = new Rectangle2D[5]; public GameFrame() { GamePanel MyPanel = new GamePanel(); addKeyListener(new GameKeyListener());// 增加监听器 this.add(MyPanel); setSize(308, 334); } class GamePanel extends JPanel { public GamePanel() { } public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; for (int i = 1; i <= 4; i++) { rect[i] = new Rectangle2D.Double(xPos[i], yPos[i], 30f, 30f); } ColorMovingPaint(g2); MiddlePaint(g2); isWin(g2); repaint(); } public void isWin(Graphics2D g2) { boolean isWin = true; for (int i = 1; i <= 4; i++) { if (arriver[i] == 0) isWin = false; } if (isWin) { g2.drawString("恭喜你,游戏结束!", 100, 100); } } public void MiddlePaint(Graphics g2) { g2.setColor(Color.RED); g2.drawRect(120, 120, 30, 30); g2.drawRect(120, 150, 30, 30); g2.drawRect(150, 120, 30, 30); g2.drawRect(150, 150, 30, 30); } public void ColorMovingPaint(Graphics2D g2) { for (int i = 1; i <= 4; i++) { if (flag != i) { g2.setColor(Color.BLUE); g2.fill(rect[i]); } else { g2.setColor(Color.RED); g2.fill(rect[i]); } } } } class GameKeyListener implements KeyListener { public void keyPressed(KeyEvent event) { int keyCode = event.getKeyCode(); if (keyCode == KeyEvent.VK_1) { flag = 1; } if (keyCode == KeyEvent.VK_2) { flag = 2; } if (keyCode == KeyEvent.VK_3) { flag = 3; } if (keyCode == KeyEvent.VK_4) { flag = 4; } if (keyCode == KeyEvent.VK_UP) { move(0, -30, flag); } if (keyCode == KeyEvent.VK_DOWN) { move(0, 30, flag); } if (keyCode == KeyEvent.VK_LEFT) { move(-30, 0, flag); } if (keyCode == KeyEvent.VK_RIGHT) { move(30, 0, flag); } } public void keyReleased(KeyEvent arg0) { } public void keyTyped(KeyEvent arg0) { } } void move(int x, int y, int flag) { double xTemp = xPos[flag] + x; double yTemp = yPos[flag] + y; boolean canMove = true; for (int i = 1; i <= 4; i++) { if (i == flag) continue; if (xTemp == xPos[i] && yTemp == yPos[i]||xTemp>270||xTemp<0||yTemp<0||yTemp>270) { canMove = false; break; } } if (canMove) { xPos[flag] += x; yPos[flag] += y; } if (xPos[flag] >= 120 && xPos[flag] <= 150 && yPos[flag] <= 150 && yPos[flag] >= 120) arriver[flag] = 1; else arriver[flag] = 0; } }