【问题标题】:random.shuffle() not working for number guessing gamerandom.shuffle() 不适用于猜数字游戏
【发布时间】:2016-01-05 08:17:25
【问题描述】:

我正在制作一款基于文本的冒险游戏,但有一次我希望用户无休止地输入数字。我是 Python 新手,所以越简单越好,但这就是我目前所掌握的。

这里是代码

import os
import sys
import string

import time
import random
numbers = ['1', '2', '3', '4', '5', '6', '7', '8' , '9']

print("Welcome to My Text Adventure Game: Dumb Edition")
print ("You (yes YOU) awake in an E-M-P-T-Y room.")
print ("It's very chilly willy and someone is drawing on the walls")
print (" Do you exit the room via the door that is obviously the right way (1)")
print ("what do you do?")
time.sleep(1)
print("Wait!")
print("You can't be trusted to not get this wrong")
print("I'll do it")
print("1")
time.sleep(1)
print("Erm...It should be going..")
print("Meh I'll just make something up! Two seconds..")
time.sleep(3)
print ("Ok.. I've got it! You'll just press buttons and it will be fun!")
print ("Or else..")
print ("Here we go...")
time.sleep(1)
print ("Please enter the following")
while True:
        rng_number = random.shuffle(numbers)
        print (rng_number)
        user_input = input("Go on, type it in!")
        if user_input == rng_number:
                print("Good job again!")
        else:
                print("Try again...Moron")

这是我运行代码时发生的情况

Welcome to My Text Adventure Game: Dumb Edition
You (yes YOU) awake in an E-M-P-T-Y room.
It's very chilly willy and someone is drawing on the walls
 Do you exit the room via the door that is obviously the right way?(1)
what do you do?
Wait!
You can't be trusted to not get this wrong
I'll do it
1
Erm...It should be going..
Meh I'll just make something up! Two seconds..
Ok.. I've got it! You'll just press buttons and it will be fun!
Or else..
Here we go...
Please enter the following
None
Go on, type it in!None
Try again...Moron
None
Go on, type it in!

【问题讨论】:

  • 请在此处添加您的代码。
  • 首先请将您的代码粘贴为代码而不是图像。 random.shuffle(x[, random]) Shuffle the sequence x in place Doc 换句话说,当您调用rng_number=random.shuffle(numbers) 时,它只是随机排列数字数组并将None 分配给rng_numberrandom.shuffle() 返回无)。 input 读取用户输入的文本,您应该将其转换为 int。
  • 谢谢亚历克斯。我已将输入更改为 int(input("Go on, type it in!")) 但我仍然没有得到一个数字。
  • @TheFlyingScotsman 你会 - 正如亚历克斯所指出的 - 洗牌返回 None - 试着看看 random.choice 代替

标签: python random numbers generator python-3.4


【解决方案1】:

正如 cmets 中所指出的,您的程序的问题是 random.shuffle() 没有为 rng_number 分配数字。要从 numbers 分配一个值到 rng_number,您必须改用 random.choice() (Docs)。

import random
numbers = ['1', '2', '3', '4', '5', '6', '7', '8' , '9']

while True:
    rng_number = random.choice(numbers)
    print (rng_number)
    user_input = input("Go on, type it in!")
    if user_input == rng_number:
        print("Good job again!")
    else:
        print("Try again...Moron")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-20
    • 2016-06-21
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多