一、建立基础
-
新建 ballgame1.java 文件,新建 images 文件夹,把游戏涉及的 ball desk 图片放进去
-
制作一个基础的窗口
import java.awt.*;
import javax.swing.*;
public class BallGame extends JFrame {
// 窗口加载
void launchFrame() {
setSize(300, 300);
setLocation(400, 400);
setVisible(true);
}
//main 方法是执行程序的入口
public static void main(String[] args) {
System.out.println("hello, it my first game");
BallGame game = newBallGame();
game.launchFrame();
}
}
最终效果
二、加载两个图片
import java.awt.* ;
import javax.swing.*;
public class BallGame extends JFrame {
Image ball = Toolkit.getDefaultToolkit().getImage('images/ball.png');
Image desk = Toolkit.getDefaultToolkit().getImage('images/desk.jpg');
double x = 100; //小球的坐标
double y = 100;
//画窗口的方法
public void paint(Graphics g){
System.out.println('windows load again');
g.drawImage(desk, 0, 0, null);
g.drawImage(ball, (int)x, (int)y, null);
}
// 窗口加载
void launchFrame(){
setSize(856,500);
setLocation(50,50);
setVisible(true);
}
public static void main(String[] args){
System.out.println('the first game');
BallGame game = new BallGame();
game.launchFrame();
}
}
最终效果
三、实现小球水平动态运动
import java.awt.*;
import javax.swing.*;
public class BallGame extends JFrame {
Image ball = Toolkit.getDefaultToolkit().getImage('images/ball.png');
Image desk = Toolkit.getDefaultToolkit().getImage('images/desk.jpg');
double x = 100;
double y = 100;
boolean right = true; //方向
//画窗的方法
public void paint(Graphics g){
System.out.println('paint again');
g.drawImage(desk, 0, 0, null);
g.drawImage(ball, (int)x, (int)y, null);
if(right){
x = x + 10;
} else{
x = x - 10;
}
if(x>856-70){
right = false;
}
if(x<40){
right = true;
}
}
void launchFrame(){
setSize(856,500);
setLocation(50, 50);
setVisible(true);
while(true){
repaint();
try{
Thread.sleep(40);
}catch(Expection e){
e.printStackTrace();
}
}
}
public static void main(String[] args){
System.out.println('my first game');
BallGame game = new BallGame();
game.launcFrame();
}
}
四、小球沿着任意角度运动(复制)
import java.awt.*;
import javax.swing.*;
public class BallGame2 extends JFrame {
Image ball = Toolkit.getDefaultToolkit().getImage("images/ball.png");
Image desk = Toolkit.getDefaultToolkit().getImage("images/desk.jpg");
double x=100; //小球的横坐标
double y=100; //小球的纵坐标
double degree = 3.14/3; //弧度。此处就是:60度
//画窗口的方法
public void paint(Graphics g){
System.out.println("窗口被画了一次!");
g.drawImage(desk, 0, 0, null);
g.drawImage(ball,(int)x, (int)y, null);
x = x+ 10*Math.cos(degree);
y = y +10*Math.sin(degree);
//碰到上下边界
if(y>500-40-30||y<40+40){//500是窗口高度;40是桌子边框,30是球直径;最后一个40是标题栏的高度
degree = -degree;
}
//碰到左右边界
if(x<40||x>856-40-30){
degree = 3.14 - degree;
}
}
//窗口加载
void launchFrame(){
setSize(856,500);
setLocation(50,50);
setVisible(true);
//重画窗口,每秒画25次
while(true){
repaint();
try{
Thread.sleep(40); //40ms, 1秒=1000毫秒. 大约一秒画25次窗口
}catch(Exception e){
e.printStackTrace();
}
}
}
//main方法是程序执行的入口
public static void main(String[] args){
System.out.println(" 小游戏而已!");
BallGame2 game = new BallGame2();
game.launchFrame();
}
}
网友评论