You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据用户输入方向在二维网格中更新X的位置

Solution to Move 'X' in the Grid Based on Direction Input

Let's break down how to add the movement functionality to your existing grid code. Here's a step-by-step implementation with explanations that’s easy to follow:

Step 1: Locate the Current Position of 'X'

First, we need a way to find where the 'X' is sitting in the grid before processing any movement. We can loop through each row and column to grab its coordinates:

def find_x_position(grid):
    for row_idx in range(len(grid)):
        for col_idx in range(len(grid[row_idx])):
            if grid[row_idx][col_idx] == 'X':
                return (row_idx, col_idx)
    # This line is a fallback (shouldn't trigger in your setup)
    return (-1, -1)

Step 2: Parse Direction Input & Calculate New Position

Next, we’ll take the user’s direction input, compute the new coordinates, and stick to common direction terms like up, down, left, right (you can swap these for key presses like w/s/a/d later if needed):

# Get where 'X' is right now
current_row, current_col = find_x_position(x)

new_row, new_col = current_row, current_col
valid_direction = True

# Adjust coordinates based on input
if d.lower() == 'up':
    new_row = current_row - 1
elif d.lower() == 'down':
    new_row = current_row + 1
elif d.lower() == 'left':
    new_col = current_col - 1
elif d.lower() == 'right':
    new_col = current_col + 1
else:
    print("Oops, that's not a valid direction! Use up/down/left/right.")
    valid_direction = False

Step 3: Enforce Grid Boundaries & Update the Grid

We need to make sure the new position doesn’t take 'X' outside the grid. If it’s a valid move, we’ll update the grid by resetting the old position to . and placing 'X' in the new spot:

if valid_direction:
    # Check if new position is within grid limits
    if 0 <= new_row < grid and 0 <= new_col < grid:
        # Move the 'X'
        x[current_row][current_col] = '.'
        x[new_row][new_col] = 'X'
        # Print the updated grid
        print("\nUpdated Grid:")
        for row in x:
            print(*row)
    else:
        print("\nCan't move that way—you'll go outside the grid!")

Full Integrated Code

Here’s the complete working version combined with your original grid setup:

grid = int(input("Grid size: "))
x = []
for i in range(grid):
    y = []
    for j in range(grid):
        e = '.'
        y.append(e)
    x.append(y)
x[0][0] = 'X'

# Function to find 'X' position
def find_x_position(grid):
    for row_idx in range(len(grid)):
        for col_idx in range(len(grid[row_idx])):
            if grid[row_idx][col_idx] == 'X':
                return (row_idx, col_idx)
    return (-1, -1)

# Print initial grid
print("Initial Grid:")
for row in x:
    print(*row)

d = input("Direction (up/down/left/right): ")

# Get current position
current_row, current_col = find_x_position(x)

# Calculate new position
new_row, new_col = current_row, current_col
valid_direction = True
if d.lower() == 'up':
    new_row = current_row - 1
elif d.lower() == 'down':
    new_row = current_row + 1
elif d.lower() == 'left':
    new_col = current_col - 1
elif d.lower() == 'right':
    new_col = current_col + 1
else:
    print("Invalid direction! Please use up/down/left/right.")
    valid_direction = False

# Update grid if valid
if valid_direction:
    if 0 <= new_row < grid and 0 <= new_col < grid:
        x[current_row][current_col] = '.'
        x[new_row][new_col] = 'X'
        print("\nUpdated Grid:")
        for row in x:
            print(*row)
    else:
        print("\nMovement blocked: Can't go outside the grid!")

Quick Notes

  • Case Insensitivity: Using d.lower() means inputs like Up or RIGHT will work just fine.
  • Error Prevention: The boundary check stops you from getting index errors when trying to move outside the grid.
  • Clear Feedback: The code tells you if you enter a bad direction or try to move out of bounds.

内容的提问来源于stack exchange,提问作者user9644262

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:41:47