我有一个任务,必须在Python中用乌龟制作游戏。 我能够生成自己想要的网格,并且能够生成多个不同的海龟。我的 -在弄清楚如何让三只 不同 乌龟中的每只乌龟随机地在整个棋盘上移动时,我不知道从哪里开始,而是停留在网格线上。 -在两只乌龟撞到屏幕边缘后,“游戏”必须停止,我也不知道该怎么做。
这是我到目前为止所拥有的:
import turtle
import random
turtle.pensize(2)
turtle.penup()
turtle.goto(-160,-160)
turtle.pendown()
turtle.color("green")
turtle.speed(0)
for i in range(4):
turtle.forward(320)
turtle.left(90)
for y in range(-160,160,80):
for x in range(-160,160,80):
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
for k in range(4):
turtle.forward(40)
turtle.left(90)
turtle.end_fill()
for y in range(-120,160,80):
for x in range(-120,160,80):
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
for k in range(4):
turtle.forward(40)
turtle.left(90)
billy = turtle.Turtle()
billy.shape("turtle")
billy.color("red")
billy.penup()
billy.left(90)
rick = turtle.Turtle()
rick.shape("turtle")
rick.color("orange")
rick.penup()
mike = turtle.Turtle()
mike.shape("turtle")
mike.color("purple")
mike.penup()
turtle.done()
强有力的指导将非常有帮助。
答案 0 :(得分:1)
您可以利用面向对象的优势。这是我的乌龟脚本版本:
import turtle
import random
# I added randint.
from random import randint
# Let's define a class so we can create turtles
class MyTurtle():
# Here's the constructor. Where we give some initial values.
def __init__(self, name, color):
self.name = name
self.color = color
self.turtle = turtle.Turtle()
self.turtle.shape("turtle")
self.turtle.color(self.color)
self.turtle.speed(1)
self.turtle.pd()
# We need to know if this turtle is off the board.
def off_board(self):
x = self.turtle.xcor()
y = self.turtle.ycor()
return x < -160 or 160 < x or y < -160 or 160 < y
# calling this will move the turtle in a random direction.
def move(self):
turn = randint(0,2)
if turn == 1:
self.turtle.lt(45)
elif turn == 2:
self.turtle.rt(45)
self.turtle.forward(5)
# Put your code for drawing the grid
# Let's create some turtles and start moving them.
turtles = []
turtles.append( MyTurtle('billy', 'red'))
turtles.append( MyTurtle('chris', 'blue'))
turtles.append( MyTurtle('lilly', 'pink'))
turtles.append( MyTurtle('kevin', 'green'))
ok = True
while ok:
for t in turtles:
t.move()
if t.off_board():
print ("Turtle %s wins!!!" % (t.name))
ok = False
turtle.done()