2017-01-14 19 views
0

Я делаю охоту за сокровищами на сменной сетке 8 x 8, 10 x 10 или 12 x 12 как часть задания для школы, и мне нужна помощь. Всякий раз, когда я делаю движение по сетке, он не всегда переходит в нужное положение. Может ли кто-нибудь помочь мне или объяснить мне, почему это не работает?Неправильное размещение маркера в 2D-сетке

Код, приведенный ниже, является тем, что у меня есть.

def makeMove(): 
    global board, numberOfMoves, tokenBoard, playerScore, tokenBoard 
    playerCoords = getPlayerPosition() 
    currentRow = playerCoords[0] #sets var to playerCoords[0] 
    currentCol = playerCoords[1] #sets var to playerCoords[1] 

    directionUD = input("Up/Down?") #sets var to the input of "Up/down?" 
    movement_col = int(input("How many places?")) 
    if directionUD == "u": #checks if var equals "u" 
     newCol = currentCol - movement_col 
     print (newCol) 
    elif directionUD =="d": #checks if var equals "d" 
     newCol = currentCol + movement_col 

    directionLR = input("Left/Right?") #sets var to the input of "Up/down?" 
    movement_row = int(input("How many places?")) 
    if directionLR == "l": #checks if var equals "l" 
    newRow = currentRow - movement_row 
    print(newRow) 
    elif directionLR == "r": #checks if var equals "r" 
    newRow = currentRow + movement_row 
    print(newRow) 

    calculatePoints(newCol, newRow) #calls the calculatePoints function 

    if newCol > gridSize or newRow > gridSize: 
    print("That move will place you outside of the grid. Please try again.") 


    board[newCol][newRow] = "X" #sets the new position to "X" 
    board[currentRow][currentCol] = "-" 
    numberOfMoves = numberOfMoves + 1 #adds 1 to the numberOfMoves 
    displayBoard() #calls the displayBoard function 
+1

От только визуального контроля текущий код, ничего не выскакивает как явно неправильно (есть место для улучшения, но ничего, кажется, приводит к непредсказуемому поведению). Можете ли вы включить код или «вычислить очки» и уточнить, «он не всегда переходит в нужную позицию»? – Tagc

+0

Ваш комментарий '#sets var на вкладке« Вверх/вниз? »' Дублируется, кстати. Второй раз для «Влево/Вправо». – Tagc

+0

Также ваше условие 'if newCol> gridSize или newRow> gridSize:' должно использовать '> =' не так ли? Он также должен возвращать или возбуждать исключение. – Tagc

ответ

0

Хорошо, я чувствую себя идиотом. Мне потребовалось воспроизвести вашу работу с нуля, прежде чем я заметил проблему - я запутываю столбцы с рядами. Я думаю, это может быть и ваша проблема.

В вашей игре, вы должны определить, горизонтального движения вашего игрока («Left/Right?») Путем изменения тока колонок и вертикального движения игрока («вверх/вниз?») Путем изменения в настоящее время ряд.

Это происходит потому, что, когда вы определяете значение для newRow, отличающуюся от currentRow, вы двигаетесь через строки, а не вдоль им. Аналогичная логика применяется для столбцов.

Вот мой код ниже для справки:

def create_board(size): 
    return [['_' for _ in range(size)] for _ in range(size)] 


def print_board(board): 
    for row in board: 
     print(row) 


def get_board_dimensions(board): 
    # PRE: board has at least one row and column 
    return len(board), len(board[0]) 


def make_move(board, player_position): 
    def query_user_for_movement(): 
     while True: 
      try: 
       return int(input('How many places? ')) 
      except ValueError: 
       continue 

    def query_user_for_direction(query, *valid_directions): 
     while True: 
      direction = input(query) 
      if direction in valid_directions: 
       return direction 

    vertical_direction = query_user_for_direction('Up/Down? ', 'u', 'd') 
    vertical_displacement = query_user_for_movement() 
    horizontal_direction = query_user_for_direction('Left/Right? ', 'l', 'r') 
    horizontal_displacement = query_user_for_movement() 

    curr_row, curr_column = player_position 
    new_row = curr_row + vertical_displacement * (1 if vertical_direction == 'd' else -1) 
    new_column = curr_column + horizontal_displacement * (1 if horizontal_direction == 'r' else -1) 

    width, height = get_board_dimensions(board) 

    if not (0 <= new_row < height): 
     raise ValueError('Cannot move to row {} on board with height {}'.format(new_row, height)) 
    elif not (0 <= new_column < width): 
     raise ValueError('Cannot move to column {} on board with width {}'.format(new_column, width)) 

    board[curr_row][curr_column] = '_' 
    board[new_row][new_column] = 'X' 

    return board 


if __name__ == '__main__': 
    # Set up an 8 x 8 board with the player at a specific location 
    board_size = 8 
    player_position = (1, 2) 
    board = create_board(board_size) 
    board[player_position[0]][player_position[1]] = 'X' 
    print('Initialised board with size {} and player at ({}, {})'.format(board_size, *player_position)) 
    print_board(board) 

    # Allow the player to make their move. 
    print('Player, make your move:\n') 
    board = make_move(board, player_position) 

    # Show the new board state 
    print('Board after making move') 
    print_board(board) 

Начало игры

Initialised board with size 8 and player at (1, 2) 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', 'X', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
Player, make your move: 

Перемещение одной плитки вниз

Up/Down? d 
How many places? 1 
Left/Right? r 
How many places? 0 
Board after making move 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', 'X', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 

Moving уплотнительное пе плитка прямо

Up/Down? d 
How many places? 0 
Left/Right? r 
How many places? 1 
Board after making move 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', 'X', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 

Перемещение одной плитки до

Up/Down? u 
How many places? 1 
Left/Right? l 
How many places? 0 
Board after making move 
['_', '_', 'X', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 

Перемещения одна плитки левого

Up/Down? d 
How many places? 0 
Left/Right? l 
How many places? 1 
Board after making move 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', 'X', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 

Перемещения по диагонали вниз и вправо

Up/Down? d 
How many places? 1 
Left/Right? r 
How many places? 1 
Board after making move 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', 'X', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 
['_', '_', '_', '_', '_', '_', '_', '_'] 

Создание незаконного перемещения

Up/Down? u 
How many places? 3 
Left/Right? r 
How many places? 0 
Traceback (most recent call last): 
    File "C:/Users/<<me>>/.PyCharmCE2016.3/config/scratches/scratch_2.py", line 62, in <module> 
    board = make_move(board, player_position) 
    File "C:/Users/<<me>>/.PyCharmCE2016.3/config/scratches/scratch_2.py", line 41, in make_move 
    raise ValueError('Cannot move to row {} on board with height {}'.format(new_row, height)) 
ValueError: Cannot move to row -2 on board with height 8