汉诺塔java小游戏完整源代码
时间: 2023-06-23 12:26:50 浏览: 199
下面是一个简单的汉诺塔Java小游戏的完整源代码:
```
import java.util.Scanner;
public class HanoiTower {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入汉诺塔的层数:");
int n = scanner.nextInt();
hanoi(n, 'A', 'B', 'C');
}
public static void hanoi(int n, char a, char b, char c) {
if (n == 1) {
System.out.println("将第1个盘子从" + a + "移动到" + c);
} else {
hanoi(n - 1, a, c, b);
System.out.println("将第" + n + "个盘子从" + a + "移动到" + c);
hanoi(n - 1, b, a, c);
}
}
}
```
运行程序后,输入汉诺塔的层数,即可输出移动的步骤。
相关问题
汉诺塔java小游戏全部源代码
下面是一个汉诺塔Java小游戏的完整源代码,包含了用户交互界面和游戏逻辑:
```
import java.util.Scanner;
public class HanoiTowerGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来到汉诺塔小游戏!");
System.out.println("请输入汉诺塔的层数:");
int n = scanner.nextInt();
HanoiTower hanoiTower = new HanoiTower(n);
boolean isGameOver = false;
while (!isGameOver) {
hanoiTower.show();
System.out.println("请输入要移动的盘子的起始柱子和目标柱子(例如:A->B):");
String input = scanner.next();
String[] inputArray = input.split("->");
if (inputArray.length != 2) {
System.out.println("输入有误,请重新输入!");
continue;
}
char from = inputArray[0].charAt(0);
char to = inputArray[1].charAt(0);
if (from < 'A' || from > 'C' || to < 'A' || to > 'C') {
System.out.println("柱子的编号只能是 A、B、C,请重新输入!");
continue;
}
if (!hanoiTower.move(from, to)) {
System.out.println("移动失败,请重新输入!");
continue;
}
if (hanoiTower.isGameOver()) {
isGameOver = true;
System.out.println("恭喜你成功完成游戏!");
}
}
}
}
class HanoiTower {
private int n;
private int[] towers[];
public HanoiTower(int n) {
this.n = n;
towers = new int[3][n];
for (int i = 0; i < n; i++) {
towers[0][i] = n - i;
}
}
public boolean move(char from, char to) {
int fromIndex = from - 'A';
int toIndex = to - 'A';
if (fromIndex < 0 || fromIndex > 2 || toIndex < 0 || toIndex > 2) {
return false;
}
int fromTop = getTop(fromIndex);
if (fromTop == -1) {
return false;
}
int toTop = getTop(toIndex);
if (toTop != -1 && fromTop > toTop) {
return false;
}
towers[fromIndex][fromTop] = 0;
towers[toIndex][toTop + 1] = fromTop + 1;
return true;
}
public boolean isGameOver() {
return towers[2][n - 1] == 1;
}
private int getTop(int index) {
for (int i = n - 1; i >= 0; i--) {
if (towers[index][i] != 0) {
return i;
}
}
return -1;
}
public void show() {
System.out.println("当前汉诺塔的状态:");
for (int i = n - 1; i >= 0; i--) {
System.out.print(towers[0][i] + "\t");
System.out.print(towers[1][i] + "\t");
System.out.println(towers[2][i]);
}
System.out.println("A\tB\tC");
}
}
```
运行程序后,输入汉诺塔的层数,即可开始游戏。玩家需要输入要移动的盘子的起始柱子和目标柱子,例如:A->B。如果输入有误或移动失败,程序会提示重新输入。当所有盘子都移动到第三个柱子上时,游戏结束。
阅读全文