将Turtle.write函数更新为计数器

时间:2016-11-15 03:38:29

标签: python methods counter turtle-graphics

所以在这个模拟中,我有熊,鱼和植物在网格上做各种各样的事情。一旦模拟开始,我有来自模拟函数的变量更新了fishCount和bearCount下的世界类构造函数中的熊和鱼的数量。我在世界级的另一种方法是龟。将熊和海龟的数量作为计数器。两个问题。每个生物的初始计数在启动时是错误的,当通过繁殖更新计数时,showCounts方法会继续写入先前的计数,使其难以阅读。我想让它在每次制作新熊/鱼或者死亡时更新屏幕上的计数。

这是我的代码:

from math import *
from turtle import *
from random import *
import turtle
import random
import math

def mainSimulation():
    numberOfBears = 5
    numberOfFish = 5
    numberOfPlants = 5
    worldLifeTime = 2500
    worldWidth = 30
    worldHeight = 25

    myworld = World(worldWidth,worldHeight,numberOfBears,numberOfFish)
    myworld.draw()
    myworld.getBearStarvePass()
    myworld.getBearBreedPass()
    myworld.setBearStarvePass(25)
    myworld.setBreedPass(3)
    myworld.getFishOvercrowdNum()
    myworld.getFishBreedPass()
    myworld.setFishOvercrowdNum(5)
    myworld.setFishBreedPass(2)

    for i in range(numberOfFish):
        newfish = Fish(myworld)
        x = random.randrange(myworld.getMaxX())
        y = random.randrange(myworld.getMaxY())
        while not myworld.emptyLocation(x,y):
            x = random.randrange(myworld.getMaxX())
            y = random.randrange(myworld.getMaxY())
        myworld.addThing(newfish,x,y)

    for i in range(numberOfBears):
        newbear = Bear(myworld)
        x = random.randrange(myworld.getMaxX())
        y = random.randrange(myworld.getMaxY())
        while not myworld.emptyLocation(x,y):
            x = random.randrange(myworld.getMaxX())
            y = random.randrange(myworld.getMaxY())
        myworld.addThing(newbear,x,y)

    for i in range(numberOfPlants):
        newplant = Plant()
        x = random.randrange(myworld.getMaxX())
        y = random.randrange(myworld.getMaxY())
        while not myworld.emptyLocation(x,y):
            x = random.randrange(myworld.getMaxX())
            y = random.randrange(myworld.getMaxY())
        myworld.addThing(newplant,x,y)

    for i in range(worldLifeTime):
        myworld.liveALittle()
        myworld.showCounts()


    myworld.freezeWorld()

这是世界级的

