我对 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/