井字游戏RNG

时间:2018-07-13 13:54:00

标签: python tic-tac-toe

import random

a = 1

b = 2

c = 3

d = 4
# I would like the random_number to be 5

random_number = random.randint(1,5)

def function():
    global random_number
    while True:
        random_number = random.randint(1,5)
        if random_number !=  a or b or c or d:
            break
        print (random_number)


function()

下面是代码的链接

https://pastebin.com/bhmMkF81

因此,我正在尝试制作一个能够播放井字游戏的程序。但是我无法生成分配给该变量的数字。我发布的这段代码不断为我提供随机数。

2 个答案:

答案 0 :(得分:2)

假设您要在function内循环直到random_number为5,则function内的条件不正确。以下将运行循环,直到random_number为5并打印结果为止。

def function():
    global random_number
    print('here')
    while True:
        print('here2')
        random_number = random.randint(1,5)
        print(random_number)
        if random_number not in [a, b, c, d]:
            break
    print (random_number) # will always print 5

请注意条件random_number not in [a, b, c, d]检查random_number是否等于abcd

答案 1 :(得分:0)

您的代码检查数字是否为1或2或3或4。

如果只想显示5个,则需要将其更改为和

这里的逻辑是

如果您得到任何数字,将不是下面这4个数字之一

〜1或〜2或〜3或〜4 <​​/ p>

因此必须同时与所有这些都不同

if random_number !=  a and b and c and d:

我也相信这全都在while(True)里面,但是在打印中,在这里复制代码时只是缩进错误。 因此,代码应为

import random

a = 1
b = 2
c = 3
d = 4
# I would like the random_number to be 5

random_number = random.randint(1,5)

def function():
    global random_number
    while True:
        random_number = random.randint(1,5)
        if (random_number != a) and (random_number != b) and (random_number != c) and (random_number != d):
            break
    print (random_number)


function()