class World:
    def __init__(self,mx,my,bear,fish):
        self.maxX = mx
        self.maxY = my
        self.thingList = []
        self.grid = []
        self.bearCount = bear
        self.fishCount = fish
        self.fishOvercrowdNum = 0
        self.fishBreedNum =0
        self.bearStarvePass = 0
        self.bearBreedPass = 0

        for arow in range(self.maxY):
            row=[]
            for acol in range (self.maxX):
                row.append(None)
            self.grid.append(row)

        self.wturtle = turtle.Turtle()
        self.wscreen = turtle.Screen()
        self.wscreen.setworldcoordinates(0,0,self.maxX-1,self.maxY-1)
        self.wscreen.addshape("E:/Python/Lib/idlelib/Bear.gif")
        self.wscreen.addshape("E:/Python/Lib/idlelib/Fish.gif")
        self.wscreen.addshape("E:/Python/Lib/idlelib/Plant.gif")
        self.wturtle.hideturtle()

    def getBearStarvePass(self):
        return self.bearStarvePass

    def getBearBreedPass(self):
        return self.bearBreedPass

    def setBearStarvePass(self, newNum):
        self.bearStarvePass = newNum

    def setBreedPass(self, newNum):
        self.bearBreedPass = newNum

    def getFishOvercrowdNum(self):
        return self.fishOvercrowdNum

    def getFishBreedPass(self):
        return self.fishBreedNum

    def setFishOvercrowdNum(self, newNum):
        self.fishOvercrowdNum = newNum

    def setFishBreedPass(self, newNum):
        self.fishBreedNum = newNum

    def showCounts(self):
        bearCount = self.bearCount
        fishCount = self.fishCount
        self.wturtle.write("Bear: %d Fish: %d " % (bearCount, fishCount), move = False)

    def getNumBears(self):
        return self.bearCount

    def getNumFish(self):
        return self.fishCount

    def incBear(self):
        self.bearCount = self.bearCount + 1

    def incFish(self):
        self.fishCount = self.fishCount + 1

    def decBear(self):
        self.bearCount = self.bearCount - 1

    def decFish(self):
        self.fishCount = self.fishCount - 1



    def draw(self):
        self.wscreen.tracer(0)
        self.wturtle.forward(self.maxX-1)
        self.wturtle.left(90)
        self.wturtle.forward(self.maxY-1)
        self.wturtle.left(90)
        self.wturtle.forward(self.maxX-1)
        self.wturtle.left(90)
        self.wturtle.forward(self.maxY-1)
        self.wturtle.left(90)
        for i in range(self.maxY-1):
            self.wturtle.forward(self.maxX-1)
            self.wturtle.backward(self.maxX-1)
            self.wturtle.left(90)
            self.wturtle.forward(1)
            self.wturtle.right(90)
        self.wturtle.forward(1)
        self.wturtle.right(90)
        for i in range(self.maxX-2):
            self.wturtle.forward(self.maxY-1)
            self.wturtle.backward(self.maxY-1)
            self.wturtle.left(90)
            self.wturtle.forward(1)
            self.wturtle.right(90)
        self.wscreen.tracer(1)



    def freezeWorld(self):
        self.wscreen.exitonclick()

    def addThing(self,athing,x,y):
        a = 0
        athing.setX(x)
        athing.setY(y)
        self.grid[y][x] = athing
        athing.setWorld(self)
        self.thingList.append(athing)
        athing.appear()
        if isinstance(athing, Bear):
            self.bearCount = self.bearCount + 1
        elif isinstance(athing, Fish):
            self.fishCount = self.fishCount + 1

    def delThing (self, athing):
        athing.hide()
        self.grid[athing.getY()][athing.getX()] = None
        self.thingList.remove(athing)

    def moveThing(self,oldx,oldy,newx,newy):
        self.grid[newy][newx] = self.grid[oldy][oldx]
        self.grid[oldy][oldx] = None

    def getMaxX(self):
        return self.maxX

    def getMaxY(self):
        return self.maxY

    def liveALittle(self):
        if self.thingList != [ ]:
            athing = random.randrange(len(self.thingList))
            randomthing = self.thingList[athing]
            randomthing.liveALittle()

    def emptyLocation(self,x,y):
        if self.grid[y][x] == None:
            return True
        else:
            return False

    def lookAtLocation(self,x,y):
        return self.grid[y][x]

这是熊类

class Bear:
    def __init__(self, theWorld):
        self.turtle=turtle.Turtle()
        self.turtle.up()
        self.turtle.hideturtle()
        self.turtle.shape("E:/Python/Lib/idlelib/Bear.gif")
        self.offsetList = [(-1,1) ,(0,1) ,(1,1),
                            (-1,0)        ,(1,0),
                            (-1,-1),(0,-1),(1,-1)]
        self.theWorld = theWorld
        self.bearStarvePass = self.theWorld.bearStarvePass
        self.bearBreedPass = self.theWorld.bearBreedPass

        self.xpos=0
        self.ypos=0
        self.world=None

        self.starveTick=0
        self.breedTick=0

    def setX(self, newx):
        self.xpos = newx

    def setY(self, newy):
        self.ypos = newy

    def getX(self):
        return self.xpos

    def getY(self):
        return self.ypos

    def setWorld(self, aworld):
        self.world = aworld

    def appear(self):
        self.turtle.goto(self.xpos, self.ypos)
        self.turtle.showturtle()

    def hide(self):
        self.turtle.hideturtle()

    def move(self, newx, newy):
        self.world.moveThing(self.xpos, self.ypos, newx, newy)
        self.xpos = newx
        self.ypos = newy
        self.turtle.goto(self.xpos, self.ypos)


    def liveALittle(self):
        self.breedTick = self.breedTick + 1
        if self.breedTick >= self.bearBreedPass:
            self.tryToBreed()

        self.tryToEat()

        if self.starveTick == self.bearStarvePass:
            self.world.delThing(self)
        else:
            self.tryToMove()

    def tryToMove(self):
        randomOffsetIndex = random.randrange(len(self.offsetList))
        randomOffset = self.offsetList[randomOffsetIndex]
        nextx=self.xpos + randomOffset[0]
        nexty=self.ypos + randomOffset[1]
        while not(0 <= nextx < self.world.getMaxX() and
                  0 <= nexty < self.world.getMaxY() ):
            randomOffsetIndex = random.randrange(len(self.offsetList))
            randomOffset = self.offsetList[randomOffsetIndex]
            nextx=self.xpos + randomOffset[0]
            nexty=self.ypos + randomOffset[1]

        if self.world.emptyLocation(nextx,nexty):
            self.move(nextx,nexty)


    def tryToBreed(self):
        randomOffsetIndex = random.randrange(len(self.offsetList))
        randomOffset = self.offsetList[randomOffsetIndex]
        nextx = self.xpos + randomOffset[0]
        nexty = self.ypos + randomOffset[1]
        while not(0 <= nextx < self.world.getMaxX() and 0 <= nexty < self.world.getMaxY()):
            randomOffsetIndex = random.randrange(len(self.offsetList))
            randomOffset = self.offsetList[randomOffsetIndex]
            nextx = self.xpos + randomOffset[0]
            nexty = self.ypos + randomOffset[1]

        if self.world.emptyLocation(nextx, nexty):
            childThing = Bear(self.theWorld)
            self.world.addThing(childThing, nextx, nexty)
            self.breedTick = 0



    def tryToEat(self):
        adjprey = []
        for offset in self.offsetList:
            newx = self.xpos + offset[0]
            newy = self.ypos + offset[1]
            if 0 <= newx < self.world.getMaxX() and 0 <= newy < self.world.getMaxY():
                if (not self.world.emptyLocation(newx,newy)) and isinstance(self.world.lookAtLocation(newx,newy),Fish):
                    adjprey.append(self.world.lookAtLocation(newx,newy))

        if len(adjprey)>0:
            randomprey = adjprey[random.randrange(len(adjprey))]
            preyx = randomprey.getX()
            preyy = randomprey.getY()

            self.world.delThing(randomprey)
            self.move(preyx,preyy)
            self.starveTrick = 0

        else:
            self.starveTick = self.starveTick + 1

