2012-01-18 115 views
3

我在java中做了一個基本的蛇遊戲,我需要一些幫助獲得更流暢的動畫。蛇的每一部分都是20x20的正方形,所以我讓蛇每移動一步20個像素。這使蛇看起來像一個網格,這意味着它將總是與只在「網格」上產生的食物排成一線。現在我的問題是,當我嘗試將它移動3步時,它不再與「網格」對齊。另一個更嚴重的問題是,蛇通過移動第一個方塊來移動,然後將所有其他方法設置到數組中的下一個位置(請參閱代碼)。問題是,當它移動3步時,蛇會縮小,所以每個起點之間只有3個間隔,而不是20個。任何人都可以幫助解決這些問題嗎?如果需要,我可以添加整個源代碼。蛇遊戲(java)中的流暢動畫?

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; 
} 
} 
+1

爲什麼不會移動20倍(即2,5,10)?然後,你的蛇將與地圖上的每個塊對齊,並應解決你的問題。與3不同,你的蛇只會與每個第3塊對齊。 – 2012-01-18 17:52:48

回答

6

1)使用Java命名約定正確player1應該Player1

2)不使用pre_historic AWT Canvas,使用Swing JPanel, JLabel or JComponent,同爲Frame ---> JFrame

3)不使用KeyListener,因爲您的帆布需要Focus,最簡單的就是使用KeyBinding

4)您有012問題,使用javax.swing.Timer而非錯implemntations爲Runnable#Tread

5)永遠不會使用Thread.sleep(Math.max(0, difference));用於AWT/Swing的焦耳/組件,因爲塊EventDispatchTread,並且通過爲了Thread.sleep錯implentations()yoour GUI將被冷凍的os留un_responsible,使用javax.swing.Timer來處理Swing中的任何事件

6)在這裏發佈一個SSCCE,它展示了你的真正的組織,而不是一堆un_relatted代碼和somw anothere錯過(也許是,也許不是)重要的類,

+0

我想給你+1分,但這是不可能的:-( – Robin 2012-01-18 18:53:23

+0

嗯,謝謝你的幫助。我先解決所有這些問題,然後我會回到我在這裏發佈的問題。我是一個編程/ java noob所以有很多東西我需要工作 – user1150769 2012-01-18 19:34:09

+0

很高興幫助,在這個論壇有很多相關的問題和答案 – mKorbel 2012-01-18 19:37:09

1

除了@ mKorbel的優秀建議,請考慮使用你的蛇段一個java.util.Queue

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

然後一個動畫步驟需要簡單地去除最舊的Element並添加一個新的多數民衆贊成根據您的遊戲對位置和速度規則偏移:

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

+1我看到我忘了油漆vs paintComponent – mKorbel 2012-01-18 22:04:09

+1

@mKorbel:我會說這是第二點的一部分,但我會添加相關的引用,「Swing程序應該重寫'paintComponent()',而不是重寫'paint()'。」 - [在AWT和Swing中繪製:Paint方法(http://java.sun.com/products/jfc/tsc/articles/painting/index.html#callbacks)。 – trashgod 2012-01-18 23:44:03