charp37.1.11.游戏编程:按以下要求定义-个乌龟类和鱼类并尝试编写游戏。

要求:

1、假设游戏场景为范围(x, y)为0<=x<=10,0<=y<=10
2、游戏生成1只乌龟和10条鱼
3、它们的移动方向均随机
4、乌龟的最大移动能力是2 ( Ta可以随机选择1还是2移动) , 鱼儿的最大移动能力是1
5、当移动到场景边缘,自动向反方向移动
6、乌龟初始化体力为100(上限)
7、乌龟每移动- -次,体力消耗1
8、当乌龟和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20
9、鱼暂不计算体力
10、当乌龟体力值为0 (挂掉)或者鱼儿的数量为0游戏结束

问题:

1、为什么不用在def __init__(self,x,y)括号里面添加xy变量?

def __init__(self,x,y)

在括号里插入xy变量,xy为确定值,此处我要的是随机生成的值,所以:

import random

def __init__(self):
    self.x = random.randint(0, 10)
    self.y = random.randint(0, 10)
    print('随机化的初始位置为:%d %d' % (self.x, self.y))
    self.direction = input('请输入需要移动的方向,例如:上、下、左、右:')
    self.move = input('请输入需要移动的步数,可以选择1或2:')

答案只能说 我看懂了,让我自己写,真的不一定能写出来

import random

class Turtle:
    def __init__(self):
        self.x = random.randint(0, 10)
        self.y = random.randint(0, 10)
        self.stamina = 100

    def move(self):
        self.stamina -= 1
        move_distance = random.randint(1, 2)
        move_direction = random.choice(['up', 'down', 'left', 'right'])

        if move_direction == 'up':
            self.y += move_distance
        elif move_direction == 'down':
            self.y -= move_distance
        elif move_direction == 'left':
            self.x -= move_distance
        elif move_direction == 'right':
            self.x += move_distance

        self.check_boundaries()

    def check_boundaries(self):
        if self.x < 0:
            self.x = 0
        elif self.x > 10:
            self.x = 10

        if self.y < 0:
            self.y = 0
        elif self.y > 10:
            self.y = 10


class Fish:
    def __init__(self):
        self.x = random.randint(0, 10)
        self.y = random.randint(0, 10)

    def move(self):
        move_distance = random.randint(1, 1)
        move_direction = random.choice(['up', 'down', 'left', 'right'])

        if move_direction == 'up':
            self.y += move_distance
        elif move_direction == 'down':
            self.y -= move_distance
        elif move_direction == 'left':
            self.x -= move_distance
        elif move_direction == 'right':
            self.x += move_distance

        self.check_boundaries()

    def check_boundaries(self):
        if self.x < 0:
            self.x = 0
        elif self.x > 10:
            self.x = 10

        if self.y < 0:
            self.y = 0
        elif self.y > 10:
            self.y = 10


turtle = Turtle()
fishes = []
for _ in range(10):
    fish = Fish()
    fishes.append(fish)#不会

while turtle.stamina > 0 and len(fishes) > 0:
    turtle.move()
    for fish in fishes:
        if turtle.x == fish.x and turtle.y == fish.y:
            turtle.stamina += 20
            fishes.remove(fish)
            break

if turtle.stamina <= 0:
    print("游戏结束,乌龟体力耗尽!")
else:
    print("游戏结束,鱼儿被乌龟吃光!")

你可能感兴趣的:(conch的代码学习,游戏,python)