📄 game.java
字号:
/**
*声明:1、本程序是作为金鹰教育网学习Java基本语法的例子。可以自由使用,但必须保留此声明!
* 2、具体的介绍、说明文档,请见金鹰教育网:www.eagledu.org
* 3、有问题的,请到金鹰教育网:www.eagledu.org中的Java标准版本课程中提出,我们会及时给予答复!
* 4、有其它想法的,也可直接交流:eagleduorg@126.com
*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Game extends Applet implements Runnable{
private int xpos=100,ypos=0;//当前活动图形的相对坐标
private BaseShape currShape;//当前活动的图形
private Image buffer;//双缓存内存图
private Graphics bg;
private Thread th;
private Button btnStart=new Button("开始");
public Game()
{
th=new Thread(this);
}
public void init() {
buffer=this.createImage(200,400);
bg=buffer.getGraphics();
currShape=new Ding();
currShape.setShape(xpos,ypos);
bg.setColor(Color.BLACK);
bg.fillRect(0,0,200,400);
currShape.paint(bg);
this.addKeyListener(new GameKeyLister());
this.setLayout(null);
btnStart.setBounds(220,20,60,20);
btnStart.addActionListener(new StartActionListener());
this.add(btnStart);
}
public void update(Graphics g)
{
g.clipRect(0,0,200,400);
bg.setColor(Color.BLACK);
bg.fillRect(0,0,200,400);
currShape.paint(bg);
paint(g);
}
public void paint(Graphics g) {
g.drawImage(buffer,0,0,this);
}
//子线程的代码,每隔0.5移,下移一格
public void run()
{
while(true)
{
ypos+=20;
currShape.setShape(xpos,ypos);
if(currShape.getBottom()>400)
{
ypos-=20;
currShape.setShape(xpos,ypos);
}
repaint();
try{
Thread.sleep(500);
}
catch(InterruptedException e)
{ }
}
}
//内部类,处理按钮单击事件
class StartActionListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
th.start();
requestFocus(true);//让applet得到焦点
}
}
//内部类,以实现键盘的事件处理
class GameKeyLister extends KeyAdapter
{
public void keyReleased(KeyEvent e)
{
int keyCode=e.getKeyCode();
if(keyCode==KeyEvent.VK_UP)
{
currShape.rotate();
currShape.setShape(xpos,ypos);
while(currShape.getLeft()<0)
{
xpos+=20;
currShape.setShape(xpos,ypos);
}
while(currShape.getRight()>200)
{
xpos-=20;
currShape.setShape(xpos,ypos);
}
while(currShape.getBottom()>400)
{
ypos-=20;
currShape.setShape(xpos,ypos);
}
repaint();
}
else if(keyCode==KeyEvent.VK_RIGHT && currShape.getRight()<200)
{
xpos+=20;
currShape.setShape(xpos,ypos);
repaint();
}
else if(keyCode==KeyEvent.VK_LEFT && currShape.getLeft()>0)
{
xpos-=20;
currShape.setShape(xpos,ypos);
repaint();
}
else if(keyCode==KeyEvent.VK_DOWN && currShape.getBottom()<400)
{
ypos+=20;
currShape.setShape(xpos,ypos);
repaint();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -