간단한 주사위 굴리기 게임 애플리케이션입니다. 사용자는 굴릴 주사위 수와 각 주사위의 면 수를 지정할 수 있습니다. 그런 다음 애플리케이션은 주사위 굴리기를 시뮬레이션하고 결과를 표시합니다.
Python에서 가능한 구현은 다음과 같습니다.
import random
def roll_dice(num_dice, num_sides):
"""Simulates rolling multiple dice.
Args:
num_dice: The number of dice to roll.
num_sides: The number of sides on each die.
Returns:
A list of integers representing the results of each die roll. Returns an empty list if num_dice is 0 or less.
"""
if num_dice <= 0:
return []
return [random.randint(1, num_sides) for _ in range(num_dice)]
def main():
"""Gets user input and runs the dice rolling simulation."""
while True:
try:
num_dice = int(input("Enter the number of dice to roll (or 0 to exit): "))
if num_dice == 0:
break
num_sides = int(input("Enter the number of sides on each die: "))
if num_sides <=0:
print("Number of sides must be greater than 0.")
continue
results = roll_dice(num_dice, num_sides)
print("Results:", results)
print("Total:", sum(results))
except ValueError:
print("Invalid input. Please enter integers only.")
if __name__ == "__main__":
main()
이 코드는 먼저 주사위 수와 면 수를 입력으로 받아 결과 목록을 반환하는 함수 roll_dice를 정의합니다. main 함수는 사용자 상호작용을 처리하여 입력을 요청하고 유효성을 검사합니다. 그런 다음 roll_dice을 호출하고 결과와 합계를 인쇄합니다. while True 루프를 사용하면 사용자는 0을 입력할 때까지 여러 번 굴릴 수 있습니다. 정수가 아닌 입력을 포착하기 위한 오류 처리가 포함됩니다. 이는 기본적이지만 기능적인 주사위 굴리기 애플리케이션을 제공합니다. 더 많은 고급 기능이 추가될 수 있습니다(예: 그래픽 사용자 인터페이스, 다양한 유형의 주사위, 점수 저장).