眾所周知,在眾多編程語言當中,Python是這些編程語言當中比較流行的。很多軟件開發人員利用Python可以制作很多自己喜歡的東西,例如簡單的小爬蟲、簡便的編輯器等,還有些開發人員用Python制作一款自己喜歡的游戲。那么如何用Python制作自己的游戲今天將分享一些技巧,用python創建一個簡單的石頭剪刀布游戲,該游戲將是人類與計算機的游戲。
· 通過以下方式導入隨機模塊:
import random
為什么?這樣計算機將產生自己的選擇。
放置一個無限的while循環(您不必一次又一次地運行程序。)
while True:
· 陳述游戲規則。
# Rules of the game
print("""Enter your choice :
a. Press '1' to select 'Stone'.
b. Press '2' to select 'Paper'.
c. Press '3' to select 'Scissor'. """)
· 根據上述規則從用戶那里獲取輸入。
user_choice = int(input("Enter YOUR choice: "))
· 用戶輸入超出范圍時,對條件進行編碼。
while user_choice > 3 or user_choice < 1:
user_choice = int(input("Enter valid input: "))
· 為用戶選擇分配編號。
if user_choice == 1:
choice_name = 'Stone'
elif user_choice == 2:
choice_name = 'Paper'
else:
choice_name = 'Scissor'
· 讓計算機選擇其選擇,然后為計算機的選擇分配編號。
computer_choice = random.randint(1, 3) # Assigning numbers to the computer's choices
if computer_choice == 1:
computer_choicehoice_name = 'Stone'
elif computer_choice == 2:
computer_choicehoice_name = 'Paper'
else:
computer_choicehoice_name = 'Scissor'
· 編寫游戲的主要邏輯。
if((user_choice == 1 and computer_choice == 2) or
(user_choice == 2 and computer_choice ==1 )):
print("Paper wins !!! ", end = "")
result = "Paper"
elif((user_choice == 1 and computer_choice == 3) or
(user_choice == 3 and computer_choice == 1)):
print("Stone wins !!! ", end = "")
result = "Stone"
else:
print("Scissor wins !!! ", end = "")
result = "Scissor"
· 聲明結果。
if result == choice_name:
print(" YOU WIN !!! ")
else:
print(" COMPUTER WINS !!! ")
· 提出重播問題,并編寫條件以打破無限的while循環。
print("Do you want to play again? (y/n)")
ans = input()
if ans == 'n' or ans == 'N':
break
好了關于如何用Python制作自己的游戲介紹到這里就結束了,想了解更多關于Python的信息,請繼續關注中培偉業。