我們通過 Python 的第三方庫可以完成很多操作,下面為大家介紹如何用 Python 制作一個(gè)骰子模擬器和石頭剪刀布游戲。
一、骰子模擬器
目標(biāo):做出一個(gè)可以擲骰子游戲的程序。
tips:在用戶詢問時(shí),用 random 模塊去生成 1 到 6 間的數(shù)字。
二、石頭剪刀布游戲
目標(biāo):做出一個(gè)命令行游戲,玩家可以在石頭、剪刀和布之間選擇,和計(jì)算機(jī)進(jìn)行對(duì)決。如果玩家獲勝,得分會(huì)添加,游戲結(jié)束后最終分?jǐn)?shù)展示給玩家。
tops:收到玩家選擇,和計(jì)算機(jī)選擇比較。計(jì)算機(jī)的選擇是在列表隨機(jī)選中。如果玩家獲勝會(huì)增加一分。
import random
choices = ["Rock", "Paper", "Scissors"]
computer = random.choice(choices)
player = False
cpu_score = 0
player_score = 0
while True:
player = input("Rock, Paper or Scissors?").capitalize()
# 判斷游戲者和電腦的選擇
if player == computer:
print("Tie!")
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
cpu_score+=1
else:
print("You win!", player, "smashes", computer)
player_score+=1
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
cpu_score+=1
else:
print("You win!", player, "covers", computer)
player_score+=1
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
cpu_score+=1
else:
print("You win!", player, "cut", computer)
player_score+=1
elif player=='E':
print("Final Scores:")
print(f"CPU:{cpu_score}")
print(f"Plaer:{player_score}")
break
else:
print("That's not a valid play. Check your spelling!")
computer = random.choice(choices)
以上就是小編為您帶來的關(guān)于 Python做一個(gè)骰子模擬器和石頭剪刀布游戲 的全部內(nèi)容。