Java蛇和梯子是一種常見的經典游戲。它有一個棋盤,玩家需要控制一條蛇走到終點,中途會有一些障礙物,其中包括梯子,可以幫助玩家快速到達終點。這個游戲是用Java語言編寫的,下面我們就來看一下Java蛇和梯子的代碼實現吧。
import java.util.Scanner; import java.util.ArrayList; public class SnakeAndLadderGame { static int[][] board = new int[10][10]; static ArrayListladders = new ArrayList<>(); public static void main(String[] args) { initBoard(); initLadders(); Scanner sc = new Scanner(System.in); int player = 1; int currPos = 0; while (true) { System.out.println("Player " + player + ", enter your roll: "); int roll = sc.nextInt(); currPos += roll; if (currPos >= 100) { System.out.println("Player " + player + " wins!"); break; } currPos = checkLadder(currPos); currPos = checkSnake(currPos); System.out.println("Player " + player + " is at " + currPos); if (roll != 6) { player = (player == 1) ? 2 : 1; } } } public static void initBoard() { int counter = 100; for (int i = 0; i< 10; i++) { for (int j = 0; j< 10; j++) { board[i][j] = counter; counter--; } } } public static void initLadders() { ladders.add(14); ladders.add(31); ladders.add(42); ladders.add(69); ladders.add(84); } public static int checkLadder(int currPos) { int newPos = currPos; for (int i = 0; i< ladders.size(); i++) { if (currPos == ladders.get(i)) { newPos = (100 - ladders.get(i+1)); } } return newPos; } public static int checkSnake(int currPos) { int newPos = currPos; if (currPos == 17) { newPos = 7; } else if (currPos == 54) { newPos = 34; } else if (currPos == 62) { newPos = 19; } else if (currPos == 64) { newPos = 60; } else if (currPos == 87) { newPos = 36; } else if (currPos == 93) { newPos = 73; } else if (currPos == 95) { newPos = 75; } else if (currPos == 98) { newPos = 79; } return newPos; } }