2016-12-06 2 views
0

저는 파이썬에서 초보자이며 플레이어가 왼쪽/오른쪽으로 이동하려는 곳의 수를 입력하는 보드 게임을 만들고 있습니다. 그러나 때로는 올바르게 움직이고 때로는 움직이지 않는 경우도 있습니다. 내 격자 배열과 관련이 있다고 생각하지만 확실하지 않습니다 ... 누군가가 나를 도울 수 있다면 좋을 것입니다, 감사합니다! 나는 내 문제와 프로그램이 명확하게 포함하는 부품 모르겠어요으로 사용자가 그리드를 탈출하지 않도록 내가 검증을 포함한 모든 내 코드를 첨부왜 내 배열 편집이 제대로 작동하지 않습니까?

choice=0 
b=0 
oldP=0 
newP=0 
player_location='X' 
x=8 
y=0 
xi=0 
yi=0 
up=0 
down=0 
left=0 
right=0 
new_board=[xi][yi] 
gold_coins=0 
bandits=5 
treasure_chests=10 
a=1 
xi2=0 
yi2=0 

import random 
def menu(): 
    print('If you would like to play the Treasure Hunt , press 1') 
    choice=input('If not, press any key to exit') 
    if choice=='1': 
     print('Great! You have made the right choice :)') 
    else: 
     print('Goodbye.') 
     quit() 
menu() 
def grid(): 
    new_board = [ ] 

