博客
关于我
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/

你可能感兴趣的文章
mysql-connector-java各种版本下载地址
查看>>
mysql-group_concat
查看>>
MySQL-【4】基本操作
查看>>
Mysql-丢失更新
查看>>
Mysql-事务阻塞
查看>>
Mysql-存储引擎
查看>>
mysql-开启慢查询&所有操作记录日志
查看>>
MySQL-数据目录
查看>>
MySQL-数据页的结构
查看>>
MySQL-架构篇
查看>>
MySQL-索引的分类(聚簇索引、二级索引、联合索引)
查看>>
Mysql-触发器及创建触发器失败原因
查看>>
MySQL-连接
查看>>
mysql-递归查询(二)
查看>>
MySQL5.1安装
查看>>
mysql5.5和5.6版本间的坑
查看>>
mysql5.5最简安装教程
查看>>
mysql5.6 TIME,DATETIME,TIMESTAMP
查看>>
mysql5.6.21重置数据库的root密码
查看>>
Mysql5.6主从复制-基于binlog
查看>>