Python编程基础:第三十七节 石头剪刀布游戏Rock, Paper, Scissors Game
第三十七節(jié) 石頭剪刀布游戲Rock, Paper, Scissors Game
- 前言
- 實踐
前言
我們這一節(jié)的內(nèi)容主要是對前邊學(xué)習(xí)內(nèi)容的一個綜合應(yīng)用,以石頭,剪刀,布游戲為例講解列表、隨機(jī)數(shù)、用戶輸入、字符串操作、循環(huán)結(jié)構(gòu)、選擇分支、判斷表達(dá)式等相關(guān)知識。如果你能獨立完成本節(jié)編程內(nèi)容,說明對前邊的學(xué)習(xí)有了一個很好的掌握。
實踐
我們的項目需求為:電腦隨機(jī)選擇剪刀石頭布中的一個選項,用戶自己輸入一個作為自己的選擇,然后比較電腦的選擇結(jié)果與用戶的選擇結(jié)果判斷輸贏。如果用戶輸入錯誤,那就讓用戶一直輸入,直到輸入正確的選項為止。同時用戶還可以決定是否停止游戲。我們先給出代碼,然后逐步分析:
import random# 石頭,布,剪刀 choices = ["rock", "paper", "scissors"] print("Let's begin the game!") while True:computer = random.choice(choices)user = input("Please input rock, paper, or scissors: ").lower()while user not in choices:user = input("Please input rock, paper, or scissors: ").lower()print("The choice of the computer: {}".format(computer))print("The choice of the user: {}".format(user))if user == computer:print("Just so so!")if user == "rock":if computer == "paper":print("You lose")elif computer == "scissors":print("You win!")if user == "paper":if computer == "scissors":print("You lose")elif computer == "rock":print("You win!")if user == "scissors":if computer == "rock":print("You lose")elif computer == "paper":print("You win!")go_on = input("Do you want to play again? (Yes/No): ").lower()if go_on != "yes":break >>> Let's begin the game!>>> Please input rock, paper, or scissors: dasdsad>>> Please input rock, paper, or scissors: asdasd>>> Please input rock, paper, or scissors: Rock >>> The choice of the computer: paper >>> The choice of the user: rock >>> You lose>>> Do you want to play again? (Yes/No): yes>>> Please input rock, paper, or scissors: Paper >>> The choice of the computer: rock >>> The choice of the user: paper >>> You win!>>> Do you want to play again? (Yes/No): No為了保證電腦選擇的隨機(jī)性,我們需要導(dǎo)入random模塊。
因為一共三種選擇,所以我們需要定義列表存放選項,列表中的元素表示剪刀,石頭,布。
打印游戲開始信息。
由于需要反復(fù)執(zhí)行游戲,所以我們需要用while循環(huán)結(jié)構(gòu)。
首先讓電腦從列表中選擇一個作為自己的選項。
用戶需要借助于鍵盤的輸入,為了便于電腦判斷,我們統(tǒng)一轉(zhuǎn)為小寫。
若用戶輸入結(jié)果不在列表內(nèi),需要讓其反復(fù)輸入,直到輸入正確選項為止。
分別打印用戶和電腦的選擇結(jié)果。將用戶的選項與電腦選項做比較并給出判斷結(jié)果。
用戶輸入Yes/No來選擇是否繼續(xù)游戲。
以上便是石頭剪刀布游戲的全部內(nèi)容,感謝大家的收藏、點贊、評論。我們下一節(jié)將介紹問答游戲(Quiz Game),敬請期待~
總結(jié)
以上是生活随笔為你收集整理的Python编程基础:第三十七节 石头剪刀布游戏Rock, Paper, Scissors Game的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python编程基础:第三十六节 模块M
- 下一篇: Python编程基础:第三十八节 问答游