def board(): 
    new_board = [ ] 
    top_row = [' 1 ',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ',' 8 '] 

    new_board.append(top_row) 

    for x in range(0,8): 
    row = [' 0 ']*8 
    new_board.append(row) 
    return new_board 

def print_board(b): 
    row_letters = [' ','A','B','C','D','E','F','G','H'] 
    i = 0 
    for row in b: 
    print (row_letters[i],''.join(row)) 
    i=i+1 
new_board = board() 
xi=int(8) 
yi=int(0) 
new_board[xi][yi] = player_location 
print_board(new_board) 
while a==1: 
    upordown=input('Would you like to move up or down? Enter \'u\' for up or \'d\' for down.').lower() 
    upordown=upordown.lower() 
    while not (upordown== 'u' or upordown== 'd'): 
     print('Invalid input. Please try again') 
     upordown= input().lower() 
    while upordown=='u': 
     try: 
      up=int(input('How many spaces would you like to move up?')) 
      b=0 
     except: 
      print('This is not a valid input, please enter a number.') 
      b=1 
     if b==0: 
      break 
    while upordown=='d': 
     try: 
      down=int(input('How many spaces would you like to move down?')) 
      b=0 
     except: 
      print('This is not a valid input, please enter a number.') 
      b=1 
     if b==0: 
      break 
    leftorright=input('Would you like to move left or right Enter \'l\' for left or \'r\' for right.').lower() 
    leftorright.lower() 
    while not (leftorright== 'l' or leftorright== 'r'): 
     print('Invalid input. Please try again') 
     leftorright= input().lower() 
    while leftorright=='l': 
     try: 
      left=int(input('How many spaces would you like to move left?')) 
      b=0 
     except: 
      print('This is not a valid input, please enter a number.') 
      b=1 
     if b==0: 
      break  
    while leftorright=='r': 
     try: 
      right=int(input('How many spaces would you like to move right?')) 
      b=0 
     except: 
      print('This is not a valid input, please enter a number.') 
      b=1 
     if b==0: 
      break 
    print('Okay...') 

    grid() 
    while True: 
     board() 
     player_location=' X ' 
     if upordown=='d' and leftorright=='l': 
      new_board[y-down][x-left] = player_location 
      new_board = board() 
      xi2=int(xi2-left) 
      yi2=int(yi2-down) 
      print ("The current x location is",xi) 
      print ("The current y location is",yi) 
      print ("The amount you chose to go down was",down) 
      print ("The amount you chose to go right was",left) 
      xi = int(xi+left) 
      print("The new x location is",xi2) 
      yi = int(yi+down) 
      print("The new y location is",yi2) 
      print(' ') 
      while 0>xi2 or xi2>8 or 0>yi2 or yi2>8: 
       print('Your move was illegal. Please enter a move that will position you within the grid') 
       left=int(input('Please enter the number of moves you would like to move right')) 
       down=int(input('Please enter the number of moves you would like to move up.')) 
       xi=int(xi+left) 
       yi=int(yi+down) 
      new_board[xi][yi] = player_location 
      print_board(new_board) 
      break 
     elif upordown=='d' and leftorright=='r': 
      new_board = board() 
      xi2=int(xi2+right) 
      yi2=int(yi2-down) 
      print ("The current x location is",xi) 
      print ("The current y location is",yi) 
      print ("The amount you chose to go down was",down) 
      print ("The amount you chose to go right was",right) 
      xi = int(xi+right) 
      print("The new x location is",xi2) 
      yi = int(yi+down) 
      print("The new y location is",yi2) 
      print(' ') 
      while 0>xi2 or xi2>8 or 0>yi2 or yi2>8: 
       print('Your move was illegal. Please enter a move that will position you within the grid') 
       right=int(input('Please enter the number of moves you would like to move right')) 
       down=int(input('Please enter the number of moves you would like to move down.')) 
       xi=int(xi+right) 
       yi=int(yi+down) 
      new_board[xi][yi] = player_location 
      print_board(new_board) 
      break 
     elif upordown=='u' and leftorright=='l': 
      new_board = board() 
      xi2=int(xi2+left) 
      yi2=int(yi2-up) 
      print ("The current x location is",xi) 
      print ("The current y location is",yi) 
      print ("The amount you chose to go up was",up) 
      print ("The amount you chose to go left was",left) 
      xi = int(xi+left) 
      print("The new x location is",xi2) 
      yi = int(yi-up) 
      print("The new y location is",yi2) 
      print(' ') 
      while 0>xi2 or xi2>8 or 0>yi2 or yi2>8: 
       print('Your move was illegal. Please enter a move that will position you within the grid') 
       left=int(input('Please enter the number of moves you would like to move right')) 
       up=int(input('Please enter the number of moves you would like to move up.')) 
       xi=int(xi-left) 
       yi=int(yi-up) 
      new_board[xi][yi] = player_location 
      print_board(new_board) 
      break 
     elif upordown=='u' and leftorright=='r': 
      new_board = board() 
      xi2=int(xi2+right) 
      yi2=int(yi2+up) 
      print ("The current x location is",xi) 
      print ("The current y location is",yi) 
      print ("The amount you chose to go up was",up) 
      print ("The amount you chose to go right was",right) 
      xi = int(xi-right) 
      print("The new x location is",xi2) 
      yi = int(yi+up) 
      print("The new y location is",yi2) 
      print(' ') 
      while 0>xi2 or xi2>8 or 0>yi2 or yi2>8: 
       print('Your move was illegal. Please enter a move that will position you within the grid') 
       right=int(input('Please enter the number of moves you would like to move right')) 
       up=int(input('Please enter the number of moves you would like to move up.')) 
       xi=int(xi-right) 
       yi=int(yi-up) 
      new_board[xi][yi] = player_location 
      print_board(new_board) 
      break 

.

+1

_ "저는 파이썬에서 초보자입니다."- _ 그만해! 몇 걸음 뒤로 물러서 야합니다. 이런 프로젝트는 초보자가해야 할 일이 아닙니다. tic-tac-toe 제작과 같은 것을 시도한 다음 위로 이동하십시오. –

+0

@leaf 확실히 사실이지만 조금 모험적입니다! 그러나 나는 이것을 웹 사이트에서 초보자가하는 도전으로 보았고 실제로 그것을 끝내기를 원했습니다. – user5095215

+0

"초보자"를 정의하십시오. _Just Python_을 다운로드하거나 _I에서 몇 달 동안 Python을 사용하고있는 초보자를 의미합니다. 바로 지금 당신의 코드에서 볼 수있는 가장 큰 문제점은 매우 장황하다는 것입니다. –

답변

2

연습 개선 :

난 강력하게 증분 프로그래밍을 추천 here

을 디버깅 할 수있는 멋진 소개있다 : 물론 그들이 작동하도록, 당신은 몇 줄을 작성하고 당신이있을 때까지 계속하지 않는이 기존 코드가 정확합니다. 그렇게하면 무언가가 작동하지 않을 때, 당신이 추가 한 마지막 몇 라인에 있음을 알 수 있습니다. 그렇지 않으면 200 줄의 코드가 생기고 오류가있는 곳을 알 수 없습니다.

프로그램이 코드는 디버깅 또는 유지 보수를 위해 설계되지 않은

변경; 계속하기 전에 이러한 문제를 해결해야합니다. 무엇보다도 하나의 작업 (사용자 이동)을 수행하는 두 세트의 입력과 동일한 작업을 수행하는 네 개의 코드 블록 (사용자 이동)을 작성했습니다.

대신 플레이어가 행에 이동을 입력하게하는 유용한 문구를 찾으십시오. 이를 "1과 2의 위쪽으로"[1, -2]와 같은 이동 좌표로 변환 한 다음 단일 코드 블록을 사용하여 격자를 통해 이동합니다. 네 개의 코드 블록을 테스트하는 대신 하나를 테스트합니다. 변경할 필요가있을 때 하나를으로 변경하고 회전 및 반사 아래에 4 개의 복사본을 만들지 마십시오.

결과 당신이 살고있는 코드는 더 다음과 같아야합니다

def get_move(): 
    advice = "Please enter your move in two integers:\n" + 
       "vertical, then horizontal. Use positive numbers\n" + 
       "for up and right, negative for down and left.\n" 
    example = "For instance, the line \n\t2 -1\n" + 
       " is 2 spaces up, one space left." 
    move = input(advice + example).split 
    x_move = int(move[0]) 
    y_move = int(move[1]) 
    # Here, you check move legality; repeat until you get a legal move 

    return x_move, y_move 

while True: 
    print_board() 
    x_move, y_move = get_move() # get_move contains the input interaction and data checking 
    move(x_move, y_move) # perform the move; update the board. 

는 또한 당신은 아마 오히려 모든 움직임에 대한 새로운 하나를 만들어 (분명히)보다, 기존의 보드를 업데이트해야합니다 있습니다. 게임이 끝날 때까지이 반복을 계속하십시오. 한 번에 탈출하지 마라.

당신을 솔루션으로 이끌어 갈 수 있습니까?

+0

조언과 조언에 감사드립니다. 나는 디버깅에 대한 소개를 확실히 읽을 것이고, 이것은 분명히 나를 해결책으로 이끌었다! – user5095215

+0

좋아요. 결의안을 작성할 때 여기서 직접 돌아와 도움이되는 사항에 대해 투표를하고 답변을 수락해야합니다. 그게 스택 오버 플로우가 제대로 은퇴하고 질문 보관할 수 있습니다. – Prune

관련 문제