鱼C论坛

 找回密码
 立即注册
查看: 3803|回复: 0

[学习笔记] 乌龟吃鱼

[复制链接]
发表于 2018-2-23 17:39:58 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
自己写了大部分,就差吃鱼的没写好。参照了鱼兄的。
  1. import random as r

  2. class Turtle:

  3.     def __init__(self):
  4.         self.live=100
  5.         self.x=r.randint(0,10)
  6.         self.y=r.randint(0,10)
  7.    
  8.     def move(self):
  9.         new_x=self.x+r.choice([-2,-1,1,2])
  10.         new_y=self.y+r.choice([-2,-1,1,2])

  11.         if new_x>10 :
  12.             self.x=10-(new_x-10)
  13.         elif new_x<0:
  14.             self.x=abs(new_x)
  15.         else:
  16.             self.x=new_x
  17.             
  18.         if new_y>10:
  19.             self.y=10-(new_y-10)
  20.         elif new_y<0:
  21.             self.y=abs(new_y)
  22.         else:
  23.             self.y=new_y
  24.             
  25.         self.live-=1
  26.         return self.x,self.y

  27.     def eat(self):
  28.         self.live+=20
  29.         if self.live>100:
  30.             self.live=100
  31.         
  32. class Fish:

  33.     def __init__(self):

  34.         self.x=r.randint(0,10)
  35.         self.y=r.randint(0,10)

  36.     def move(self):
  37.         new_x=self.x+r.choice([-1,1])
  38.         new_y=self.y+r.choice([-1,1])

  39.         if new_x>10 :
  40.             self.x=10-(new_x-10)
  41.         elif new_x<0:
  42.             self.x=abs(new_x)
  43.         else:
  44.             self.x=new_x
  45.             
  46.         if new_y>10:
  47.             self.y=10-(new_y-10)
  48.         elif new_y<0:
  49.             self.y=abs(new_y)
  50.         else:
  51.             self.y=new_y

  52.         return self.x,self.y

  53. def gamestart():
  54.         
  55.     while True:        
  56.         if turtle.live==0:
  57.             print("乌龟饿死了,游戏结束")
  58.             break
  59.         if len(fishs)==0:
  60.             print("鱼被吃光了,游戏结束")
  61.             break

  62.         turtle_pos=turtle.move()

  63.         for each_fish in fishs:
  64.             if each_fish.move()==turtle_pos:
  65.                 turtle.eat()
  66.                 fishs.remove(each_fish)
  67.                 print("吃掉了一条鱼,剩下%d条" % len(fishs))               
  68.                
  69. fishs=[]
  70. turtle=Turtle()
  71. for i in range(20):
  72.     new_fish=Fish()
  73.     fishs.append(new_fish)

  74. gamestart()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-14 11:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表