小游戏龟吃鱼

1. 游戏编程:按以下要求定义一个乌龟类和鱼类并尝试编写游戏。(初学者不一定可以完整实现,但请务必先自己动手,你会从中学习到很多知识的^_^)

假设游戏场景为范围(x, y)为0<=x<=10,0<=y<=10

游戏生成1只乌龟和10条鱼

它们的移动方向均随机

乌龟的最大移动能力是2(Ta可以随机选择1还是2移动),鱼儿的最大移动能力是1

当移动到场景边缘,自动向反方向移动

乌龟初始化体力为100(上限)

乌龟每移动一次,体力消耗1

当乌龟和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20

鱼暂不计算体力

当乌龟体力值为0(挂掉)或者鱼儿的数量为0游戏结束

import random
list1 = [[-1,0],[1,0],[0,1],[0,-1]] #穷举一次移动坐标的变化
class Turtle:
    def __init__(self):   #创建对象时,直接初始化乌龟坐标与体力
        self.x = random.randint(0,10)
        self.y = random.randint(0,10)
        self.power = 100
    def move(self):
        moves = random.randint(1,2)  #随机移动的步数
        count = 1
        while count <= moves:
            index = random.randint(0,3)
            a = list1[index][0]
            b = list1[index][1]
            self.x = self.border(self.x,a)
            self.y = self.border(self.y,b)
            count += 1
        self.power -= 1
    def eat(self):
        self.power += 20
    def border(self,turtle_x,move_a):   #当遇到边界问题的时候
        if turtle_x + move_a > 10 or turtle_x + move_a < 0:
            return turtle_x - move_a
        else:
            return turtle_x + move_a

class Fishs:
    def __init__(self):         #生成十条坐标随机的鱼
        for i in range(10):
            x = random.randint(0,10)
            y = random.randint(0,10)
            fish.append([x,y])
    def move(self):
        for i in range(len(fish)):         #对每条鱼进行一次随机移动
            index = random.randint(0,3)
            a = list1[index][0]
            b = list1[index][1]
            fish[i][0] = self.border(fish[i][0],a)
            fish[i][1] = self.border(fish[i][1],b)
    def border(self,fish_x,move_a):   #当遇到边界问题的时候
        if fish_x + move_a > 10 or fish_x + move_a < 0:
            return fish_x - move_a
        else:
            return fish_x + move_a
fish = []
t = Turtle()
f = Fishs()
while True:
    t.move()
    f.move()
    print('龟坐标:',t.x,t.y)
    print(fish)
    print('\n')
    if [t.x,t.y] in fish:
        t.eat()
        fish.remove([t.x,t.y])
        if len(fish) == 0:
            print('鱼吃光了')
            break
    if t.power == 0:
        print('坚持不住了')
        break

猜你喜欢

转载自blog.csdn.net/weixin_42389277/article/details/82527179