这是CLass Fish

class Fish:
    def __init__(self, theworld):
        self.turtle = turtle.Turtle()
        self.turtle.up()
        self.turtle.hideturtle()
        self.turtle.shape("E:/Python/Lib/idlelib/Fish.gif")
        self.offsetList = [(-1, 1), (0, 1), (1, 1),
                            (-1, 0)        , (1, 0),
                            (-1, -1), (0, -1), (1, -1)]
        self.theWorld = theworld
        self.overcrowd = self.theWorld.fishOvercrowdNum
        self.breed = self.theWorld.fishBreedNum

        self.xpos = 0
        self.ypos = 0
        self.world = None

        self.breedTick = 0

    def setX(self, newx):
        self.xpos  = newx

    def setY(self, newy):
        self.ypos = newy

    def getX(self):
        return self.xpos

    def getY(self):
        return self.ypos

    def setWorld(self, aworld):
        self.world = aworld

    def appear(self):
        self.turtle.goto(self.xpos, self.ypos)
        self.turtle.showturtle()

    def hide(self):
        self.turtle.hideturtle()

    def move(self, newx, newy):
        self.world.moveThing(self.xpos, self.ypos, newx, newy)
        self.xpos = newx
        self.ypos = newy
        self.turtle.goto(self.xpos, self.ypos)

    def liveALittle(self):
        adjfish = 0
        for offset in self.offsetList:
            newx = self.xpos + offset[0]
            newy = self.ypos + offset[1]
            if 0 <= newx < self.world.getMaxX() and 0 <= newy < self.world.getMaxY():
                if (not self.world.emptyLocation(newx, newy)) and isinstance(self.world.lookAtLocation(newx, newy), Fish):
                    adjfish = adjfish + 1

        if adjfish >= self.overcrowd:
            self.world.delThing(self)
        else:
            self.breedTick = self.breedTick + 1
            if self.breedTick >= self.breed:
                self.tryToBreed()

        self.tryToMove()

    def tryToBreed(self):
        offsetList = [(-1, 1), (0, 1), (1, 1),
                      (-1, 0)        , (1, 0),
                      (-1, -1), (0, -1), (1, -1)]
        randomOffsetIndex = random.randrange(len(offsetList))
        randomOffset = offsetList[randomOffsetIndex]
        nextx = self.xpos + randomOffset[0]
        nexty = self.ypos + randomOffset[1]
        while not(0 <= nextx < self.world.getMaxX() and 0 <= nexty < self.world.getMaxY()):
            randomOffsetIndex = random.randrange(len(offsetList))
            randomOffset = offsetList[randomOffsetIndex]
            nextx = self.xpos + randomOffset[0]
            nexty = self.ypos + randomOffset[1]

        if self.world.emptyLocation(nextx, nexty):
            childThing = Fish(self.theWorld)
            self.world.addThing(childThing, nextx, nexty)
            self.breedTick = 0

    def tryToMove(self):
        offsetList = [(-1, 1), (0, 1), (1, 1),
                  (-1, 0)        , (1, 0),
                  (-1, -1), (0, -1), (1, -1)]
        randomOffsetIndex = random.randrange(len(offsetList))
        randomOffset = offsetList[randomOffsetIndex]
        nextx = self.xpos + randomOffset[0]
        nexty = self.ypos + randomOffset[1]
        while not(0 <= nextx < self.world.getMaxX() and 0 <= nexty < self.world.getMaxY()):
            randomOffsetIndex = random.randrange(len(offsetList))
            randomOffset = offsetList[randomOffsetIndex]
            nextx = self.xpos + randomOffset[0]
            nexty = self.ypos + randomOffset[1]

        if self.world.emptyLocation(nextx, nexty):
            self.move(nextx, nexty)

