|
发表于 2019-8-9 18:45:26
|
显示全部楼层
对代码进行修改,现在代码可以调节小鱼数量、乌龟体力、活动范围、游戏开始与结束
代码如下:
import random
class Move_step:
def __init__(self,right,left,top,bottom):
self.right = right
self.left = left
self.top = top
self.bottom = bottom
def move(self,breed):
i=random.randint(0,3)
self.direction=[1,2,3,4][i] #代表移动的方向,分别对应 +x,+y,-x,-y
if breed == 'wugui':
move_distance=random.randint(1,2)
self.energy -= 1 * move_distance
else:
move_distance=1 #代表移动的大小
for i in range(move_distance):
if self.left <= self.x <= self.right or self.bottom <= self.y <= self.top:
if self.direction == 1:
if self.x == self.right:
self.x = self.left + 1
else:
self.x += 1
elif self.direction == 2:
if self.y == self.top:
self.y = self.bottom + 1
else:
self.y += 1
elif self.direction == 3:
if self.x == self.left:
self.x == self.right - 1
else:
self.x -= 1
elif self.direction == 4:
if self.y == self.bottom:
self.y = self.top - 1
else:
self.y -= 1
else:
print('报错',(self.x,self.y))
class Turtle(Move_step):
def __init__(self,energy,right,left,top,bottom):
super().__init__(right,left,top,bottom)
self.energy = energy
self.x=random.randint(self.left,self.right)
self.y=random.randint(self.top,self.bottom) #乌龟坐标值初始化
class Fish(Move_step):
def __init__(self,right,left,top,bottom):
super().__init__(right,left,top,bottom)
self.x=random.randint(self.left,self.right)
self.y=random.randint(self.top,self.bottom) #鱼坐标值初始化
def game():
a,b,c,d = map(int,input('请输入游戏范围的上、下、左、右【整数】,并以空格隔开:').split())
if a < b or d < c:
print("哎呀,范围出错啦")
return
energy = int(input('你希望乌龟的体力是:'))
wugui=Turtle(energy,a,b,c,d)
fish=[]
fish_num = input('小鱼的数量:')
for i in range(int(fish_num)):
fish.append(Fish(a,b,c,d))
while 1:
wugui.move('wugui')
for each in fish:
each.move('fish')
for each in fish:
if each.x==wugui.x and each.y==wugui.y:
fish.remove(each)
print('有一条鱼被吃掉了')
wugui.energy+=20
if fish==[]:
print('wuguiasdsssssssssssssssssssssssssss胜利')
break
if wugui.energy<=0:
print('yu胜利')
break
while 1:
print("开始游戏请输入1,结束游戏请输入0")
start = input('请输入:')
if start == '1':
game()
else:
print("游戏结束!")
break |
|