关于《零基础入门学习Python》课后作业037讲类和对象面向对象编程最后1题乌龟吃鱼游戏
啊首先说一下我是0基础自学编程的,好多知识点都感觉一知半解,然后这个乌龟吃鱼的题我在看答案之前自己琢磨出来的,没敢用迭代,关于课程里讲到的self用法也不太明白,希望能有大佬对我的代码提出意见建议、以及不好的习惯、可以改进简化的地方,在这里先感谢大佬,以下是代码:class Game():
origin = (0, 0) # 原点
legal_x = [-5, 5]# x轴的移动范围
legal_y = [-5, 5]# y轴的移动范围
#设定游戏场景范围
# 随机生成位置
def rand():
import random
x = random.randint(-5, 6)
y = random.randint(-5, 6)
return (x, y)
# 鱼移动方法
def fish_moving(x, y):
import random
# direction参数设置方向,1为向右(向上),-1为向左(向下),0为不移动(当前为必须移动)
direction = [-1, 1]
# step参数设置移动的距离
step =
new_x = x + random.choice(direction) * random.choice(step)
new_y = y + random.choice(direction) * random.choice(step)
# 检查移动后是否超出x轴边界
if new_x < Game.legal_x:
pos_x = Game.legal_x - (new_x - Game.legal_x)
elif new_x > Game.legal_x:
pos_x = Game.legal_x - (new_x - Game.legal_x)
else:
pos_x = new_x
# 检查移动后是否超出y轴边界
if new_y < Game.legal_y:
pos_y = Game.legal_y - (new_y - Game.legal_y)
elif new_y > Game.legal_y:
pos_y = Game.legal_y - (new_y - Game.legal_y)
else:
pos_y = new_y
return pos_x, pos_y
# 龟移动方法
def tortoise_moving(x, y):
import random
# direction参数设置方向,1为向右(向上),-1为向左(向下),0为不移动(当前为必须移动)
direction = [-1, 1]
# step参数设置移动的距离
step =
new_x = x + random.choice(direction) * random.choice(step)
new_y = y + random.choice(direction) * random.choice(step)
# 检查移动后是否超出x轴边界
if new_x < Game.legal_x:
pos_x = Game.legal_x - (new_x - Game.legal_x)
elif new_x > Game.legal_x:
pos_x = Game.legal_x - (new_x - Game.legal_x)
else:
pos_x = new_x
# 检查移动后是否超出y轴边界
if new_y < Game.legal_y:
pos_y = Game.legal_y - (new_y - Game.legal_y)
elif new_y > Game.legal_y:
pos_y = Game.legal_y - (new_y - Game.legal_y)
else:
pos_y = new_y
return pos_x, pos_y
# 游戏开始
print('游戏开始啦!')
# 生成1只乌龟和10条鱼
tortoise = Game.rand()
fish1 = Game.rand()
fish2 = Game.rand()
fish3 = Game.rand()
fish4 = Game.rand()
fish5 = Game.rand()
fish6 = Game.rand()
fish7 = Game.rand()
fish8 = Game.rand()
fish9 = Game.rand()
fish10 = Game.rand()
# 游戏场景内
list_pool =
# 测试
#print('初始生成')
#print(list_pool)
power = 100 # 龟体力
i = 1
# 移动
while power > 0 and len(list_pool) > 1:
# 比较函数
def compare(x):
if x == 0:
return 0
else:
new_fish = Game.fish_moving(x, x)
if new_fish == tortoise:
print('第%d次鱼被吃掉啦!' % i)
global power
power += 20
return 0
else:
return new_fish
# 龟、鱼移动
tortoise = Game.tortoise_moving(tortoise, tortoise)
fish1 = compare(fish1)
fish2 = compare(fish2)
fish3 = compare(fish3)
fish4 = compare(fish4)
fish5 = compare(fish5)
fish6 = compare(fish6)
fish7 = compare(fish7)
fish8 = compare(fish8)
fish9 = compare(fish9)
fish10 = compare(fish10)
list_pool =
# 在列表中移除已被吃掉的鱼
k = 1
while k:
if 0 in list_pool:
list_pool.remove(0)
k = 1
else:
k = 0
# 测试
i += 1
#print(list_pool)
power -= 1
if power == 0:
print('乌龟体力耗尽!还剩%d条鱼!' % (len(list_pool) - 1))
else:
print('鱼被吃光啦!乌龟剩余%d体力!' % power)
print('游戏结束!')
# 待解决问题:鱼被吃掉时显示第几条鱼被吃掉
{:9_227:} {:10_279:}{:10_279:}
页:
[1]