JAVA中的(不是传统的)蛇游戏

时间:2014-11-20 12:20:40

标签: java multithreading applet

我必须创建一个类似于[IMG] http://i58.tinypic.com/15guqs4.png[/IMG]的java applet。蛇由5个矩形制成,每个都有20px高度和20px宽度。通过使用线程,我必须使其仅在边缘和顺时针方向移动(如图中所示)。这是我的代码,我知道如何绘制蛇,我知道如何让它从左向右移动,我无法从上到下,从右到左,从下到上移动...任何帮助将不胜感激:)

import javax.swing.JApplet;

import java.awt.*;
import java.awt.event.*;
import java.util.logging.Logger;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.JComboBox;
import javax.swing.JApplet;
import javax.swing.JSlider;

import java.awt.Color;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Treta extends JApplet implements Runnable {

private int x = 0;
private int y = 0;
private int dx = 5;

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

public void paint(Graphics g){
    super.paint(g);

    g.setColor(Color.BLUE);
    g.fillRect(x, y, 20, 20);
    g.fillRect(x+20, y, 20, 20);
    g.fillRect(x+40, y, 20, 20);
    g.fillRect(x+60, y, 20, 20);
    g.fillRect(x+80, y, 20, 20);

    g.setColor(Color.BLACK);
    g.drawRect(x, y, 20, 20);
    g.drawRect(x+20, y, 20, 20);
    g.drawRect(x+40, y, 20, 20);
    g.drawRect(x+60, y, 20, 20);
    g.drawRect(x+80, y, 20, 20);
}

public void run(){
    while(true){
        x += dx;
        repaint();
        if(x >= getWidth()-20){
            y += 5;
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 }
}

0 个答案:

没有答案