Java小程序游戏双缓冲中断与switch语句

Java小程序游戏双缓冲中断与switch语句,java,applet,awt,switch-statement,doublebuffered,Java,Applet,Awt,Switch Statement,Doublebuffered,我刚开始尝试制作游戏,我做了一个HelloWorld小程序,然后测试了我的滚动想法,最终它开始变成一个“直升机”式的游戏。现在一切都很顺利,直到我决定加入一堆switch语句来处理状态(标题屏幕、跑步和游戏结束)。以前运行的代码没有变化,我的新“简介屏幕”工作正常,但当你切换到游戏状态时,双缓冲似乎出了问题。游戏前景快速闪烁,并有三角形切割出来,背景几乎没有渲染。这只是我在探索游戏编码的基本原理,所以它不是优雅的、模块化的或任何东西,但它应该可以工作 [编辑]我知道小程序和AWT通常是一种不好的

我刚开始尝试制作游戏,我做了一个HelloWorld小程序,然后测试了我的滚动想法,最终它开始变成一个“直升机”式的游戏。现在一切都很顺利,直到我决定加入一堆switch语句来处理状态(标题屏幕、跑步和游戏结束)。以前运行的代码没有变化,我的新“简介屏幕”工作正常,但当你切换到游戏状态时,双缓冲似乎出了问题。游戏前景快速闪烁,并有三角形切割出来,背景几乎没有渲染。这只是我在探索游戏编码的基本原理,所以它不是优雅的、模块化的或任何东西,但它应该可以工作

[编辑]我知道小程序和AWT通常是一种不好的方式,但我是这样开始的,我只想了解它是如何工作的,我做错了什么,这样我就可以满足并继续前进

package testStuff;


import java.awt.*;
import java.applet.*;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;


