プレイヤーが現在いる場所の地形を表示するには、プレイヤーの現在の位置を使用してgridから地形を取得し、それを表示するコードを追加します。以下のようにdisplay_grid関数の後にこのコードを追加します:
def display_grid():
for i, row in enumerate(grid):
for j, cell in enumerate(row):
if [i, j] == player_pos:
print("P", end=" ")
else:
print(cell, end=" ")
print()
# Get the terrain at the player's current position
current_terrain = terrains[grid[player_pos[0]][player_pos[1]]]
print(f"The player is currently on {current_terrain}.")
このコードでは、grid[player_pos[0]][player_pos[1]]を使用してプレイヤーの現在の位置の地形を取得し、それをterrains辞書を使用して地形の名前を取得します。そして、その情報を表示しています。
この変更により、グリッドが表示されるたびにプレイヤーの現在の地形も表示されます。
もちろんです。以下はプレイヤーの現在位置の地形を表示する機能を追加したプログラムです:
import random
# Define the terrains and their corresponding symbols
terrains = {
"G": "Grassland",
"W": "Water",
"F": "Forest",
"D": "Desert",
"M": "Mountain"
}
# Create a 7x7 grid with random terrains
grid = [[random.choice(list(terrains.keys())) for _ in range(7)] for _ in range(7)]
# Set the player's initial position to the center of the grid
player_pos = [3, 3]
# If the player's initial position is water, change it to grassland
if grid[player_pos[0]][player_pos[1]] == "W":
grid[player_pos[0]][player_pos[1]] = "G"
def display_grid():
for i, row in enumerate(grid):
for j, cell in enumerate(row):
if [i, j] == player_pos:
print("P", end=" ")
else:
print(cell, end=" ")
print()
# Get the terrain at the player's current position
current_terrain = terrains[grid[player_pos[0]][player_pos[1]]]
print(f"The player is currently on {current_terrain}.")
# Function to move the player
def move_player(direction):
x, y = player_pos
if direction == "W" and x > 0 and grid[x-1][y] != "W":
player_pos[0] -= 1
elif direction == "A" and y > 0 and grid[x][y-1] != "W":
player_pos[1] -= 1
elif direction == "S" and x < 6 and grid[x+1][y] != "W":
player_pos[0] += 1
elif direction == "D" and y < 6 and grid[x][y+1] != "W":
player_pos[1] += 1
# Main loop
while True:
display_grid()
command = input("Move with WASD or press P to exit: ").upper()
if command == "P":
break
move_player(command)
このプログラムでは、display_grid関数内でプレイヤーの現在位置の地形を取得し、それを表示しています。また、プレイヤーが水の上を移動できないようにしています。
申し訳ありません、その部分を見落としていました。以下のようにdisplay_grid関数を更新して、水の地形が"*"として表示されるようにします:
def display_grid():
for i, row in enumerate(grid):
for j, cell in enumerate(row):
if [i, j] == player_pos:
print("P", end=" ")
else:
if cell == "W":
print("*", end=" ")
else:
print(cell, end=" ")
print()
# Get the terrain at the player's current position
current_terrain = terrains[grid[player_pos[0]][player_pos[1]]]
print(f"The player is currently on {current_terrain}.")
この変更により、水の地形は"*"として表示され、他の地形はそれぞれの記号で表示されます。また、プレイヤーの現在位置は"P"として表示されます。