这是班级工厂

class Plant:
    def __init__(self):
        self.turtle = turtle.Turtle()
        self.turtle.up()
        self.turtle.hideturtle()
        self.turtle.shape("E:/Python/Lib/idlelib/Plant.gif")

        self.xpos = 0
        self.ypos = 0
        self.world = None

        self.breedTick = 0

#accessor and mutators

    def setX(self, newx):
        self.xpos = newx

    def setY(self, newy):
        self.ypos = newy

    def getX(self):
        return self.xpos

    def getY(self):
        return self.ypos

    def setWorld(self, aworld):
        self.world = aworld

    def appear(self):
        self.turtle.goto(self.xpos, self.ypos)
        self.turtle.showturtle()

    def hide(self):
        self.turtle.hideturtle()

    def tryToBreed(self):
        offsetList=[(-1,1),(0,1),(1,1),
                    (-1,0)      ,(1,0),
                    (-1,-1),(0,-1),(1,-1)]
        randomOffsetIndex=random.randrange(len(offsetList))
        randomOffset=offsetList[randomOffsetIndex]
        nextx=self.xpos+randomOffset[0]
        nexty=self.ypos+randomOffset[1]
        while not(0<=nextx<self.world.getMaxX()and
                  0<=nexty<self.world.getMaxY() ):
            randomOffsetIndex=random.randrange(len(offsetList))
            randomOffset=offsetList[randomOffsetIndex]
            nextx=self.xpos+randomOffset[0]
            nexty=self.ypos+randomOffset[1]

        if self.world.emptyLocation(nextx,nexty):
            childThing=Plant()
            self.world.addThing(childThing,nextx,nexty)
            self.breedTick=0

    def liveALittle(self):
        offsetList = [(-1, 1), (0, 1), (1, 1),
                      (-1, 0)        , (1, 0),
                      (-1, -1), (0, -1), (1, -1)]
        self.breedTick = self.breedTick + 1
        if self.breedTick >= 5:
            self.tryToBreed()
        adjplant = 0
        for offset in offsetList:
            newx = self.xpos + offset[0]
            newy = self.ypos + offset[1]
            if 0 <= newx < self.world.getMaxX() and 0 <= newy < self.world.getMaxY():
               if (not self.world.emptyLocation(newx, newy)) and isinstance(self.world.lookAtLocation(newx, newy), Plant):
                       adjplant = adjplant + 1

        if adjplant >= 2:
            self.world.delThing(self)
        else:
            self.breedTick = self.breedTick + 1
            if self.breedTick >= 12:
                self.tryToBreed()


if __name__ == '__main__':
    mainSimulation()

1 个答案:

答案 0 :(得分:1)

@ Tankobot wturtle.clear()建议的问题在于它擦除了wturtle可能已经完成的所有操作。因此,您只需要一个单独的乌龟来绘制文本。如果你正在使用当前的Python 3海龟模块,那么相关的方法不是要清除,而是要去 撤消 最后一个写命令:

撤消 方法的方案是:

初始设置:

  1. 创建一个单独的乌龟,让它隐形(hideturtle)并竖起来。 (你不需要用笔来做turtle.write()

  2. 将乌龟移动到想要显示计数器的位置。

  3. 写出一组初始(零&#39; d)计数器。

  4. 运行时:

    1. 在致电turtle.write()之前,请致电turtle.undo()以删除之前的计数器。

    2. 调用turtle.write()以显示更新的计数器。如果龟位置正确用于上一次写入,则不需要先将乌龟移动到位。

    3. 我为想要了解How to output variable on turtle screen

      的海龟用户写的一个例子