[Basic knowledge of python] 10. Use Python to implement the rock-paper-scissors game-Function Practical Operation

introduction

Rock, Paper, Scissors is a classic hand-guessing game that is popular around the world. Through the programming language Python, we can easily implement this interesting little game. This article will introduce the rules of the rock-paper-scissors game and provide a complete code example written in Python.
rock paper scissors

game rules

The rules of rock paper scissors are very simple. It includes three options: rock, scissors, and paper. The winning and losing relationship between them is as follows:

  • Rock Wins Scissors: When the player chooses rock and the computer chooses scissors, rock wins.
  • Scissors win over paper: When the player chooses scissors and the computer chooses paper, scissors win.
  • Cloth wins stone: When the player chooses cloth and the computer chooses stone, cloth wins.

practice goals

Although this is a small game, there are many ways to implement it, so let's implement it in the simplest way first, and strive to master the basic syntax of Python and the use of the random module.
Therefore, the goal we will achieve is as follows:
play a rock-paper-scissors game with the computer: the computer randomly punches, and we can choose what to punch.

Step by step breakdown

Punch from both sides:

First, we have to let both sides choose to punch in order to determine the outcome.
We can set the variable computer_choice to represent the computer's punching choice, and set the variable user_choice to represent your punching choice.
For the computer's punch, we can use random.choice() to randomly select it; for our punch, we can manually enter the type of our punch.
In addition, judge your input: when the input content is not rock, paper, scissors, the computer will remind you 'Input error, please punch again' and punch again.
The code here is implemented as:

import random
# 出拳
punches = ['石头','剪刀','布']
computer_choice = random.choice(punches)
user_choice = ''
while True:
    user_choice=input('请输入‘石头’或者‘剪刀’或者‘布’:')
    if user_choice not in punches:
        print('您的输入有误,请重新出拳')
    else:
        break

Both sides show off their fists:

We have just implemented the punches of you and the computer. Next, we need to know what the punches of both parties are.

Use the print() function to print the results of Liangquan. The sample code is as follows:

# 亮拳
print('————战斗过程————')
print('电脑出拳为:{},你的出拳为{}'.format(computer_choice,user_choice))

Determine the outcome:

In the first two steps, after the computer and you have selected the type of punch and revealed the punch, there is only the last step left: judging the outcome based on the result.
According to the rules of the game, we can clearly know that the rules are as follows:

  • Rock Wins Scissors: When the player chooses rock and the computer chooses scissors, rock wins.
  • Scissors win over paper: When the player chooses scissors and the computer chooses paper, scissors win.
  • Cloth wins stone: When the player chooses cloth and the computer chooses stone, cloth wins.

So how to implement it in code? It should be enough to judge all these situations separately through the if method. The sample code is as follows:

# 判断胜负
if computer_choice==user_choice:
    print('这一把是平局')
elif computer_choice=='石头'and user_choice=='布':
    print('恭喜你赢了!')
elif computer_choice=='剪刀'and user_choice=='石头':
    print('恭喜你赢了!')
elif computer_choice=='布'and user_choice=='剪刀':
    print('恭喜你赢了!')
elif computer_choice=='石头'and user_choice=='剪刀':
    print('遗憾!电脑赢了这局!')
elif computer_choice=='剪刀'and user_choice=='布':
    print('遗憾!电脑赢了这局!')
elif computer_choice=='布'and user_choice=='石头':
    print('遗憾!电脑赢了这局!')
else:
    print('这是不可能的一种—————结果—————')

Optimization of winning and losing logic:

Although the above method can be implemented and is clear at a glance, it always feels very redundant. Friends who are good at thinking should also feel this way. So can it be optimized? The answer must be yes! The optimized sample code is as follows:

# 判断胜负
if user_choice == computer_choice:  # 使用if进行条件判断
    print('平局!')
elif (user_choice == '石头' and computer_choice == '剪刀') or (user_choice == '剪刀' and computer_choice == '布') or (user_choice == '布' and computer_choice == '石头'):
    print('你赢了!')
else:
    print('你输了!')

Implementation

The steps to write a rock-paper-scissors game using Python are as follows:

Introduce the random module:

At the beginning of the code, use import random to introduce Python's random module so that we can randomly select the computer's options in the game.

import random

Create a list of options:

Create a list containing rock, scissors, and paper, for example: options = ["rock", "scissors", "paper"].

punches = ['石头','剪刀','布']

Validate user input:

Use a loop to let the user enter their selections and validate them. If the user input is not rock, scissors or paper, give the corresponding error prompt and ask for input again.

user_choice = ''
user_choice = input('请出拳:(石头、剪刀、布)')  # 请用户输入选择
while user_choice not in punches:  # 当用户输入错误,提示错误,重新输入
    print('输入有误,请重新出拳')
    user_choice = input()

