Untitled
unknown
c_cpp
2 years ago
2.7 kB
14
Indexable
#include <stdio.h>
#define MAP_SIZE 5
// 函數以符號初始化地圖
void initializeMap(char map[MAP_SIZE][MAP_SIZE], int playerX, int playerY) {
for (int i = 0; i < MAP_SIZE; i++) {
for (int j = 0; j < MAP_SIZE; j++) {
map[i][j] = '-';
}
}
// 放置玩家在地圖上
map[playerX][playerY] = 'P';
// 放置硬幣在地圖上
map[2][0] = '$';
map[1][3] = '$';
map[4][4] = '$';
}
// 函數顯示地圖
void displayMap(char map[MAP_SIZE][MAP_SIZE]) {
for (int i = 0; i < MAP_SIZE; i++) {
for (int j = 0; j < MAP_SIZE; j++) {
if(j != MAP_SIZE - 1){
printf("%c ", map[i][j]);
}else{
printf("%c", map[i][j]);
}
}
printf("\n");
}
}
// 函數移動玩家在地圖上
void movePlayer(char map[MAP_SIZE][MAP_SIZE], int *playerX, int *playerY, char direction, int steps) {
int newX = *playerX;
int newY = *playerY;
// 根據方向更新新位置
switch (direction) {
case 'w':
newX = (*playerX - steps < 0) ? *playerX : *playerX - steps;
break;
case 's':
newX = (*playerX + steps >= MAP_SIZE) ? *playerX : *playerX + steps;
break;
case 'a':
newY = (*playerY - steps < 0) ? *playerY : *playerY - steps;
break;
case 'd':
newY = (*playerY + steps >= MAP_SIZE) ? *playerY : *playerY + steps;
break;
}
// 在地圖上更新玩家位置
map[*playerX][*playerY] = '-';
*playerX = newX;
*playerY = newY;
map[*playerX][*playerY] = 'P';
}
int main() {
char map[MAP_SIZE][MAP_SIZE];
int playerX, playerY;
// 獲取初始玩家位置
scanf("%d %d", &playerX, &playerY);
// 初始化地圖
initializeMap(map, playerX, playerY);
//displayMap(map);
// 不斷取得使用者輸入直到不輸入為止
char input[10];
while (fgets(input, sizeof(input), stdin) != NULL) {
char direction;
int steps;
if (sscanf(input, "%c %d", &direction, &steps) == 2) {
// 移動玩家
movePlayer(map, &playerX, &playerY, direction, steps);
// 顯示更新後的地圖
//displayMap(map);
}
}
displayMap(map);
// 檢查玩家是否找到錢
if ((playerX == 2 && playerY == 0) || (playerX == 4 && playerY == 4) || (playerX == 1 && playerY == 3)) {
printf("I found it!");
} else {
printf("I didn't find it!");
}
return 0;
}
Editor is loading...
Leave a Comment