这一周Java学习了如何去做一个小游戏,推箱子。
刚开始会发现很多问题,但经过老师的讲解,收获颇深。
import javax.swing.JFrame;
public class GameFrame extends JFrame {//继承
GamePanel gp;//有画板 int age;
//构造方法:创建对象,初始化属性值
public GameFrame(){
this.setSize(500,500);
this.setTitle("推箱子");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gp=new GamePanel();
this.add(gp);
this.setVisible(true);
}
}
import java.awt.Graphics;
import javax.swing.JPanel;
/*
* 系统画板
*/
public class GamePanel extends JPanel {
GamePlayer player;
public GamePanel(){
player=new GamePlayer(200,200);
}
//绘制画图:Graphics系统画笔
public void paint(Graphics g){
player.render(g);
}
}
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
/*
* 游戏中的玩家
*/
public class GamePlayer {
Image image;
int x,y;
public GamePlayer(int x,int y){
ImageIcon icon=new ImageIcon("player.png");
image=icon.getImage();
this.x=x;
this.y=y;
}
//绘制自己:渲染到屏幕上
public void render(Graphics g){
g.drawImage(image,x,y,null);//画图
}
//移动
public void movePlayer(int dx,int dy){
x=x+dx;
y=y+dy;
}
}
public class Run {
//创建一个对象,调用构造方法
public static void main(String[] args) {
GameFrame gf=new GameFrame();
}
}