问题遇到的现象和发生背景
Java实战项目
MyFish在游戏开始后加载不出来
窗口代码
package com.ynl;
import javax.swing.;
import java.awt.;
import java.awt.event.*;
public class GameWin extends JFrame{
/*游戏状态 0未开始,1游戏中,2通关失败,3通关成功,4暂停/
//游戏默认状态
static int state = 0;
Image offScreenImage;
//窗口大小
int width = 1209;
int height = 754;
double random;
//计数器
int time = 0;
//背景类的队像
Bg bg = new Bg();
//敌方鱼类
Enamy enamy;
//我方鱼类
MyFish myFish = new MyFish();
public void launch(){
//设置窗口是否可见
this.setVisible(true);
//设置窗口大小
this.setSize(width,height);
//设置窗口在屏幕的居中位置
//this.setLocation(null);
//设置游戏窗口不可改变
//this.setResizable(false);
//设置窗口标题
this.setTitle("YNL");
//设置关闭窗口按钮
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(e.getButton() == 1&&state == 0){
state = 1;
repaint();
}
}
});
//键盘监视器的运用
this.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
super.keyTyped(e);
}
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
if(e.getKeyCode() == 87){
GameUtils.UP = true;
System.out.println("W");
}
if(e.getKeyCode() == 83){
GameUtils.DOWN = true;
System.out.println("S");
}
if(e.getKeyCode() == 65){
GameUtils.LEFT = true;
System.out.println("D");
}
if(e.getKeyCode() == 63){
GameUtils.RIGHT = true;
System.out.println("A");
}
}
@Override
public void keyReleased(KeyEvent e) {
//super.keyReleased(e);
if(e.getKeyCode() == 87){
GameUtils.UP = false;
}
if(e.getKeyCode() == 83){
GameUtils.DOWN = false;
}
if(e.getKeyCode() == 65){
GameUtils.LEFT = false;
}
if(e.getKeyCode() == 63){
GameUtils.RIGHT = false;
}
}
});
//背景图片需要重复使用,因此需要加上循环(该循环是每隔40秒调用1次)
/**加上while循环后其实页面会出现文字闪动的情况,需双缓存解决*/
while(true){
repaint();
time++;
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void paint(Graphics g) {
//加载模式初始化对象
offScreenImage = createImage(width,height);
Graphics gImage = offScreenImage.getGraphics();
//g.drawImage(GameUtils.bgimg,0,0,null);
switch (state){
case 0:
//启动背景图片
gImage.drawImage(GameUtils.bgimg,0,0,null);
//将画笔颜色改为粉色
gImage.setColor(Color.pink);
//设置字体样式
gImage.setFont(new Font("仿宋",Font.BOLD,60));
//为启动页面添加文字
gImage.drawString("开始",555,425);
//gImage.requestFocus();
break;
case 1:
bg.paintSelf(gImage);//加载开始页面的图片
myFish.paintSelf(gImage);
logic();
for (Enamy enamy:GameUtils.EnamyList) {
enamy.paintSelf(gImage);
}
break;
case 2:
break;
case 3:
break;
case 4:
break;
default:
}
g.drawImage(offScreenImage,0,0,null);
}
void logic(){
//敌方鱼的生成
if(time % 10 == 0){
enamy = new Enamy_1_L();
GameUtils.EnamyList.add(enamy);
}
//敌方鱼的方向
for (Enamy enamy:GameUtils.EnamyList){
enamy.x = enamy.x + enamy.dir * enamy.speed;
}
}
//main方法
public static void main(String[] args) {
GameWin gameWin = new GameWin();
gameWin.launch();
}
}