public class HelloWorld extends Applet implements Runnable{

//game time counter
int count = 0;

//controller object
Controller control;

//accesses images and creates image variables
File wavesource = new File("C:\\sourceimages\\waves.jpg");
File playerSource = new File("C:\\sourceimages\\plane3.png");
Image player = null;
Image waves = null;

//font for score
Font myFont;

//double buffer objects
Graphics bground;
Image bgImage = null;
private int bgx = 0;

//player position
private int xPos=0;
private int yPos=50;

//arrays for tunnel locations
private int[] topTunnel = new int[200];
private int[] botTunnel = new int[200];

//size of tunnel
private int tunnelSize;

//boolean determines direction of tunnel movement
private boolean tunUp;

//state
private int state;


//"constructor"
public void init(){

    //set state
    state = 0;
    //instantiates controller adds it to the applet
    control = new Controller();
    this.addKeyListener(control);
    //instantiates images
    try {
        waves = ImageIO.read(wavesource);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        player = ImageIO.read(playerSource);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //instantiates arrays and tunnel size
    for(int i=0;i<199;i++){
        topTunnel[i]=-1;
        botTunnel[i]=-1;
    }
    topTunnel[199]=20;
    botTunnel[199]=179;
    tunnelSize = botTunnel[199]-topTunnel[199];
    tunUp = false;
}
public void paint(Graphics g){
    switch(state){
    case 0:
        g.setColor(Color.black);
        myFont = new Font("Courier", Font.BOLD+Font.ITALIC, 12);
        g.setFont(myFont);
        g.drawString("DON'T CRASH THE PLANE BRO", 10, 100);
        myFont = new Font("Courier", Font.PLAIN, 8);
        g.setFont(myFont);
        g.drawString("Press Spacebar to Play", 40, 150);
        break;
    case 1:
        g.drawImage(player, xPos, yPos, null);
        g.setColor(Color.red);
        for(int i=0;i<200;i++){
            g.fillRect(i, 0, 1, topTunnel[i]);
            g.fillRect(i, botTunnel[i], 1, botTunnel[i]);
        }
        g.setColor(Color.cyan);
        myFont = new Font("Helvetica", Font.PLAIN, 12);
        setFont(myFont);
        if(count<170)
            g.drawString("SCORE: " + 0, 0, 12);
        else
            g.drawString("SCORE: " + (this.count-170), 0, 12);
        break;
    }
}

public void start(){
    Thread thread = new Thread(this);
    thread.start();
}

@Override
public void run(){
    while(true){
        switch(state){
        case 0:
            //increases count
            count++;

            //paints
            this.repaint();

            try {
                    Thread.sleep(1000/30);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            if(control.spaceDown()){
                state = 1;
                count = 0;
            }
            break;

        case 1:
            //increases count
            count++;

            //handles scrolling
            if(xPos<75){
                xPos++;
            }
            else{
                if(bgx>-600){
                    bgx--;
                }
                else{
                    bgx=0;
                }
            }
            //handles input
            if(control.spaceDown()==true&&yPos>=0){
                yPos--;
            }
            else if(yPos<180){
                yPos++;
            }
            //repositions tunnel
            if(xPos>=75){
                for(int i=1;i<200;i++){
                    topTunnel[i-1]=topTunnel[i];
                    botTunnel[i-1]=botTunnel[i];
                }
            }
            //defines new tunnel space
            if(topTunnel[199]<=0 || !tunUp)
                topTunnel[199]++;
            if(botTunnel[199]>=200 || tunUp)
                topTunnel[199]--;
            botTunnel[199] = topTunnel[199]+tunnelSize;

            //randomly chooses direction to move tunnel
            double randomNum = Math.random();
            if(randomNum>.5)
                tunUp = true;
            else
                tunUp = false;

            //narrows tunnel
            if(count%20 == 0)
                tunnelSize--;

            //calls update
            this.repaint();
            //handles framerate
            try {
                Thread.sleep(1000/30);
            } catch (InterruptedException e) {
                 //TODO Auto-generated catch block
                e.printStackTrace();
            }
            break;
        }
    }
}

public void update(Graphics g){

    //instantiates image and graphics on first tick
    if(bgImage == null){
        bgImage = createImage(this.getSize().width, this.getSize().height);
        bground = bgImage.getGraphics();
    }
    //create background based on state
    switch(state){
    case 0:
        //flashing colors!
        if(count%20<10){
            bground.setColor(Color.yellow);
            bground.fillRect(0, 0, 200, 200);
        }
        else{
            bground.setColor(Color.orange);
            bground.fillRect(0, 0, 200, 200);
        }
        break;
    case 1:
        //draws background image(s)
        bground.drawImage(waves,bgx,0,this);
        if(bgx<-399)
            bground.drawImage(waves,bgx+600,0,this);
        break;
    }
    //paint over the background then draw it to screen
    paint(bground);
    g.drawImage(bgImage, 0, 0, this);
}
 }
testStuff包;
导入java.awt.*;
导入java.applet.*;
导入java.io.File;
导入java.io.IOException;
导入javax.imageio.imageio;
公共类HelloWorld扩展小程序实现可运行{
//游戏时间计数器
整数计数=0;
//控制器对象
控制器控制;
//访问图像并创建图像变量
File wavesource=新文件(“C:\\sourceimages\\waves.jpg”);
File playerSource=新文件(“C:\\sourceimages\\plane3.png”);
图像播放器=空;
图像波=零;
//分数字体
字体myFont;
//双缓冲区对象
图形背景圆;
图像bgImage=null;
私有整数bgx=0;
//球员位置
私有int xPos=0;
私人int yPos=50;
//隧道位置阵列
私有整数[]topTunnel=新整数[200];
私有int[]botTunnel=新int[200];
//隧道尺寸
私人隧道;
//布尔值确定隧道移动的方向
私有布尔tunUp;
//陈述
私人和国家;
//“构造函数”
公共void init(){
//设定状态
状态=0;
//实例化控制器并将其添加到小程序
控制=新控制器();
这个.addKeyListener(控件);
//实例化图像
试一试{
波=图像读取(波源);
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
试一试{
player=ImageIO.read(playerSource);
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
//实例化数组和隧道大小

对于(int i=0;i我认为您应该开始,但要添加更多的大括号。我是一名编码初学者,但从我所阅读的内容来看,在代码中的某些语句上编写没有大括号的冗长语句会导致一些错误

这里有很多过程,我觉得牙套有帮助

如果我错了,请纠正我,我也只是想学习!

您需要“清除”每个帧上的图形,否则您将在先前绘制的基础上绘制

在下面的示例中,我在“播放”时填充了图形上下文,但在暂停时仍保持不变,您应该能够看到差异

public class HelloWorld extends Applet implements Runnable {

    private int direction = 4;
    private int state = 0;
    private Image bgImage;
    private Graphics bground;
    private int count;

    private int x = 0;

//"constructor"
    public void init() {
        addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                    if (state == 0) {
                        state = 1;
                    } else if (state == 1) {
                        state = 0;
                    }
                }
            }

        });
    }

    public void paint(Graphics g) {
        switch (state) {
            case 0:
                g.setColor(Color.black);
                g.drawString("DON'T CRASH THE PLANE BRO", 10, 100);
                g.drawString("Press Spacebar to Play", 40, 150);
                break;
            case 1:
                break;
        }
    }

    public void start() {
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        while (true) {
            switch (state) {
                case 0:
                    count++;
                    this.repaint();
                    break;
                case 1:

                    x += direction;
                    if (x < 0) {
                        x = 0;
                        direction *= -1;
                    } else if (x > getWidth()) {
                        x = getWidth();
                        direction *= -1;
                    }

                    //calls update
                    this.repaint();
                    //handles framerate
                    try {
                        Thread.sleep(1000 / 30);
                    } catch (InterruptedException e) {
                        //TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    public void update(Graphics g) {

        //instantiates image and graphics on first tick
        if (bgImage == null) {
            bgImage = createImage(this.getSize().width, this.getSize().height);
            bground = bgImage.getGraphics();
        }
        //create background based on state
        switch (state) {
            case 0:
                //flashing colors!
                if (count % 20 < 10) {
                    bground.setColor(Color.yellow);
                    bground.fillRect(0, 0, 200, 200);
                } else {
                    bground.setColor(Color.orange);
                    bground.fillRect(0, 0, 200, 200);
                }
                break;
            case 1:
                bground.setColor(Color.WHITE);
                bground.fillRect(0, 0, getWidth(), getHeight());
                bground.setColor(Color.RED);
                int y = (getHeight() / 2) - 4;
                bground.fillOval(x, y, 8, 8);
                break;
        }
        //paint over the background then draw it to screen
        paint(bground);
        g.drawImage(bgImage, 0, 0, this);
    }

}
公共类HelloWorld扩展小程序实现可运行{
专用int方向=4;
私有int状态=0;
私有图像;
私密图形;
私人整数计数;
私有整数x=0;
//“构造函数”
公共void init(){
addKeyListener(新的KeyAdapter(){
@凌驾
按下公共无效键(按键事件e){
if(例如getKeyCode()==KeyEvent.VK_空间){
如果(状态==0){
状态=1;
}else if(state==1){
状态=0;
}
}
}
});
}
公共空间涂料(图g){
开关(状态){
案例0:
g、 设置颜色(颜色为黑色);
g、 抽绳(“不要撞毁飞机兄弟”,10100);
g、 抽绳(“按空格键播放”,40、150);
打破
案例1:
打破
}
}
公开作废开始(){
螺纹=新螺纹(此);
thread.start();
}
@凌驾
公开募捐{
while(true){
开关(状态){
案例0:
计数++;
这个。重新绘制();
打破
案例1:
x+=方向;
if(x<0){
x=0;
方向*=-1;
}如果(x>getWidth()),则为else{
x=getWidth();
方向*=-1;
}
//呼叫更新
这个。重新绘制();
//处理帧速率
试一试{
睡眠(1000/30);
}捕捉(中断异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
打破
}
}
}
公共空间更新(图g){
//在第一个刻度上实例化图像和图形
如果(bgImage==null){
bgImage=createImage(this.getSize().width,this.getSize().height);
bground=bgImage.getGraphics();
}
//基于状态创建背景
开关(状态){
案例0:
//闪烁的颜色!
如果(计数%20<10){
bground.setColor(Color.yellow);
bground.fillRect(0,0200200);
}否则{
bground.setColor(Color.orange);
bground.fillRect(0,0200200);
}
打破
案例1:
bground.setColor(Color.WHITE);
B回合
        //randomly chooses direction to move tunnel
        double randomNum = Math.random();
        if(randomNum>.5)
            tunUp = true;
        else
            tunUp = false;

        //narrows tunnel
        if(count%20 == 0)
            tunnelSize--;

        //calls update
        this.repaint();
public class HelloWorld extends Applet implements Runnable {

    private int direction = 4;
    private int state = 0;
    private Image bgImage;
    private Graphics bground;
    private int count;

    private int x = 0;

//"constructor"
    public void init() {
        addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                    if (state == 0) {
                        state = 1;
                    } else if (state == 1) {
                        state = 0;
                    }
                }
            }

        });
    }

    public void paint(Graphics g) {
        switch (state) {
            case 0:
                g.setColor(Color.black);
                g.drawString("DON'T CRASH THE PLANE BRO", 10, 100);
                g.drawString("Press Spacebar to Play", 40, 150);
                break;
            case 1:
                break;
        }
    }

    public void start() {
        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        while (true) {
            switch (state) {
                case 0:
                    count++;
                    this.repaint();
                    break;
                case 1:

                    x += direction;
                    if (x < 0) {
                        x = 0;
                        direction *= -1;
                    } else if (x > getWidth()) {
                        x = getWidth();
                        direction *= -1;
                    }

                    //calls update
                    this.repaint();
                    //handles framerate
                    try {
                        Thread.sleep(1000 / 30);
                    } catch (InterruptedException e) {
                        //TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    public void update(Graphics g) {

        //instantiates image and graphics on first tick
        if (bgImage == null) {
            bgImage = createImage(this.getSize().width, this.getSize().height);
            bground = bgImage.getGraphics();
        }
        //create background based on state
        switch (state) {
            case 0:
                //flashing colors!
                if (count % 20 < 10) {
                    bground.setColor(Color.yellow);
                    bground.fillRect(0, 0, 200, 200);
                } else {
                    bground.setColor(Color.orange);
                    bground.fillRect(0, 0, 200, 200);
                }
                break;
            case 1:
                bground.setColor(Color.WHITE);
                bground.fillRect(0, 0, getWidth(), getHeight());
                bground.setColor(Color.RED);
                int y = (getHeight() / 2) - 4;
                bground.fillOval(x, y, 8, 8);
                break;
        }
        //paint over the background then draw it to screen
        paint(bground);
        g.drawImage(bgImage, 0, 0, this);
    }

}