Skip to main content
 首页 » 编程设计

python之多个海龟,多个随机移动

2024年12月31日10JeffreyZhao

我有一项任务,我必须用 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() 

强有力的指导将非常有帮助。

请您参考如下方法:

您可以利用面向对象。这是我的乌龟脚本版本:

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() 

加油!只为这个很棒的乌龟脚本投一票?