zoukankan      html  css  js  c++  java
  • python-乌龟和鱼游戏(面向对象实例)

    pygame
    游戏编程:按以下要求定义一个乌龟类和鱼类并尝试编写游戏
    假设游戏场景为范围(x,y)为0<=x<=10,0<=y<=10
    游戏生成1只乌龟和10条鱼
    它们的移动方向均随机
    乌龟的最大移动能力为2(它可以随机选择1还是2移动),鱼儿的最大移动能力是1
    当移动到场景边缘,自动向反方向移动
    乌龟初始化体力为100(上限)
    乌龟每移动一次,体力消耗1
    当乌龟和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20
    鱼暂不计算体力
    当乌龟体力值为0(挂掉)或者鱼儿的数量为0游戏结束
    参考网上写的:

    #python练习题之乌龟吃鱼游戏
    
    import random as r
    
    
    class Turtle:
        def __init__(self):
            ##初始化体力
            self.power=100
            ##初始位置
            self.x = r.randint(0,10)
            self.y = r.randint(0,10)
    
        def move(self):
            ##随机方向移动,位置发生改变,移动速度不能为0
            new_x =r.choice([-2,-1,1,2])
            new_y =r.choice([-2,-1,1,2])
    
            if 10>=self.x+new_x>=0:
    
                self.x+=new_x
            ##一定不能用if,因为如果用了if,上面if执行后继续执行下面的条件相当于执行了两遍的self.x+=new_x
            elif self.x+new_x<0 or self.x+new_x>10:
    
                self.x-=new_x
            if 0<=self.y+new_y<=10:
                self.y+=new_y
            elif self.y+new_y<0 or self.y+new_y>10:
                self.y-=new_y
    
            self.power -=1
            return self.x,self.y
        def eat(self):
            if self.power+20>100:
                return self.power
            else:
                self.power+=20
                return self.power
    
    class Fish():
        def __init__(self):
            ##初始位置
            self.x = r.randint(0,10)
            self.y = r.randint(0,10)
    
        def move(self):
            ##随机方向移动,位置发生改变,移动速度不能为0
            new_x = r.choice([-1, 1])
            new_y = r.choice( [-1, 1])
            if 0 <= self.x + new_x <= 10:
                self.x += new_x
            if self.x + new_x < 0 or self.x + new_x > 10:
                self.x -= new_x
    
            if 0 <= self.y + new_y <= 10:
                self.y += new_y
            if self.y + new_y < 0 or self.y + new_y > 10:
                self.y -= new_y
            return self.x,self.y
    t =Turtle()
    fish = []
    for i in range(0,10):
        fish.append(Fish())
    while True:
        if not len(fish):
            print('鱼被吃完了')
            break
        if not t.power:
            print('乌龟体力耗尽了')
            break
        pos = t.move()
        print("乌龟此时的位置:",pos)
    
        for each_fish in fish[:]:
            fish_pos=each_fish.move()
            if fish_pos==pos:
                #print('乌龟的位置',pos)
                t.eat()
                fish.remove(each_fish)
    
  • 相关阅读:
    Apollo服务搭建
    常用MIME类型
    eclipse 搭建 swagger-ui(maven项目 springboot框架)
    子页面iframe跨域执行父页面定义的JS方法
    SpringBoot 实现前后端分离的跨域访问(CORS)
    使用 QueryRunner 实现 JDBC 常用操作封装
    纯Java版本的JDBC基础操作,支持查询结果到泛型实体类的转换
    javascript_鼠标划词,弹出选取的词
    js获取url参数值
    纯CSS打造的下拉菜单
  • 原文地址:https://www.cnblogs.com/aqiong/p/13406914.html
Copyright © 2011-2022 走看看