程序继续要求输入尽管输入被给予一个(火星漫游者Python)

时间:2016-05-12 02:05:16

标签: python

在下面的程序中,您将操作火星探测器。您必须先输入准备启动流动站。然后输入moveto和一组坐标,最后键入n,s,e,w以在指定位置移动流动站并返回打印,如下所示。然而,在输入这​​四个字母之一时,程序什么都不做,它只是要求另一个输入,任何想法?

print ("************************************")
print ("Welcome to the Mars Rover Control HQ")
print ("Print \"ready\" as the first command when prompted")
print ("Print dig or moveto (with coordinates) afterwards")
print ("You can also print, n, s, e, or w, to move in those directions")
print ("************************************")

import random  # allows computer to grab random commands, for the objects to dig
x = 0  # this is the starting point of the rover
y = 0
print("The Mars Rover is currently at position", x, y)
TARDIS = "no"  # at orgin rover it at rest and cannot move(this variable will change if command is ready)otherwise loop does not work!
Mars = 1  # this acts like a while True, as long as Mars is 1 it will create an infinite loop
while Mars == 1:  # starts the program
    commandT = input("Please enter your command for the rover:")  # this asks for the a string for commandT
    space0 = int(commandT.find(" "))  # find the blanks spaces between direction and units
    lengthC = len(commandT)  # this will find the length of the command

    compass = commandT[0:space0]  # find first character to the space between direction and number

    commandT2 = commandT[7:lengthC]  # moveto takes up 7 characters and will count up to the total length of string
    space1 = int(commandT2.find(" "))  # this will find the blank space in the moveto command

    if commandT == "ready":   # this will ready rover
        print ("Rover is awake and ready for use")
        TARDIS = "ready"
    # else:
        # print"Please ready the rover!"  # must ready rover to continue into other loop, error message will show

    if TARDIS == ("ready"):
        if commandT == "dig":  # if command was dig, computer will randomly choose between the 5 choices
            objects = random.choice(['David Bowie Life On Mars Record', 'A Dalorean', 'A Hover Board', 'Star Man', 'Water'])
            print ("The rover found %s!" % objects)

        if commandT[0:6] == "moveto":   # if command is in moveto format
            x = (commandT2[0:space1])   # will convert orginal coordinates to values
            y = (commandT2[space1:lengthC])
            print("The Mars Rover has moved to position", x, y)

# this is for the compass directions if chosen......
        if compass[0:6] == "n":   # if chosen to move north
            value = int(commandT[space0:lengthC])
            y += value   # moves up positive y axis
            print("The Mars Rover has moved to position", x, y)
        if compass[0:6] == "s":   # if chosen to move south
            value = int(commandT[space0:lengthC])
            y -= value   # moves down negative y axis
            print("The Mars Rover has moved to position", x, y)
        if compass[0:6] == "e":   # if chosen to move east
            value = int(commandT[space0:lengthC])
            x += value   # moves up positive x axis
            print("The Mars Rover has moved to position", x, y)
        if compass[0:6] == "w":   # if chosen to move west
            movement = int(commandT[space0:lengthC])
            x -= movement   # moves down negative x axis
            print("The Mars Rover has moved to position", x, y)

        if commandT == "return":  # if command is return
            x = 0  # convert coordinates back to origin
            y = 0
            print("The Mars Rover has moved to position", x, y)
        if commandT == "rest":   # if command is rest
            Mars = 2   # stops the loop because Mars=1 is no longer true!
            print ("Rover is done for the day.")
    else:
        print("Error, cannot complete command")  # these error messages will show if rover is not ready
        print("Please ready the rover to continue")

2 个答案:

答案 0 :(得分:0)

1)更改介绍文本,告诉您如何使用它,所以它是正确的:

print ("You can also print, n, s, e, or w, to move in those directions")

print ("You can also print, n 4, s 4, e 4, or w 4, to move 4 in those directions")

因为当我不期望它需要距离时我绊倒了,而且它确实存在。

2)行if compass[0:5] == "n"正在尝试将5个字符的字符串与1个字符的字符串进行比较,看看它们是否相同。他们永远不会是一样的。

将它们更改为if compass[0] == "n"四个方向,然后命令如" n 4"将向北移动4个单位。

与此问题无关,但为了好玩,我开始重写它以减少代码重复并重命名变量。它最终成为面向对象;它现在分为一个前端通信接口,它接收命令并为方便起来稍微处理它们,以及一个远程流动站 - 如果命令接口升级,它现在可以支持多个流动站。

火星车在火星上,所以它无法直接打印到屏幕上,只能返回文字。流动站是它可以接受的命令的权限,因此接口将向其发送任何命令,如果它具有为您发送的命令命名的方法,则运行它,否则它会发生错误。 / p>

命令和参数处理简化为单个命令,或者带有一个或两个数字作为参数的命令,并且因为错误而应该更加健壮。

Run it on repl.it here

import random

objects = [ # Things it can dig up
    'David Bowie Life On Mars Record', 'A DeLorean', 
    'A Hover Board', 'Star Man', 'Water'
    ]

print ("************************************")
print ("Welcome to the Mars Rover Control HQ")
print ("Print 'ready' as the first command when prompted")
print ("Print dig or moveto (with coordinates) afterwards")
print ("You can also print, n, s, e, or w, to move in those directions")
print ("************************************")

class Rover:
    def __init__(self):
        self.x, self.y = 0, 0
        self.resting, self.available = True, True

    def ready(self):
        self.resting = False
        return "Rover is awake and ready for use"

    def dig(self):
        return "The rover found {}!".format(random.choice(objects))

    def moveto(self, x, y):
        self.x, self.y = x, y
        return "The Mars Rover is at position {}, {}".format(self.x, self.y)

    def rest(self):
        self.resting, self.available = True, False
        return "Rover is done for the day"

    def instruct(self, command, params):
        if self.resting and command != "ready":
            return "Error, cannot complete command\nPlease 'ready' the rover to continue"
        else:
            try:
                return getattr(self, command)(*params)
            except:
                return "Rover command error"

rover = Rover()
print("The Mars Rover is at position {}, {}".format(rover.x, rover.y))

while rover.available:
    command = input("Please enter your command for the rover:").split(' ')
    command, params = command[0], command[1:]

    if all(p.isdigit() for p in params):
        params = list(map(int, params))
    else:
        print("Command error: parameters X Y need to be numbers")
        continue

    if command == "return":
        command, params = "moveto", (0, 0)

    elif command in ("n", "e", "s", "w"):
        if not params: params = [1]
        distance = params[0]
        if command == "n": params = (rover.x, rover.y+distance)
        if command == "e": params = (rover.x+distance, rover.y)
        if command == "s": params = (rover.x, rover.y-distance)
        if command == "w": params = (rover.x-distance, rover.y)
        command = "moveto"

    print(rover.instruct(command, params))

答案 1 :(得分:0)

指南针的所有if语句都没有触发,因为:

指南针[0:6]不等于" w"或" n"或者任何单个字符,它是与5个字符进行比较的单个字符

使一切只是一个字符串或使它们都是相同大小的列表,但你必须将相同的长度列表与相同的长度进行比较,或者将字符串与字符串进行比较 - 而不是:list [1] == list [ 5]#如果你明白我的意思