【发布时间】:2016-05-10 10:26:49
【问题描述】:
我想用 Java 编写蛇游戏代码并处理 IT 类,因为我不知道怎么做,所以我搜索了一个 YouTube 教程。现在我确实找到了一个,但他使用键'w','s','d','a'来移动蛇 - 另一方面我想使用箭头键。有人可以向我解释一下我如何转换这段代码:
if (keyPressed == true) {
int newdir = key=='s' ? 0 : (key=='w' ? 1 : (key=='d' ? 2 : (key=='a' ? 3 : -1)));
}
if(newdir != -1 && (x.size() <= 1 || !(x.get(1) ==x.get(0) + dx[newdir] && y.get (1) == y.get(0) + dy[newdir]))) dir = newdir;
}
变成这样:
void keyPressed () {
if (key == CODED) {
if (keyCode == UP) {}
else if (keyCode == RIGHT) {}
else if (keyCode == DOWN) {}
else if (keyCode == LEFT) {}
}
这是我到目前为止的全部代码:
ArrayList<Integer> x = new ArrayList<Integer> (), y = new ArrayList<Integer> ();
int w = 900, h = 900, bs = 20, dir = 1; // w = width ; h = height ; bs = blocksize ; dir = 2 --> so that the snake goes up when it starts
int[] dx = {0,0,1,-1} , dy = {1,-1,0,0};// down, up, right, left
void setup () {
size (900,900); // the 'playing field' is going to be 900x900px big
// the snake starts off on x = 5 and y = 30
x.add(5);
y.add(30);
}
void draw() {
//white background
background (255);
//
// grid
// vertical lines ; the lines are only drawn if they are smaller than 'w'
// the operator ++ increases the value 'l = 0' by 1
//
for(int l = 0 ; l < w; l++) line (l*bs, 0, l*bs, height);
//
// horizontal lines ; the lines are only drawn if they are smaller than 'h'
// the operator ++ increases the value 'l = 0' by 1
//
for(int l = 0 ; l < h; l++) line (0, l*bs, width, l*bs);
//
// snake
for (int l = 0 ; l < x.size() ; l++) {
fill (0,255,0); // the snake is going to be green
rect (x.get(l)*bs, y.get(l)*bs, bs, bs);
}
if(frameCount%5==0) { // will check it every 1/12 of a second -- will check it every 5 frames at a frameRate = 60
// adding points
x.add (0,x.get(0) + dx[dir]); // will add a new point x in the chosen direction
y.add (0,y.get(0) + dy[dir]); // will add a new point y in the chosen direction
// removing points
x.remove(x.size()-1); // will remove the previous point x
y.remove(y.size()-1); // will remove the previous point y
}
}
【问题讨论】:
-
您的代码中没有任何内容显示与击键的任何集成。到目前为止,您是否在代码中做过任何事情来捕获击键?您需要为您的 GUI 显示相关代码
-
这是一个 GUI 程序 (SWING/SWT) 还是一个控制台程序?如果是控制台程序读取箭头比较复杂:stackoverflow.com/questions/9545388/…
-
@pczeus 是的 - 显然我忘了添加它我添加了 int key, keyCode;
-
@gfelisberto 它是一个图形用户界面。只是交给我的老师没什么花哨的
标签: processing