python 战舰_Python战舰随机数发生器

我对Python中的类比较陌生。在编写一个战舰游戏时,我遇到了一个问题:随机选择x,y坐标作为计算机舰船的位置和计算机的攻击坐标。我不知道是将随机数生成为某个函数中的局部变量,还是生成类属性或实例属性。在

最初我想创建一个实例属性(如下),但我发现rand_x没有定义。我尝试创建一个生成随机数的战列舰函数,但每次调用它时都返回相同的一对坐标。唯一的方法是为随机变量创建一个局部变量吗?因为我将不止一次地使用随机生成器,所以最好不要重复这些代码。在

谢谢你的耐心。在

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

例如,战列舰(4,2,0,0)可能会给我一个hitlist的[[2,1],[2,1]],我想要随机的在里面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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值