2014-10-10 2 views
0

사용자가 (x, y) 격자에서 '보물'을 찾아야하고 올바른 (x, y) 값에 도달 할 때까지 프로그램이 반복되도록이 프로그램을 설계하고 싶습니다. 루프 설계 방법을 찾는 데 도움이 필요합니다.특정 값의 조합에 도달 할 때까지 프로그램을 반복 시키려면 어떻게합니까?

question = (input("Where do you want to go?: ")); 
y = 0 
x = 0 
if question in ["up"]: 
    y = y + 1 
    print("You've moved up one unit!") 
    print("Your position is now ", x, y) 

if question in ["down"]: 
    y = y - 1 
    print("You've moved down one unit!") 
    print("Your position is now ", x, y) 

if question in ["right"]: 
    x = x + 1 
    print("You've moved right one unit!") 
    print("Your position is now ", x, y) 

if question in ["left"]: 
    y = y + 1 
    print("You've moved left one unit!") 
    print("Your position is now ", x, y)  

else: 
    print("You can't go there.") 
+0

https://docs.python.org/3/tutorial/introduction.html#first-steps-towards-programming – jonrsharpe

답변

0

시작 힌트 :

treasure_spot = (<somex>, <somey>) 
x = y = 0 
while (x, y) != treasure_spot: 
    <move> 

훨씬 확대 대답 (파이썬 3) 의견에 응답했다. 이것으로부터 몇 가지 배울 점이 있습니다. 이해하는데 어려움이 있다면, CPython 튜토리얼을 읽으십시오.

from random import randint 

maxy = 2 
X = randint(0, maxy) 
Y = randint(0, maxy) 
x,y = maxy//2, maxy//2 # start in middle, 0,0 is upper left 

directions = { # dir: (direction, (deltax, deltay)) 
    'u' : ('up', (0, -1)), 
    'ur': ('up right', (1, -1)), 
    'r' : ('right', (1, 0)), 
    'dr': ('down right', (1, 1)), 
    'd' : ('down', (0, 1)), 
    'dl': ('down left', (-1, 1)), 
    'l' : ('left', (-1, 0)), 
    'ul': ('up left', (-1, -1)), 
    'q' : ('quit',()) 
    } 
print("Your start in the middle of an {0} by {0} field.".format(maxy+1)) 
print("Move around to find the treasure. Here are the moves.") 
print("move meaning") 
for move in ('u', 'ur', 'r', 'dr', 'd', 'dl', 'l', 'ul'): 
    print("{:4s} {}".format(move, directions[move][0])) 

while x != X or y != Y: 
    move = input("You are as {:d}, {:d}. Your move? ".format(x, y)) 
    if move == 'q': 
     break 
    try: 
     dx, dy = directions[move][1] 
    except KeyError: 
     print("Not a legal move.") 
     continue 
    newx, newy = x+dx, y+dy 
    if not (0 <= newx <= maxy and 0 <= newy <= maxy): 
     print("You ran into a fence!") 
     continue 
    x, y = newx, newy 

if move != 'q': 
    print("You found the treasure at {:d},{:d}.".format(X, Y)) 
else: 
    print("Bye, treasure is at {:d},{:d}.".format(X, Y)) 
+0

이 질문에 대한 답을 제공하지 않습니다. 비평하거나 저자의 설명을 요청하려면 게시물 아래에 의견을 남겨 둡니다. –

+0

Fiaom이 '루프 디자인 방법'을 물었습니다. 위의 내용은 저의 골격입니다. 나는 Fiaom으로두고 을 초기 코드로 대체했다. 단, x와 y의 초기화를 루프에서 빠져 나가는 것을 제외하고는. –

+0

이 의미하는 바를 자세히 설명해 주시겠습니까? 저는 파이썬에 대해 매우 익숙합니다. 따라서 구문에 대한 지식은 최소한으로 남아 있습니다. 나는 어리석은 질문에 사과한다. – Flaom

관련 문제