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