2
目前,我可以在二維數組中創建一個隨機世界。不過,我覺得這太隨意了。這是我目前正與類:爲基於文本的RPG創建更一致,隨機生成的世界空間
from random import randint, choice, randrange
class WorldSpace(object):
def __init__(self, row, col, world_array):
self.row = row # Number of lists to be created.
self.col = col # Number of indexes inside of each row.
self.world_array = world_array
創建世界上WorldSpace
方法:
@classmethod
def generate(cls, autogen):
print 'Starting world generation...'
print
if autogen is True:
row_amt = 75
col_amt = 75
else:
row_amt = input('Please specify row length of world array.: ')
col_amt = input('Please specify column length of world array.: ')
if (row_amt or col_amt) == 0:
print 'Invalid world values!'
cls.generateWorld(False)
world_array = [[' ']*col_amt for _ in xrange(row_amt)]
print 'Created world...'
return cls(row_amt, col_amt, world_array)
修改該世界的方法 - 目前只創建forests
儘管在我的全部代碼中,也形成了一系列的海洋和山脈:
def modify_world(self, autogen):
if autogen is True:
# Forests:
count = randint(6, 10)
while count > 0:
a = randint(1, (self.row/randint(2, 6)))
b = randint(1, (self.col/randint(2, 6)))
row_val = randint(5, self.row)
count_val = randint(5, 15)
self.genLine_WObj(a, b, row_val, 't', count_val)
count -=1
print('\n'.join([''.join(['{:1}'.format(item) for item in row])
for row in self.world_array]))
inp = input('')
if inp != '':
return
而實際創建forest
磚的方法:
def genLine_WObj(self, a, b, row_val, char, count):
# 'genLine_WObj' - Generate Line(like) world object.
# Used to place lines of certain characters with psuedo-randomized
# width and length onto the world array.
while count != 0:
row_col_dict = {row_val: (a, b)}
for row in row_col_dict.keys():
startPos, endPos = row_col_dict[row]
for i in range(startPos, endPos):
self.world_array[row][i] = char
b += choice([0, 1])
a += choice([0, 0, 0, 0, 1])
row_val -= 1
count -= 1
現在實際運行程序:
world = WorldSpace.generate(True)
world.modify_world(True)
然而,雖然作品時〜20%-30%,有時當它應該在地圖周圍創建森林時,會生成小森林或小對t
個字符。我如何改進我的代碼以使隨機生成的代更加一致?
你沒有解釋目標。有些東西不能既是隨機的,又是一致的 - 這是矛盾的。 「小對」是什麼意思?另外你的代碼有問題:例如,查看genLine的while循環的前三行 - 你創建一個單元字典並對它進行「迭代」(循環只運行一次),然後使用鍵查找您剛剛明確賦予它的值,並將* that *分配給兩個新變量。沒有任何代碼實際上做任何事情。我建議你將你的代碼發佈到CodeReview並獲得幫助來清理它。 –