简体   繁体   English

Python随机生成器

[英]Python Random Generator

Basically i need some quick help. 基本上我需要一些快速帮助。 I'm making a program where I am using two random generators to generate numbers. 我正在编写一个程序,其中使用两个随机生成器来生成数字。

  1. First generator, between 2-14 each number representing a card. 第一个生成器,在2-14之间,每个数字代表一张卡。 Numbers 11, 12 13, and 14 represent Jack, Queen, King & Ace respectively. 数字11、12、13和14分别代表杰克,皇后,国王和王牌。
  2. Second random generator generating numbers 15-18 to represent the type of card for example 15, 16, 17, 18 would represent Hearts, Spades, Diamonds & Clubs respectively. 第二个随机生成器生成的数字15-18代表卡的类型,例如15、16、17、18将分别代表红心,黑桃,钻石和球杆。

What the outcome of the generators should come to is the first generator generated a number 8 and the second generator generated the number 17. I then want it to translate this to read: "8 of Diamonds". 生成器的结果应该是第一个生成器生成数字8,第二个生成器生成数字17。然后,我希望它将其翻译为:“ 8颗钻石”。

Here is my code so far: 到目前为止,这是我的代码:

import random

Player1 = input("Enter Name Of Player1")
Card = random.randint(2, 14)
Suit = random.randint(15,18)
if Card == 11:
    print("Jack")
elif Card == 12:
    print("Queen")
elif Card == 13:
    print("King")
elif Card == 14:
    print("Ace")
else:
    print(Card)

Try the following, using random.choice() and string formats : 使用random.choice()字符串格式尝试以下操作:

import random

suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
numbers = [
    '2', '3', '4', '5', '6', '7', '8', '9', '10',
    'Jack', 'Queen', 'King', 'Ace']

print('{number} of {suit}'.format(
    number=random.choice(numbers),
    suit=random.choice(suits)))

>> Ace of Hearts

You could use some range function to generate the numbers, but in this particular case, you can probably get away with hardcoding it. 您可以使用一些range函数来生成数字,但是在这种特殊情况下,您可以避免对其进行硬编码。 Note that strings are probably the better option as well because you're mixing that with 'Jack', 'Queen', 'King', and 'Ace' . 请注意,字符串可能也是更好的选择,因为您将其与'Jack', 'Queen', 'King', and 'Ace'

Another solution: 另一个解决方案:

import random

Player1 = raw_input("Enter Name Of Player1")
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
numbers = {2:'2', 3:'3', 4:'4', 5:'5', 6:'6', 7:'7', 8:'8', 9:'9', 10:'10', 11:'Jack', 12:'Queen', 13:'King', 14:'Ace'}
Card = random.randint(2, 14)
Suit = random.randint(0, 3)
print '{0} of {1}'.format(numbers[Card], suits[Suit])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM