HOWTO · Python
Python でサイコロロールシミュレーターを作成する
この記事では、Python でダイスロールシミュレーターを作成する方法を紹介します
このページの内容
Python でサイコロを振るシミュレーターを作成するには、random.randint() 関数を使用して、次のように 1 から 6 の範囲の乱数を生成します。
random.randint(1, 6)
Python で random.randint(1,6)を使用してダイスロールシミュレーターを作成する
random.randint() 関数を使用して、Python でサイコロを振るシミュレーターを作成できます。関数の構文は次のとおりです。
random.randint(x, y)
したがって、x と y の間のランダムな整数を生成します。サイコロシミュレータの例では、
x は 1、y は 6 です。
以下に例を示します。
import random
print("You rolled the following number", random.randint(1, 6))
ユーザーがサイコロを振り続けるかどうかを選択できるようにするには、次のように while ループ内に random.randint(1,6) を配置します。
from random import randint
repeat_rolling = True
while repeat_rolling:
print("You rolled the following number using the Dice -", randint(1, 6))
print("Do you wish to roll the dice again?")
repeat_rolling = ("y" or "yes") in input().lower()
ユーザーがサイコロを振るのをやめることを選択した場合、while ループを終了する必要があります。
出力:
You rolled the following number using the Dice - 2
Do you wish to roll the dice again?
y
You rolled the following number using the Dice - 4
Do you wish to roll the dice again?
y
You rolled the following number using the Dice - 5
Do you wish to roll the dice again?
n