我一直在搞乱 CanvasPaint 库,我想制作一个不错的小游戏,我可以根据用户输入在其中移动一个圆圈。
我的方法是创建 2 个同时运行的 While 循环,第一个寻找用户的新输入,第二个移动圆圈。
抱歉,由于我缺乏发布此类代码的经验,但我刚刚开始进行 Java 编码。
问题:我的“方向”变量始终为 0,我无法获得任何值 :(
package canvas;
import java.awt.Color;
import java.util.Scanner;
import TestPackage.CanvasPaint;
public class BilSpil extends Thread {
Scanner input = new Scanner (System.in);
private int direction;
public void run() { //First array, checking user-input
while(true) {
System.out.print("Direction: ");
direction = input.nextInt();
}
}
//Getter for user-input
public int getDirection() {
return direction;
}
public static void main(String[] args) {
(new BilSpil()).start();
BilSpil spilObject = new BilSpil(); //Create object of extended Thread.
int commands = (spilObject.direction); //Raw command-data for circle
//Game background
int yBg = 10;
CanvasPaint cp = new CanvasPaint(500,500);
cp.setBackground(Color.black);
for(int i = 0; i<50; i++) {
cp.setColor(Color.DARK_GRAY);
cp.paintLine(yBg, 500, yBg, 0); //Y-streger
cp.paintLine(500, yBg, 0, yBg); //X-streger
yBg += 10;
}
boolean gameIsLive = true;
int x = 245;
int y = 245;
cp.setColor(Color.CYAN);
cp.paintOval(x, y, 5, 5);
while(gameIsLive) { //Second while-loop, moving the circle
while(commands == 2) { //Down direction
cp.paintOval(x, y+10, 5, 5);
y += 10;
try{Thread.sleep(1000);}
catch (InterruptedException e) {}
cp.repaintFrame();
}
while(commands == 4) { //Left direction
cp.paintOval(x-10, y, 5, 5);
x -= 10;
try{Thread.sleep(1000);}
catch (InterruptedException e) {}
cp.repaintFrame();
}
while(commands == 8) { //UP direction
cp.paintOval(x, y-10, 5, 5);
y-= 10;
try{Thread.sleep(1000);}
catch (InterruptedException e) {}
cp.repaintFrame();
}
while(commands == 6) { //RIGHT direction
cp.paintOval(x+10, y, 5, 5);
x += 10;
try{Thread.sleep(1000);}
catch (InterruptedException e) {}
cp.repaintFrame();
}
}
}
}