저는 Python의 클래스를 처음 접했습니다. 전함 게임을 코딩하는 동안 컴퓨터의 배송 위치와 컴퓨터의 공격 좌표에 대해 임의의 x, y 좌표를 선택하는 데 문제가 발생했습니다. 나는 하나의 함수에서 지역 변수로서 또는 클래스 속성 또는 인스턴스 속성으로 난수를 생성할지 여부에 대해 혼란 스럽다.Python Battleship 난수 생성기
처음에는 인스턴스 속성 (아래)을 만들려고했지만 rand_x가 정의되어 있지 않습니다. 나는 난수를 생성 한 Battleship 함수를 만들려고했지만, 호출 될 때마다 같은 좌표 쌍을 반환했습니다. 임의의 #에 대한 로컬 변수를 만들려면이 작업을 수행하는 유일한 방법입니까? 랜덤 생성기를 두 번 이상 사용할 것이므로 해당 코드를 반복하지 않아도됩니다.
양해 해 주셔서 감사합니다.
편집 : 임의성 기능으로 더 많은 코드를 포함 시켰고 임의 변경 기능에서 size
을 self.size
으로 바꿨습니다.
예를 들어 Battleship (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
:
당신이 독립적 인 임의의 숫자 쌍
self.numberships
쌍로 채워 할hitlist
을하려면로plotships
방법을 쓰기 무작위'. 'random.randint (0, self.size - (wtv는 x 범위 임)'및'random.randint (0, self.size - (wtv는 y 범위)'를 사용하십시오) –당신은 [edit] 우리가 무엇이 잘못되었는지를 알 수있는 유일한 방법은 짐작하는 것입니다. –
@ Imtiaz Raqib이 문제는 % 100에 지나치게 위선적 인 것이지만 더 많은 것을 사용할 수는 있습니다. 보안 랜덤 넘버 생성기 호출 (IE :'os.urandom'). 적군이 함대 Admiral @ st4rgut의 위치를 예측하는 것을보고 싶지 않을 것입니다. –