[英]Python Battleship random number generator
我对Python中的类很新。 在编写战舰游戏时,我遇到了一个问题,就是选择计算机船只位置的随机x,y坐标和计算机的攻击坐标。 我很困惑是否在其中一个函数中生成随机数作为局部变量,或者作为Class属性或实例属性。
最初我想创建一个实例属性(下面),但我没有定义rand_x。 我尝试创建一个生成随机数的Battleship函数,但每次调用它时都会返回相同的坐标对。 唯一的方法是为随机#s创建局部变量吗? 因为我将不止一次地使用随机生成器,所以不必重复该代码会很好。
谢谢你的耐心。
编辑:我已经包括了更多的代码与随机性功能,并更换size
与随机性功能self.size
。
例如,Battleship(4,2,0,0)可能会给我一个[[2,1],[2,1]]的热门hitlist
我希望在hitlist
随机#s。
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
我认为这是因为你调用random.choice
size
而不是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
要获得随机数,您可以导入随机库。
您可以使用它来初始化类的实例上的(X,Y)coordenates。
import random
Battleship(size, numberships, random.randint(0, WIDTH), random.randint(0, HEIGHT))
我假设你有屏幕的宽度和高度可用。 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.