尝试生成5个随机项目,有时生成4个

2024-06-09 00:26:02 发布

您现在位置:Python中文网/ 问答频道 /正文

import random

twoDimMap = [["H", "-", "-", "-", "-", "-"], ["-", "-", "-", "-", "-", "-"],
             ["-", "-", "-", "-", "-", "-"], ["-", "-", "-", "-", "-", "-"],
             ["-", "-", "-", "-", "-", "-"], ["-", "-", "-", "-", "-", "-"]]

items = 0

while items <= 4:
    test = random.randrange(0, 3)
    if test == 0:
        twoDimMap[random.randrange(0, 5)][random.randrange(0, 5)] = "S"
    if test == 1:
        twoDimMap[random.randrange(0, 5)][random.randrange(0, 5)] = "R"
    if test == 2:
        twoDimMap[random.randrange(0, 5)][random.randrange(0, 5)] = "*"
    #  I couldn't think of an easier way to do this
    if twoDimMap[0][0] != "H":
        twoDimMap[0][0] = "H"
        items -= 1
    items += 1

print(twoDimMap)

标题很好地解释了这一切(尽管我知道它不是太描述性:/),我正在尝试做一个游戏,英雄在地图上的位置[0],[0]开始。我搞不懂为什么我有时生成的项目比其他时候少。你知道吗

编辑:谢谢你所有的反馈,很抱歉我的愚蠢错误浪费了你的时间:/。我要把这归咎于缺少咖啡。你知道吗


Tags: oftotestimportanifitemsrandom
3条回答

因为问题空间很小,所以只生成三个保证唯一的问题空间可能不是一个可怕的想法。你知道吗

valid_locations = (tup for tup in itertools.product(range(5), repeat=2) if tup != (0, 0))
items = ["S", "R", "*"]
choices = [(random.choice(items), loc) for loc in random.sample(valid_locations, 3)]

for item, (x, y) in choices:
    twoDimMap[y][x] = item

random.sample(collection, n)保证来自collectionn非重复随机结果。random.choice(collection)给你一个来自collection的随机元素。你知道吗

有时randrange(0, 5)会多次返回相同的内容,因此会重新分配某个点。你知道吗

这可以通过与类型一起生成坐标并仅在该点当前未被占用时执行循环的其余部分来解决。这也将消除对单独(0,0)测试用例的需要。你知道吗

你只是在检查播放器是否被覆盖,而不是对象是否被覆盖,你应该首先得到随机坐标,然后检查是否有东西在那里。你知道吗

while items <= 4:
    test = random.randrange(0,3)
    x = random.randrange(0, 5)
    y = random.randrange(0, 5)
    if twoDimMap[x][y] == '-':
        if test == 0:
            twoDimMap[x][y] = "S"
        if test ==1:
            twoDimMap[x][y] = "R"
        if test == 2:
            twoDimMap[x][y] = "*"
        items += 1

评论中建议的更紧凑的解决方案是

while items <= 4:
    x = random.randrange(0, 5)
    y = random.randrange(0, 5)
    if twoDimMap[x][y] == '-':
        twoDimMap[x][y] = random.choice('SR*')
        items += 1

相关问题 更多 >