眾所周知,在眾多編程語(yǔ)言當(dāng)中,Python是這些編程語(yǔ)言當(dāng)中比較流行的。很多軟件開(kāi)發(fā)人員利用Python可以制作很多自己喜歡的東西,例如簡(jiǎn)單的小爬蟲(chóng)、簡(jiǎn)便的編輯器等,還有些開(kāi)發(fā)人員用Python制作一款自己喜歡的游戲。那么如何用Python制作自己的游戲今天將分享一些技巧,用python創(chuàng)建一個(gè)簡(jiǎn)單的石頭剪刀布游戲,該游戲?qū)⑹侨祟?lèi)與計(jì)算機(jī)的游戲。
· 通過(guò)以下方式導(dǎo)入隨機(jī)模塊:
import random
為什么?這樣計(jì)算機(jī)將產(chǎn)生自己的選擇。
放置一個(gè)無(wú)限的while循環(huán)(您不必一次又一次地運(yùn)行程序。)
while True:
· 陳述游戲規(guī)則。
# 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'. """)
· 根據(jù)上述規(guī)則從用戶(hù)那里獲取輸入。
user_choice = int(input("Enter YOUR choice: "))
· 用戶(hù)輸入超出范圍時(shí),對(duì)條件進(jìn)行編碼。
while user_choice > 3 or user_choice < 1:
user_choice = int(input("Enter valid input: "))
· 為用戶(hù)選擇分配編號(hào)。
if user_choice == 1:
choice_name = 'Stone'
elif user_choice == 2:
choice_name = 'Paper'
else:
choice_name = 'Scissor'
· 讓計(jì)算機(jī)選擇其選擇,然后為計(jì)算機(jī)的選擇分配編號(hào)。
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'
· 編寫(xiě)游戲的主要邏輯。
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"
· 聲明結(jié)果。
if result == choice_name:
print(" YOU WIN !!! ")
else:
print(" COMPUTER WINS !!! ")
· 提出重播問(wèn)題,并編寫(xiě)條件以打破無(wú)限的while循環(huán)。
print("Do you want to play again? (y/n)")
ans = input()
if ans == 'n' or ans == 'N':
break
好了關(guān)于如何用Python制作自己的游戲介紹到這里就結(jié)束了,想了解更多關(guān)于Python的信息,請(qǐng)繼續(xù)關(guān)注中培偉業(yè)。