Java推箱子小游戏-1

GameFrame类   (在Java中创建一个窗体)

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;

public class GameFrame extends JFrame implements KeyListener {
 GamePanel gp;//申请一个画布在窗体里面
 public GameFrame(){//构造窗体类
  this.setTitle("推箱子");//窗体标题
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭按钮
  this.setSize(500,500);//窗体的高度和宽度
  
  gp = new GamePanel();//把画布GamePanel赋值给gp
  this.add(gp);//在窗体中添加画布gp
  
  this.addKeyListener(this);
  this.setVisible(true);//设置窗体属性为可见
 }
 public void keyPressed(KeyEvent e) { 
 
  System.out.println(e);
  gp.keyDown(e.getKeyCode());
 
 }
 public void keyReleased(KeyEvent e) { 
 } 
 public void keyTyped(KeyEvent e) { 
 }
}
Run类 (用来启动窗体)


public class Run {
 public static void main(String[] args) {
  GameFrame gf = new GameFrame();
 }

}
GamePanel类 (在窗体上创建一个画布来放需要出现的东西)
import java.awt.Graphics;
import javax.swing.JPanel;

public class GamePanel extends JPanel {//构造画布类
 GamePlayer player;//定义玩家
 
 public GamePanel(){
  player = new GamePlayer(200,300);//玩家的初始位置
 }
 public void paint(Graphics g){//画笔
  g.fill3DRect(0, 0, 500, 500, true);//从00点添加一个矩形
  player.render(g);
 }
 public void keyDown(int code){
  switch(code){
  case 38://上键值
   player.movePlayer(0, -50);
   break;
  case 40:
   player.movePlayer(0, +50);
   break;
  case 37:
   player.movePlayer(-50, 0);
   break;
  case 39:
   player.movePlayer(+50, 0);
   break;
  }
   this.repaint();//刷新
    
 }
}
GamePlayer类 (玩家图片显示在窗体画布上并移动)

import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;

public class GamePlayer {
 Image im;//定义im存放玩家
 int x , y;//玩家在窗体上的坐标
 
 public GamePlayer(int _x,int _y){
 
  ImageIcon icon;
  icon = new ImageIcon("player.png");//icon中存入图片
  im = icon.getImage();
  x= _x;
  y= _y;
 }
 public void render(Graphics g){
  g.drawImage(im , x , y , null);
  
 }
 public void movePlayer(int dx , int dy){
  x += dx;
  y += dy;
 }
}


你可能感兴趣的:(Java推箱子小游戏-1)