记忆翻牌游戏java
时间: 2024-05-30 22:07:26 浏览: 20
记忆翻牌游戏是一种常见的益智游戏,玩家需要在有限时间内翻开所有的卡片并找到相同的卡片配对。以下是一个简单的记忆翻牌游戏的Java实现:
```
import java.util.*;
public class MemoryGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int size, numPairs, guess1, guess2, count = 0;
boolean gameOver = false;
System.out.print("Enter the size of the board (even number): ");
size = input.nextInt();
numPairs = size*size/2;
int[] board = new int[size*size];
for (int i = 0; i < numPairs; i++) {
board[2*i] = i+1;
board[2*i+1] = i+1;
}
shuffle(board);
while (!gameOver) {
drawBoard(board);
System.out.print("Enter the first card to guess: ");
guess1 = input.nextInt()-1;
System.out.print("Enter the second card to guess: ");
guess2 = input.nextInt()-1;
if (board[guess1] == board[guess2]) {
board[guess1] = 0;
board[guess2] = 0;
count += 2;
} else {
System.out.println("Not a match!");
}
if (count == size*size) {
gameOver = true;
System.out.println("Congratulations, you won!");
}
}
}
public static void shuffle(int[] arr) {
Random rand = new Random();
for (int i = 0; i < arr.length; i++) {
int j = rand.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public static void drawBoard(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
System.out.print("[ ]");
} else {
System.out.print("["+arr[i]+"]");
}
if ((i+1) % Math.sqrt(arr.length) == 0) {
System.out.println();
}
}
}
}
```
该实现使用了一个一维数组来表示卡片,其中每个元素都是卡片上的数字,相同的数字表示一对卡片。`shuffle`方法用于随机打乱数组顺序,`drawBoard`方法用于绘制当前卡片状态的矩阵。在主函数中,程序通过不断读入用户猜测的卡片位置并与之前猜测的位置进行比较,如果两个位置的卡片数字相同则表示猜对了一对,并将这两张卡片从矩阵中删除。当所有卡片都被删除后,游戏结束。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)