Python类和对象编写一个小游戏【含注释】

定义一个鱼类和龟类并编写游戏

  • 假设游戏场景为范围(x, y)为0<=x<=10,0<=y<=10
  • 游戏生成1只乌龟和10条鱼
  • 它们的移动方向均随机
  • 乌龟的最大移动能力是2(Ta可以随机选择1还是2移动),鱼儿的最大移动能力是1
  • 当移动到场景边缘,自动向反方向移动
  • 乌龟初始化体力为100(上限)
  • 乌龟每移动一次,体力消耗1
  • 当乌龟和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20
  • 鱼暂不计算体力
import random as r

old_x=[0,10]
old_y=[0,10]
class Turtle:
    def __init__(self):
        #每定义一个都要前面用self识别
        self.power=100
        #初始位置随机,(注意调用randint前有r)

        #????疑问为什么是old_x[1],new_x[1]
        #####解答:本人脑瓜子抽了,看列表索引值1代表10
        self.x=r.randint(old_x[0],old_x[1])
        self.y=r.randint(old_y[0],old_y[1])
    def move(self):
        #乌龟是移动1或2,随机移动,因此用列表定义比产生随机数简单
        #choice()从一个列表,元组或字符串返回一个随机项
        new_x=self.x+r.choice([-1,-2,1,2])
        new_y=self.y+r.choice([1,2,-1,-2])
        #横向移动不超过边界
        #关于为什么将old_x[0]和old_x[10]做边框而不是数值做边框的思考:这个游戏是定义在列表所在的存储空间内的,单纯的数值与列表的数值不是同一个存储空间
        if new_x>old_x[1]:
            self.x=old_x[1]-(new_x-old_x[1])
        elif new_x<old_x[0]:
            self.x=old_x[0]-(new_x-old_x[0])
        else:
            self.x=new_x
        # new_x=old_x出现了问题,原来最后的位置还是self.x,调用函数也要是self.x

        #纵坐标不超过边界与横坐标一样
        if new_y>old_y[1]:
            self.y=old_y[1]-(new_y-old_y[1])
        elif new_y<old_y[0]:
            self.y=old_y[0]-(new_y-old_y[0])
        else:
            self.y=new_y

        self.power-=1
        return (self.x,self.y)
    def eat(self):
        self.power+=20
        if self.power>100:
            self.power=100

#鱼的移动与乌龟大致类似了
class Fish:
    #class要小写
     def __init__(self):
        self.x=r.randint(old_x[0],old_x[1])
        self.y=r.randint(old_y[0],old_y[1])
     def move(self):
        new_x=self.x+r.choice([-1,1])
        new_y=self.y+r.choice([1,-1,])
        if new_x>old_x[1]:
            self.x=old_x[1]-(new_x-old_x[1])
        elif new_x<old_x[0]:
            self.x=old_x[0]-(new_x-old_x[0])
        else:
            self.x=new_x
        if new_y>old_y[1]:
            self.y=old_y[1]-(new_y-old_y[1])
        elif new_y<old_y[0]:
            self.y=old_y[0]-(new_y-old_y[0])
        else:
            self.y=new_y
        return (self.x,self.y)

turtle=Turtle()
#定义一个空列表
fish=[]
for i in range(10):
    #定义了10条鱼
    new_fish=Fish()
    fish.append(new_fish)
    #将十条鱼的坐标最终都添加到空列表里面

while True:
    #再再强调一遍,True一定要首字母大写
    if not len(fish):
        print("鱼吃完了,游戏结束!")
        break
    if not turtle.power:
        print("乌龟体力耗尽,挂掉了")
        break

#最终有些鱼是要被吃掉的
    pos=turtle.move()
    # 在迭代器中删除列表元素是非常危险的,经常会出现意想不到的问题,因为迭代器是直接引用列表的数据进行引用
    # 这里我们把列表拷贝给迭代器,然后对原列表进行删除操作就不会有问题了
    for each_fish in fish[:]:
    #fish[:]包含了全部列表
    #each_fish 10个中的任一条
        if each_fish.move()==pos:
        #鱼和乌龟位置相同
            turtle.eat()
            fish.remove(each_fish)
        #删除此鱼
            print("有一条鱼被吃掉了")

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>