Implement a small game of rock-paper-scissors where a person plays rock-paper-scissors with a computer, and learn Python's loop control statements and conditional judgment statements.
If rock, scissors, and paper are represented by numbers 0, 1, and 2 respectively. So how to determine who wins and who loses? (Recommended learning: Python video tutorial)
Although it is a simple rock-paper-scissors game, there is actually a lot of algorithmic thinking behind it, and many rules can be found.
If the variables user and computer are equal, it is a tie
If (user 1) is divided by 3 and the remainder is equal to computer, the user (person) gets Victory
In other cases, the computer wins
import random # 初始化表示手势的变量 gesture = ['石头' , '剪刀', '布'] wins = 0 print("*********************") print("石头剪刀布游戏\nVer 1.0.0 by YuZhou_1su\n") # 进行5轮游戏 for i in range(5): # 输入玩家的手势 print("*********************") print("0:石头 1:剪刀 2:布") print("*********************") user = int(input("请输入你想出的序号:\n")) if(user >= 0 and user <= 2): computer = random.randint(0, 2) print("玩家: {0}, 计算机: {1}".format(gesture[user], gesture[computer])) if user == computer: print("...平局! ") elif computer == (user + 1) % 3: print("...玩家获胜! ") wins = wins + 1 else: print("...计算机获胜! ") else: print("***你输入的序号有错、请重新输入!***") print("玩家获胜次数: %d " % wins)
For more Python-related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How to write rock-paper-scissors in python. For more information, please follow other related articles on the PHP Chinese website!