> 文档中心 > Catch fox game 抓狐狸Python代码实现

Catch fox game 抓狐狸Python代码实现

Catch fox game 抓狐狸Python代码实现
实验描述
Write a program to simulate a fox catching game. Suppose there are a total of 5 holes in a row. The little fox is initially in one of the holes, and then the player opens a hole randomly. If there is a fox in it, he catches it. If there are no foxes in the hole, they will come again the next day, but the next day the fox will jump to the next hole before the player comes.
编写程序,模拟抓狐狸小游戏。假设一共有一排5 个洞口小狐狸最开始的时候在其中一个洞口,然后玩家随机打开一个洞口,如果里面有狐狸就抓到了。如果洞口里没有狐狸就第二天再来抓,但是第二天狐狸会在玩家来抓之前跳到隔壁洞口里。
实验目的

  1. Develop the ability to analyze problems and model them.
  2. Skillfully use lists to solve practical problems.
  3. Skillfully use the selection structure and cyclic structure to solve practical problems.
  4. Understand the execution flow of the loop structure with an else clause.
  5. Understand the use of exception handling structures to constrain user input.
    1、培养分析问题并对进行建模的能力。
    2、熟练使用列表解决实际问题。
    3、熟练运用选择结构和循环结构解决实际问题。
    4、理解带else 子句的循环结构执行流程。
    5、理解使用异常处理结构约束用户输入的用法。
    上代码
from random import *def mai():    print("=====================*抓狐狸*=========================")    n=10  #游戏次数    d=[1,2,3,4,5]   #洞口    day=1 #天数    f=randint(0,4)  #随机选择一个洞口作为小狐狸的藏身之处    while True: while True:     try:  cy=int(input("第{0}天,这里有五个洞口(1-5),选择一个打开,确定里面有没有小狐狸:".format(day)))  assert 1<=cy<=5  break     except:  print("请选择正确的洞口")      if cy==d[f]:#如果输入的洞口数为小狐狸的洞口,则胜利     print("恭喜你找到了小狐狸")     break else:     print("不好意思,你找错了") x=f if f==0:   #小狐狸在第一个洞口,只能向右走     f+=1 elif 0<f<4:   #小狐狸在中间,可以向两边走     f=x     while True:  f=randint(f-1,f+1)    #随机模拟小狐狸的走向  if f!=x:      #排除随机数与愿洞口重复      break else:     f-=1 #小狐狸在第一个洞口,只能向左走 n-=1 day+=1      #天数+1      if n==0:     print("放弃吧,你找不到的")     breakdef main():    mai()    while True: try:     a=input("请问是否重开一局,是请输入yes,否请输入no:")     assert a=='yes' or a=='no'     if a=='no':  print("游戏结束,祝您生活愉快!!!")  break     elif a=='yes':  mai() except:     print("请输入yes或no")if __name__=='__main__':    main()

运行结果
在这里插入图片描述