我正在制作一個小游戲,其中 Player 物件能夠圍繞其他物件的 2x2 矩陣移動(在此背景關系中為 DreamObjects)。玩家可以移動到空間物體上。稍后我將實作其他物件;但都擴展了父 DreamObject。現在,要實作我的 Player 的移動,我必須始終檢查它前面的物件是否是某個物件的實體。在下面顯示的代碼中,對于玩家打算移動的每個方向,我檢查物件是否有一個 Space 實體;如果是,我會交換他們的位置并更新世界。將來我會添加怪物、靜止物體等。我遇到的問題是我會重復很多代碼,唯一的區別是我如何根據移動方向對行和列應用算術。我正在考慮應用 Generic 類,但我沒有看到實作,因為每個方向列舉的操作都不同。你怎么認為?有沒有更好的方法我沒有看到?
//returns location as [row, col]
int[] tempLocation = player.getObjectLocation();
switch (direction){
case NORTH -> {
if (getObjectAt(tempLocation[0] - 1, tempLocation[1]) instanceof Space){
this.world[tempLocation[0]][tempLocation[1]] = new Space(player.getDreamLocation());
this.world[tempLocation[0]-1][tempLocation[1]] = player;
player.changeDreamLocation(-1,0);
}
}
case EAST -> {
if (getObjectAt(tempLocation[0], tempLocation[1] 1) instanceof Space){
this.world[tempLocation[0]][tempLocation[1]] = new Space(player.getDreamLocation());
this.world[tempLocation[0]][tempLocation[1] 1] = player;
player.changeDreamLocation(0,1);
}
}
case SOUTH -> {
if (getObjectAt(tempLocation[0] 1, tempLocation[1]) instanceof Space){
this.world[tempLocation[0]][tempLocation[1]] = new Space(player.getDreamLocation());
this.world[tempLocation[0] 1][tempLocation[1]] = player;
player.changeDreamLocation(1,0);
}
}
case WEST -> {
if (getObjectAt(tempLocation[0], tempLocation[1] - 1) instanceof Space){
this.world[tempLocation[0]][tempLocation[1]] = new Space(player.getDreamLocation());
this.world[tempLocation[0]][tempLocation[1] - 1] = player;
player.changeDreamLocation(0,-1);
}
}
}
uj5u.com熱心網友回復:
我會只提取開關中的索引,并將其他所有內容放在通用方法中。您必須為 playerX/playerY 和 dreamLocationX/dreamLocationY 定義有效的初始值:
//returns location as [row, col]
int[] tempLocation = player.getObjectLocation();
int playerX = -1;
int playerY = -1;
int dreamLocationX = -1;
int dreamLocationY = -1;
switch (direction) {
case NORTH:
playerX = tempLocation[0] - 1;
playerY = tempLocation[1];
dreamLocationX = -1;
dreamLocationY = 0;
break;
case EAST:
playerX = tempLocation[0];
playerY = tempLocation[1] 1;
dreamLocationX = 0;
dreamLocationY = 1;
break;
case SOUTH:
playerX = tempLocation[0] 1;
playerY = tempLocation[1];
dreamLocationX = 1;
dreamLocationY = 0;
break;
case WEST:
playerX = tempLocation[0];
playerY = tempLocation[1] - 1;
dreamLocationX = 0;
dreamLocationY = -1;
break;
}
if (getObjectAt(playerX, playerY) instanceof Space) {
this.world[tempLocation[0]][tempLocation[1]] = new Space(player.getDreamLocation());
this.world[playerX][playerY] = player;
player.changeDreamLocation(dreamLocationX, dreamLocationY);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362162.html
