博客
关于我
python小游戏:猜数字和石头、剪刀、布
阅读量:798 次
发布时间:2023-04-15

本文共 1680 字,大约阅读时间需要 5 分钟。

一、猜数字

用Python编写一个简单的“猜数字”游戏。程序随机生成一个1到20之间的数字,玩家需要通过连续猜测6次来猜出这个数字。以下是游戏的具体实现代码:

import randomsecret_number = random.randint(1, 20)  print("我在想一个1到20之间的数字")  for guesses_taken in range(1, 7):      print("请猜测")      guess = int(input())      if guess < secret_number:          print("你的猜测太低了")      elif guess > secret_number:          print("你的猜测太高了")      else:          break  if guess == secret_number:      print(f"好极了!你用了{guesses_taken}次猜测猜中了我的数字!")  else:      print(f"不对啊,我想的数字是{secret_number}")

二、石头、剪刀、布

与“猜数字”类似,这个小游戏利用随机模块生成电脑的选择,并根据玩家的输入判断胜负或平局。以下是游戏的实现代码:

import random  wins = 0  losses = 0  ties = 0  while True:      print(f"{wins}胜,{losses}负,{ties}平")      while True:          print("请输入你的选择:r(石头)、s(剪刀)、p(布)、q(退出)")          player_choice = input().lower()          if player_choice == 'q':              sys.exit()          if player_choice in ['r', 's', 'p']:              break          print("请输入正确的选择:r、s、p或q")      print(f"你选择了:{player_choice}")      if player_choice == 'r':          print("你选了石头")      elif player_choice == 's':          print("你选了剪刀")      else:          print("你选了布")      computer_choice = random.choice(['r', 's', 'p'])      print(f"电脑选了:{computer_choice}")      if player_choice == computer_choice:          print("平局!")          ties += 1      else:          if (player_choice == 'r' and computer_choice == 's') or (player_choice == 's' and computer_choice == 'p') or (player_choice == 'p' and computer_choice == 'r'):              print("你赢了!石头剪刀布中,你的选择更占优势。")              wins += 1          else:              print("你输了!电脑的选择更优。")              losses += 1      if input("继续游戏(输入任意键继续,q退出):").lower() == 'q':          sys.exit()

转载地址:http://yzgfk.baihongyu.com/

你可能感兴趣的文章
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>