私は CanvasPaint ライブラリをいじっていましたが、ユーザー入力に基づいて円を動かすことができる素敵な小さなゲームを作りたいと思っています。
私のアプローチは、同時に実行される 2 つの While ループを作成することです。1 つはユーザーからの新しい入力を探し、2 番目は円を移動します。
この種のコードを投稿した経験がなくて申し訳ありませんが、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();
}
}
}
}