The computer randomly selects:

Use random.choice(options) to randomly select a computer's options from a list of options.

punches = ['石头','剪刀','布']
computer_choice = random.choice(punches)

Determine the relationship between victory and defeat:

According to the rules of the game, by comparing the choices of the player and the computer, the outcome is determined and the corresponding results are output.

if user_choice == computer_choice:  # 使用if进行条件判断
    print('平局!')
elif (user_choice == '石头' and computer_choice == '剪刀') or (user_choice == '剪刀' and computer_choice == '布') or (user_choice == '布' and computer_choice == '石头'):
    print('你赢了!')
else:
    print('你输了!')

Complete code

Here is the complete Python code example:

import random

options = ["石头", "剪刀", "布"]

while True:
    player_choice = input("请出拳(石头/剪刀/布):")
    
    if player_choice not in options:
        print("请输入有效的选择!")
        continue
    
    computer_choice = random.choice(options)
    
    print("玩家选择:" + player_choice)
    print("计算机选择:" + computer_choice)
    
    if player_choice == computer_choice:
        print("平局!")
    elif (player_choice == "石头" and computer_choice == "剪刀") or 
         (player_choice == "剪刀" and computer_choice == "布") or 
         (player_choice == "布" and computer_choice == "石头"):
        print("玩家获胜!")
    else:
        print("计算机获胜!")
    
    break

Run the example

Here are some example inputs and outputs:

请出拳(石头/剪刀/布):石头
玩家选择:石头
计算机选择:剪刀
玩家获胜!

请出拳(石头/剪刀/布):剪刀
玩家选择:剪刀
计算机选择:布
玩家获胜!

请出拳(石头/剪刀/布):布
玩家选择:布
计算机选择:石头
玩家获胜!

Summarize

Through this article, we learned how to use Python to write a rock-paper-scissors game. We introduced the random module to implement random selection by the computer, and judged the outcome based on the rules of the game. The implementation process of this small game is not complicated, and it also gives us room to expand and improve the code.
When playing this game in real life, the outcome may be determined by one game, or it may be a best of three games, a best of three games, a best of five games, or a best of seven games... If you consider entering this situation, what should the code be
? So, here is a more advanced version of the complete code. Friends with a solid foundation can refer to it in detail, which is very helpful for function growth~

import random
import time
pool=['石头','剪刀','布']
#creatChoice函数用来生成AI的出拳结果和玩家的出拳结果
def creatChoice ():
    AI=random.choice(pool)
    player=''
    while player not in pool:
        player=input('请出拳:(选择石头、剪刀、布)')
    print('玩家出拳为:'+player)
    print('AI出拳为:'+AI)
    return AI,player
#fighting函数是单局战斗结果的计算
def fighting (AI,player):
    if AI==player:
        print('平局')
        return 0
    elif pool.index(AI)-pool.index(player)==-1:
        print('AI赢')
        return -1
    else:
        print('玩家赢')
        return 1
#print(fighting('剪刀','石头'))
#统计胜利次数函数(参数为游戏总局数)
def fightCount (sumnum):
    result=0
    for i in range(sumnum):
        print('      -----第{}次猜拳-----'.format(i+1))
        a,b=creatChoice()
#        fighting(a,b)
        result+=fighting(a,b)
        time.sleep(1.5)
    print('-------------最终结果--------------')
    if result<0:
        print('AI获胜,多赢了{}次'.format(abs(result)))
    elif result>0:
        print('玩家获胜,多赢了{}次'.format(result))
    else:
        print('竟然是平局,玩家和AI各赢了{}次'.format(result))
#config函数是让用户输入猜拳的总局数的
def config ():
    sumnum=int(input('请输入一共要猜拳几次:(请输入整数)'))
    return sumnum
#jixu函数是判断用户是否继续玩
def jixu():
    flag=False
    choice=input('输入 y 继续游戏,其他任意键退出游戏')
    if choice=='y'or choice=='Y':
        flag=True
    else:
        flag=False
    return flag        

def main():
    print('---------------游戏开始--------------')
    gamecount=config()
    fightCount(gamecount)
    while jixu():
        gamecount=config()
        fightCount(gamecount)
    else:
        print('------游戏结束,欢迎下次再来玩-----')
        
main()

Conclusion

Please try to run this mini-game and make inferences yourself to modify the application. Through this process, you can better understand the Python programming language and improve your programming skills.
If you want to learn Python in depth, please follow my blog, follow the big brother to not get lost, and lead you to achieve more success on the road of programming!

Guess you like

Origin blog.csdn.net/qq_41308872/article/details/132142281