Python战舰随机数生成器

标签 python

我对 Python 中的类还很陌生。在编写战舰游戏时,我遇到了为计算机舰船位置和计算机攻击坐标选择随机 x,y 坐标的问题。我对是否生成随机数作为函数之一中的局部变量或作为类属性或实例属性感到困惑。

最初我想创建一个实例属性(如下),但我得到 rand_x 未定义。我尝试创建一个生成随机数的战舰函数,但每次调用它时它都会返回同一对坐标。为随机 # 创建局部变量是唯一的方法吗?因为我将多次使用随机生成器,所以最好不必重复该代码。

感谢您的耐心等待。

编辑:我在随机函数中包含了更多代码,并替换了 size在随机函数中 self.size

例如,Battleship(4,2,0,0) 可能会给我 hitlist [[2,1],[2,1]] 我想要随机#s hitlist .

import random
hitlist=[]; #a global variable

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,r):
        """input is integer coordinates for ships and output is an array of arrays with battleship locations CREATES THE HITLIST DONT REPEAT"""
        print('plotships function running')
        for i in range(self.numberships):
            hitlist.append(r) #random number from function randomness
            print(hitlist)
        return hitlist

   def randomness(self):
        rand_x=random.choice(range(self.size))
        rand_y=random.choice(range(self.size))
        randcoord=[rand_x,rand_y]
        return randcoord

#Game Interface
size=int(input('Gameboard size'))
numberships=int(input('Waiting for Number of enemy ships'))
b=Battleship(size,numberships,0,0)
random=b.randomness() #create a random x y coordinate
b.plotships(random) #create a hitlist

最佳答案

我认为这是因为您使用 size 调用 random.choice 而不是 self.size

rand_x = random.choice(range(self.size))

另外,你在哪里定义self.rand?您在尝试打印它的构造函数中肯定遇到了问题吗?

编辑 - 回应下面的评论:

如果您希望使用 self.numberships 对独立随机数对填充 hitlist,请将 plotships 方法编写为:

def plotships(self):
    """input is integer coordinates for ships and output is an
       array of arrays with battleship locations CREATES THE
       HITLIST DONT REPEAT"""
    print('plotships function running')
    for i in range(self.numberships):
        hitlist.append(randomness()) #random number from function randomness
        print(hitlist)
    return hitlist

关于Python战舰随机数生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39578807/

相关文章:

python - 与给定列表中的每个元素相比,查找每个整数的平均值

python - Kivy USB 键盘 double 字母

python - 将元组添加到 Python 中的元组列表

python - 什么时候应该使用 Unicode 字符串?

python - 将表单数组发送到 Flask

python - 通过 API 网关 v Lambda 控制台调用 lambda 函数时请求主体序列化差异

python - pyExchange 的时区问题

python - 在 Python 2.6 中使用 unicode_literals 的任何陷阱?

python - 如何使用 Google Python AppEngine 从 Backbone 应用程序发送电子邮件

Python OpenCV - 用透明度覆盖图像