下面是一个使用Python编写的示例代码:
import random
def throw_dice():
return random.randint(1, 6)
def play_game():
player_score = 0
while player_score < 21:
input("按下 Enter 键进行投掷骰子...")
dice_result = throw_dice()
print("玩家掷出了", dice_result)
player_score += dice_result
print("当前得分:", player_score)
if player_score == 21:
print("恭喜你获胜!")
else:
print("很遗憾,你输了。")
play_game()
这段代码首先定义了一个throw_dice()
函数,它使用random.randint()
函数来模拟投掷骰子的结果,得到一个1到6之间的随机整数。
然后定义了一个play_game()
函数,其中使用一个while
循环来模拟玩家进行连续投掷的过程。每次投掷后,将投掷结果加到玩家得分上,并打印出当前得分。当玩家得分达到或超过21点时,结束循环。
最后,根据玩家得分是否等于21点,判断玩家是否获胜,并输出相应的信息。
你可以直接运行这段代码来进行游戏。每次按下Enter键后,程序会模拟掷骰子并显示结果和当前得分,直到玩家获胜或者得分超过21点。