怎么优化这段课后作业代码?
课后作业的部分代码:规则(乌龟部分)是乌龟在(0,0)到(10,10)内的正方形区域移动,每次步幅不超过2(可以是1),碰到边界往反方向移动…
我看答案乌龟x坐标动完就得移y坐标,但是不是有其他情况如连续移两次x坐标等等,是否有办法实现往不同方向移动的需求?
部分代码如下:
import random as r
legal_x =
legal_y =
class Turtle:
def __init__(self):
# 初始体力
self.power = 100
# 初始位置随机
self.x = r.randint(legal_x, legal_x)
self.y = r.randint(legal_y, legal_y)
def move(self):
# 随机计算方向并移动到新的位置(x, y)
new_x = self.x + r.choice()
new_y = self.y + r.choice()
就是new_x和new_y这一段,后面就是关于边界返回的部分了 def move(self):
m = r.choice()
new_x = self.x + int(m.imag)
new_y = self.y + int(m.real) kogawananari 发表于 2021-8-7 23:54
def move(self):
m = r.choice(
import random as r
class Turtle:
def __init__(self):
self.x = r.randint(0,10)
self.y = r.randint(0,10)
self.blood = 100
def move(self):
m = r.choice([0+1j, 0+2j, 0-1j, 0-2j,
1+0j, 1+1j, 1-1j, -1-0j, -1-1j, -1+1j, 2+0j, -2+0j])
self.x += int(m.imag)
self.y += int(m.real)
self.blood -= 1
if self.x < 0:
self.x = -self.x
if self.x > 10:
self.x = 20-self.x
elif 0 <= self.x <= 10:
self.x =self.x
if self.y < 0:
self.y = -self.y
if self.y > 10:
self.y = 20-self.y
else:
self.y =self.y
print(self.x,self.y)
def eat(self):
self.blood += 20
if self.blood >= 100:
self.blood = 100
class Fish:
def __init__(self):
self.x = r.randint(0,10)
self.y = r.randint(0,10)
def move(self):
m = r.choice()
self.x += int(m.imag)
self.y += int(m.real)
if self.x < 0:
self.x = -self.x
if self.x > 10:
self.x = 20-self.x
elif 0 <= self.x <= 10:
self.x =self.x
if self.y < 0:
self.y = -self.y
if self.y > 10:
self.y = 20-self.y
else:
self.y = self.y
print(self.x,self.y)
fish = []
turtle = Turtle()
for i in range(10):
new_fish = Fish()
fish.append(new_fish)
while True:
if fish == []:
print("鱼被吃光了,游戏结束!")
break
if turtle.blood <= 0:
print("乌龟体力值不足,游戏结束!")
break
pos = turtle.move()
for each_fish in fish[:]:
if each_fish.move() == pos:
# 鱼儿被吃掉了
turtle.eat()
fish.remove(each_fish)
print("有一条鱼儿被吃掉了...")
那能帮我解释一下这两处print换成return有什么区别吗?我运行起来好像不太一样 kogawananari 发表于 2021-8-7 23:54
def move(self):
m = r.choice(
规则是:
假设游戏场景为范围(x, y)为0<=x<=10,0<=y<=10
游戏生成1只乌龟和10条鱼
它们的移动方向均随机
乌龟的最大移动能力是2(Ta可以随机选择1还是2移动),鱼儿的最大移动能力是1
当移动到场景边缘,自动向反方向移动
乌龟初始化体力为100(上限)
乌龟每移动一次,体力消耗1
当乌龟和鱼坐标重叠,乌龟吃掉鱼,乌龟体力增加20
鱼暂不计算体力
当乌龟体力值为0(挂掉)或者鱼儿的数量为0游戏结束 kogawananari 发表于 2021-8-7 23:54
def move(self):
m = r.choice(
哦,没事了,懂了
页:
[1]