蛇游戏中的流畅动画(java)?

时间:2012-01-18 17:48:08

标签: java swing animation

我在java中制作了一个基本的蛇游戏,我需要一些帮助来获得更流畅的动画效果。蛇的每个部分都是20x20的正方形,所以我让蛇以每个刻度20像素的步长移动。这使得蛇似乎在网格上移动,这意味着它将始终与仅在“网格”上产生的食物对齐。现在我的问题是,当我尝试将它移动3步时,它不再与“网格”对齐。另一个更严重的问题是蛇通过移动第一个方块移动,然后将所有其他方设置到数组中的下一个位置(参见代码)。问题是,当它移动3步时,蛇会收缩,所以每个原点之间只有3个间隙,而不是20个。任何人都可以帮助解决这些问题吗?如果需要,我可以添加整个源代码。

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferStrategy;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import javax.swing.Timer;

public class player1 extends Canvas implements Runnable {

private keyevents keyevent;
private element [] elements;
private element goal;
private int numSegments, score, endY, quitX, snakeSize, windowSize;
private Font scorefont;

private long cycleTime;
private final int FRAME_DELAY;
private BufferStrategy bf;
private boolean gameOver, isRunning;

public player1(Frame window) {
    setSize(new Dimension(window.getWidth(), window.getHeight()));
    FRAME_DELAY = 20;
    windowSize = 400;
    snakeSize = 20;
    score = 0;
    isRunning = false;
    numSegments = 5;
    scorefont =  new Font("Verdana", Font.BOLD, snakeSize);
    elements = new element [300];
    goal = new element(randompos(snakeSize,windowSize-snakeSize),randompos(snakeSize,windowSize-snakeSize), snakeSize, Color.green);
    keyevent = new keyevents();
    keyevent.setP1Keys(2,true);

    for (int i=0, xPos = round(windowSize/2), yPos = round(windowSize/2); i<numSegments; i++, xPos+=snakeSize) {
        elements[i] = new element(xPos,yPos, snakeSize, Color.blue);
    }

    addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent evt) {
            keyevent.moveIt(evt); 
            switch(evt.getKeyCode()){
            case KeyEvent.VK_ESCAPE:
                isRunning = false;
                screen.newMenu();
            }
        }
    });
}

public void start(player1 ex){
    isRunning = true;
    Thread gameThread = new Thread(ex);
    gameThread.setPriority(Thread.MIN_PRIORITY);
    gameThread.start(); 
}

public void run(){ 
    cycleTime = System.currentTimeMillis();
    while(isRunning){
        logic();
        render();
        sync();
    }
}

public void render() {
    if (bf==null){
        bf = getBufferStrategy();
    }
    Graphics2D g2 = null;
    try{
        g2 = (Graphics2D) bf.getDrawGraphics(); 
        g2.setColor(Color.black);
        g2.fillRect(0, 0, windowSize, windowSize);
        for (int i=0;i<numSegments;i+=1) {
            elements[i].draw(g2);
        }
        g2.setColor(Color.green);
        goal.draw(g2);
        g2.setColor(Color.orange);
        g2.fill3DRect(0, 0, windowSize, snakeSize, true);
        g2.setColor(Color.red);
        g2.setFont(scorefont);
        g2.drawString("Score: "+score, 5, snakeSize-4);
        FontMetrics fm = g2.getFontMetrics();
        g2.setColor(Color.blue);
        fm = g2.getFontMetrics();
        g2.setColor(Color.black);
        quitX = (windowSize - fm.stringWidth("ESC = quit")-5);
        g2.drawString("ESC = quit",quitX,snakeSize-snakeSize/5);
    }finally{
        g2.dispose();
    }
    bf.show();
    Toolkit.getDefaultToolkit().sync();
}

public void sync(){
    cycleTime = cycleTime + FRAME_DELAY;
    long difference = cycleTime - System.currentTimeMillis();
    try {
        Thread.sleep(Math.max(0, difference));
    }
    catch(InterruptedException e) {
        e.printStackTrace();
    }
}

public void logic(){
    int x = elements[0].getX();
    int y = elements[0].getY();
    Rectangle elementrect = elements[0].getRect();  
    keyevent.setP1Pressed(false);

    //Movement
    for(int i = numSegments-1; i>0; i--){
        elements[i].setX(elements[i-1].getX());
        elements[i].setY(elements[i-1].getY());
    }   
    if(keyevent.getP1Keys(0)){
        elements[0].setY(y+20);
    }
    else if(keyevent.getP1Keys(1)){
        elements[0].setY(y-20);
    }
    else if(keyevent.getP1Keys(2)){
        elements[0].setX(x-20);
    }
    else if(keyevent.getP1Keys(3)){ 
        elements[0].setX(x+20);
    }
    if(elements[0].getX()>windowSize-snakeSize){
        elements[0].setX(0);
    }
    else if(elements[0].getX()<0){
        elements[0].setX(windowSize-snakeSize);
    }
    if(elements[0].getY()>windowSize-snakeSize){
        elements[0].setY(0);
    }
    else if(elements[0].getY()<0+snakeSize){
        elements[0].setY(windowSize-snakeSize);
    }
    for(int i=0; i<numSegments; i++){
        elements[i].updateRect();
    }       

    //Collision
    if(elementrect.intersects(goal.getRect())){
        numSegments+=1;
        elements[numSegments-1] = new element(elements[numSegments-2].getX(),elements[numSegments-2].getY(), snakeSize,Color.blue);
        goal.setX(randompos(snakeSize,windowSize-snakeSize));
        goal.setY(randompos(snakeSize,windowSize-snakeSize));
        score+=1;
    }
    for(int i=1; i<numSegments; i++){
        if(elementrect.intersects(elements[i].getRect())){
            gameOver();
        }
    }
}

public void gameOver(){
    isRunning = false;
}

public int randompos(int min,int max){
    System.out.println(snakeSize);
    int range = max-min;
    Random randompos = new Random();
    int pos = randompos.nextInt(range)+min;
    pos*=2;
    pos += snakeSize;
    pos /= snakeSize*2;
    pos *= snakeSize*2;
    pos/=2;
    return pos;
}
}

2 个答案:

答案 0 :(得分:6)

1)正确使用Java命名约定player1应为Player1

2)不要使用pre_historic AWT Canvas,使用Swing JPanel, JLabel or JComponent,同样适用于Frame ---> JFrame

3)不要使用KeyListener,因为您的Canvas需要Focus,最简单的是使用KeyBinding

4)您遇到Concurency in Swing的问题,使用javax.swing.Timer而非Runnable#Tread的错误实施

5)永远不要将Thread.sleep(Math.max(0, difference));用于AWT / Swing J / Components,因为阻止EventDispatchTread,以及对于Thread.sleep()你错误的GUI实现将冻结os保持不负责任,使用javax。 swing.Timer用于分析Swing中的任何事件

6)在这里张贴SSCCE,展示你的真实的uissues,而不是一堆无法解释的代码,并且somw anothere错过了(也许是,也许不是)重要的类,

答案 1 :(得分:1)

除了@ mKorbel的优秀建议外,请考虑为您的蛇段使用java.util.Queue

Queue<Element> snake = new LinkedList<Element>();

然后单个动画步骤只需删除最早的Element并根据游戏的位置和速度规则添加一个新的偏移量:

snake.remove();
snake.add(newElement());
this.repaint();