Python战舰游戏,递归故障

标签 python recursion

提前对数据转储表示歉意。我正在用 Python 重新创建战舰游戏。我在使用 def Battleship 功能时遇到问题,计算机和用户试图猜测彼此的坐标。计算机正确猜测用户坐标的概率为e/x,其中e是剩余的船只数量,x是未知坐标的数量。问题是,在用户未击中的情况下,如何访问当用户击中得分时分配的局部变量x?由于这是一个递归函数,如果用户错过,则不会定义x。我仍然希望计算机在用户错过时猜测玩家的战舰位置。但是,我收到的错误消息是:赋值前引用的局部变量“x”

感谢您的耐心等待。似乎应该有一个简单的解决方案。

import random
import sys

globalValue=0 #for length of hitlist
loopcondition=True
compdestruction=0 #keep track of number of destroyed ships
userdestruction=0
destroyedships=[];
hitlist=[]; #a global variable
 #to end the program
you=[];
youhitship=[];

class Battleship(object):
    """ Ship object container. A game where the user tries to destroy the enemy's ships User tries to guess computer's position x and y """
    def __init__(self, size, numberships,position_x,position_y):
        self.position_x=position_x
        self.position_y=position_y
        self.numberships=numberships
        self.size = size

    def plotships(self,numberships):
        """input is integer coordinates for ships and output is an array of arrays with battleship locations CREATES THE HITLIST DONT REPEAT"""
        while len(hitlist)<numberships:
            r=Battleship.randomness(self)
            if r not in hitlist:
                hitlist.append(r)
        originalhitlist=len(hitlist)
        global globalValue
        globalValue+=originalhitlist


    def destroy(self):
        """ Destroys the ship's point supplied if it contains it """
        compChoose=Battleship.randomness(self) #computer's attak pair
        print('computer choice is '+str(compChoose))
        ship=[self.position_x,self.position_y]
        print('Your Turn...')
        if  ship in hitlist:
            print('Direct hit Captain')
            global userdestruction
            hitlist.remove(ship)
            userdestruction+=1
            CompWreck=GameBoard(self.size)
            CompWreck.update(ship,self.size, destroyedships) #empty (at first) lists with coordinates of up-to-date list of destroyed ships
        else:
            print('Drat! missed!')
        print('\nComps Turn')
        if compChoose in you:
            print('Kabloom. Your ships sunk.')
            global compdestruction
            you.remove(compChoose)
            compdestruction+=1
            YourWreck=GameBoard(self.size) #create an instance of GameBoard
            YourWreck.update(ship,self.size,youhitship)
        else:
            print('Yay! The computer missed!\n')


    def randomness(self):
        """random coordinates for computer firing and computer ship location"""
        rand_x=random.choice(range(self.size))
        rand_y=random.choice(range(self.size))
        randcoord=[rand_x,rand_y]
        return randcoord

class GameBoard(object):
    """ The container for the ships """
    def __init__(self, size):
        """Initialize clean GameBoard depending on size, etc """
        self.size=size
        self.destroyed = 'x' # representation for destroyed area
        self.clear = '-' # representation for clear water

    def printBoard(self,destroytheseships):
        """ Print the current gameboard state"""
        global compdestruction
        global userdestruction
        global globalValue
        global loopcondition
        graf='' #printed board
        x=-1 #so the first row is 0, within the range of hitlist coordinates defined in Battleship.plotships(self)
        for row in range(self.size): #for every row inside the first set of brackets
            x+=1 #x,y pairs mark the possible ship locations
            graf+='\n'
            y=-1 #so the first column is 0 
            for column in range(self.size):
                y+=1
                if [x,y] in destroytheseships:                    
                    graf+=self.destroyed
                else:
                    graf+=self.clear
        print(graf)

        if userdestruction == globalValue:
            print('You Win!')
            sys.exit('Game Over')

        if compdestruction>=originalyou:
            print('You Lose'  )
            sys.exit('Game Over')

    def update(self,ship,size,witchlist):#It matter whether it's computer or user's turn. WITCHLIST  defines which list you're choosing from
        """ Updates the gameboard according to updated ship """
        witchlist.append(ship)
        newboard=GameBoard(size) #create a new instance with the same sized board
        newboard.printBoard(witchlist)

#Game Interface do it once
size=int(input('Gameboard size'))
numberships=int(input('Waiting for Number of enemy ships'))
b=Battleship(size,numberships,0,0)
b.plotships(numberships) #create a hitlist and returns the original length of hitlist array

for i in range(numberships): #create list of your ships 
    you_x=int(input('Please enter a X coordinate for your ship'))
    you_y=int(input('Please enter a Y coordinate for your ship'))
    if ((you_x not in range(0,size)) or (you_y not in range(0,size))):
        print('please chooose a different pair of coordinates within board boundaries\n')
        continue
    your_xy=[you_x,you_y]
    you.append(your_xy)
    originalyou=len(you)
while loopcondition==True: #take another turn as long as all the ships are not destroyed
    ex=int(input('Waiting for attack X coordinate'))
    why=int(input('Waiting for attack Y coordinate'))
    if ((ex not in range(0,size)) or (why not in range(0,size))):
        print('please chooose a different pair of coordinates within board boundaries\n')
        continue
    b=Battleship(size,numberships,ex,why)
    b.destroy()

最佳答案

您的 if 语句意味着 x 不是根据未命中来计算的。您必须在 else 语句中添加更多逻辑才能确定 x 应该是什么。起点是复制绘制图形的代码块,但只保留修改 x 值的行(还将 x 初始化为 0)。

关于Python战舰游戏,递归故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39342852/

相关文章:

python - 递归函数调用不将值添加到列表中

java - 递归运行时实现 Java 与其他/功能语言?

Python - 没有返回逻辑的递归函数

python - 为什么我打包的 eel 应用程序执行失败 : AttributeError: 'NoneType' object has no attribute 'write'

python - scipy misc.derivative 结果不正确

python - 在Python中的azure函数的帮助下,Json从devops到存储帐户都表现出色

java - 二维数组的递归

python - 获取具有随机类名的元素

python - Discord-py Rewrite - Cog 中的基本 aiohttp 网络服务器

php - 如何在 PHP 中递归删除目录及其全部内容(文件 + 子目录)?