📅  最后修改于: 2020-05-20 03:27:55             🧑  作者: Mango
Python是一种多用途语言,可以用它做任何事情。Python也可以用于游戏开发。让我们创建一个简单的命令行剪刀石头布游戏,而无需使用任何外部游戏库(例如PyGame)。
在这个游戏中,用户有第一机会在石头,布和剪刀中选择选项。在该计算机从其余两个选择中(随机)选择之后,将根据规则确定获胜者。
获奖规则如下:
石头vs布->布胜
石头vs剪刀->石头胜利
布vs剪刀->剪刀胜。
在此游戏中,randint()内置函数用于生成给定范围内的随机整数值。
下面是实现:
# 导入随机模块
import random
# 打印多行指令执行字符串的字符串连接
print("Winning Rules of the Rock paper scissor game as follows: \n"
+"Rock vs paper->paper wins \n"
+ "Rock vs scissor->Rock wins \n"
+"paper vs scissor->scissor wins \n")
while True:
print("Enter choice \n 1. Rock \n 2. paper \n 3. scissor \n")
# 接受用户的输入
choice = int(input("User turn: "))
# 如果任一条件为真,则OR为短路算子,然后返回真值循环,直到用户输入无效输入
while choice > 3 or choice < 1:
choice = int(input("enter valid input: "))
# 初始化与选择值相对应的choice_name变量的值
if choice == 1:
choice_name = 'Rock'
elif choice == 2:
choice_name = 'paper'
else:
choice_name = 'scissor'
# 打印用户选择
print("user choice is: " + choice_name)
print("\nNow its computer turn.......")
# 计算机从1、2和3中随机选择任何数字。使用随机模块的randint方法
comp_choice = random.randint(1, 3)
# 循环直到comp_choice值等于选择值
while comp_choice == choice:
comp_choice = random.randint(1, 3)
# 初始化与选择值对应的comp_choice_name变量的值
if comp_choice == 1:
comp_choice_name = 'Rock'
elif comp_choice == 2:
comp_choice_name = 'paper'
else:
comp_choice_name = 'scissor'
print("Computer choice is: " + comp_choice_name)
print(choice_name + " V/s " + comp_choice_name)
# 获胜条件
if((choice == 1 and comp_choice == 2) or
(choice == 2 and comp_choice ==1 )):
print("paper wins => ", end = "")
result = "paper"
elif((choice == 1 and comp_choice == 3) or
(choice == 3 and comp_choice == 1)):
print("Rock wins =>", end = "")
result = "Rock"
else:
print("scissor wins =>", end = "")
result = "scissor"
# 打印用户或计算机获胜
if result == choice_name:
print("<== User wins ==>")
else:
print("<== Computer wins ==>")
print("Do you want to play again? (Y/N)")
ans = input()
# 如果用户输入n或N,则条件为True
if ans == 'n' or ans == 'N':
break
# 从while循环中出来后,我们感谢您的参与
print("\nThanks for playing")
输出:
winning Rules of the Rock paper and scissor game as follows:
rock vs paper->paper wins
rock vs scissors->rock wins
paper vs scissors->scissors wins
Enter choice
1. Rock
2. paper
3. scissor
User turn: 1
User choice is: Rock
Now its computer turn.......
computer choice is: paper
Rock V/s paper
paper wins =>computer wins
do you want to play again?
N