Python代码:声呐搜索

import random


class OceanTreasure:
    def __init__(self):
        self.__board = [['~'] * 60 for row in range(15)]
        self.__chests = []
        while len(self.__chests) < 3:
            coord = [str(random.randint(0, 59)), str(random.randint(0, 14))]
            if coord not in self.__chests:
                self.__chests.append(coord)

    def getChests(self):
        # returns the list of coordinates of the chests still to be found.
        return self.__chests

    def getTreasuresLeft(self):
        # returns the number of treasure chests still to be found.
        return len(self.__chests)

    def dropSonar(self, x, y, sonar):
        distance = self.checkDistance(x, y)
        if distance == None:
            sonar = 'O'
        elif distance == 0:
            self.__chests.remove([x, y])
            sonar = 'X'
        elif distance > 0:
            sonar = str(distance)
        elif distance < 0:
            if distance == -1:
                sonar = 'a'
            elif distance == -2:
                sonar = 'b'
            elif distance == -3:
                sonar = 'c'
            elif distance == -4:
                sonar = 'd'
            elif distance == -5:
                sonar = 'e'

        self.__board[int(y)][int(x)] = sonar  # change the character

    def checkDistance(self, x, y):
        location = [x, y]
        if location in self.__chests:
            return 0
        distanceList = []
        coordList = []
        coordDict = {}
        for chest in self.__chests:
            distance = ((int(chest[0]) - int(float(x))) ** 2 + (
                    int(chest[1]) - int(float(y))) ** 2) ** 0.5
            distanceList.append(distance)
            coordList.append(chest)
        for i in range(0, 3):
            coordDict[distanceList[i-1]] = coordList[i-1]

        closedChest = coordDict[min(distanceList)]
        xRange = abs(int(closedChest[0]) - int(x))
        yRange = abs(int(closedChest[1]) - int(y))
        if xRange < 10 and yRange < 6:
            if xRange < 2 * yRange and xRange != 0 or yRange == 0:
                return xRange
            else:
                return -yRange

    def drawBoard(self):
        print(" " * 4, "1", "2", "3", "4", "5", sep=" " * 9)
        print(" " * 3 + "0123456789" * 6)
        index = 0
        for line in self.__board:
            leftIndex = "%2d" % (index)
            row = ""
            for grid in line:
                row += grid
            print(leftIndex, row, str(index), sep=" ")
            index += 1
        print(" " * 4, "1", "2", "3", "4", "5", sep=" " * 9)
        print(" " * 3 + "0123456789" * 6)


def main():
    ocean = OceanTreasure()
    chestLocation = ocean.getChests()
    gameOver = False
    droppedSpot = []
    position = ['', '']
    usedSonar = 0
    haveInput = False
    print(chestLocation)
    while not gameOver:
        ocean.drawBoard()
        print("You have " + str(20 - usedSonar) + " sonar devices available. Treasures found: " + \
              str(3 - ocean.getTreasuresLeft()) + ". Still to be found: " + \
              str(ocean.getTreasuresLeft()) + ".")
        print('Where do you want to drop your sonar?')
        while not haveInput:
            userInput = input(
                'Enter coordinates x y (x in [0, 59] and y in [0, 14], 用空格隔开) (or Q to quit and H for help): ')
            try:
                if userInput.lower() in ['q', 'h']:
                    try:
                        if userInput.lower() == 'q':  # quit game
                            haveInput = True  # quit the loop
                            gameOver = True
                            break
                        elif userInput.lower() == 'h':  # get help
                            print(
                                'your input should be a pair of x y which sepreted by a space (x in [0, 59] and y in [0. 14])')
                            haveInput = False
                    except Exception as exce:
                        print(exce)

                else:
                    try:
                        haveInput = True
                        position = userInput.split(' ')
                        assert (len(position) == 2 and isinstance(int(position[0]), int) and isinstance(int(position[1]), int) and int(position[0]) in range(0, 60) and int(position[1]) in range(0, 15)),"You must enter a pair of coordinates separated by a space (or Q to quit and H for help).\n"
                        if position not in droppedSpot:
                            droppedSpot.append(position)
                        else:
                            print('You have already dropped a sonar there. You lost a sonar device.\n')

                    except:
                        haveInput = False
                        print(
                            'your input should be a pair of x y which is separated by a space (x in [0, 59] and y in [0, 14])')

            except:
                haveInput = False

        try:
            ocean.dropSonar(position[0], position[1], '')
            usedSonar += 1
            haveInput = False
            print(chestLocation)

        except:
            print('Thanks for playing')  # end the game
            gameOver = True

        if usedSonar == 20 and ocean.getTreasuresLeft() > 0:  # check if all the sonars have been used
            gameOver = True
            print('You lost all your 20 sonar devises.\nThe remaining chests were in: ' + str(ocean.getChests()))

        elif ocean.getTreasuresLeft() == 0:  # check if there is no chest left
            gameOver = True
            print('You found all the 3 treasure Chests using ', usedSonar, ' out of 20 sonar devices.')



main()

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值