使用Zelle graphics.py

时间:2018-06-24 13:49:47

标签: python-3.x graphics2d zelle-graphics

我写了一些代码来绘制任意数量的随机点,并使它们像流体一样散布一会儿。我也希望他们不要互相陷入。运行它没有问题,但是在某些情况下,完成一个点的传播会花费很长时间,因此我意识到效率不高。

我很乐意获得一些帮助,以提高效率。

This is what I meant by "like fluid"

from graphics import *
import time, random

racepoints = {} # {0:[(),()],1:[(),()]}
allpoints = []
races = {}
tx, ty = int(input("x=")), int(input("y="))

def Window():
    global win, sure, spreadSize
    win = GraphWin("Pencere", tx, ty)
    starttime = time.time()
    Start()
    spreadSize = int(input("Başlangıç boyutu?"))
    Spread(spreadSize)
    finishtime = time.time()
    sure = (finishtime - starttime)
    writeTime()
    print("Bitti! Ve {} saniye sürdü!".format(sure))
    time.sleep(5)


def writeTime():
    timefile = open("C:\\Python36\\timefile.py", "r")
    gotta_rewrite = timefile.readlines()
    timefile.close()
    timefile = open("C:\\Python36\\timefile.py", "w")
    gotta_rewrite.append("\n{} ırk, {} genişlik, {}*{} alan, {} saniye sürdü.".format(racecount, spreadSize, tx, ty, sure))
    timefile.seek(0)
    timefile.writelines(gotta_rewrite)
    timefile.close()


def Start():
    global racecount
    racecount = int(input("Kaç tane ırk olsun?"))
    for i in range(racecount):
        randomcolor = color_rgb(random.randrange(255), random.randrange(255), random.randrange(255))
        races[i] = randomcolor
        racepoints[i] = []
        nx = random.randrange(tx)
        ny = random.randrange(ty)
        randomstartpoint = Point(nx, ny)
        randomstartpoint.setFill(races[i])
        randomstartpoint.draw(win)
        allpoints.append((nx, ny))
        (racepoints[i]).append((nx, ny))


def Spread(maxsize):
    defaultsize = maxsize
    for i in range(racecount):
        maxsize = defaultsize
        while maxsize > 0:
            for point in list(racepoints[i]):
                lx, ly = point
                ax, ay = 0, 0
                while ax == 0 and ay == 0:
                    ax = random.choice([-1, 0, 1])
                    ay = random.choice([-1, 0, 1])
                if (lx + ax, ly + ay) not in allpoints:
                    lx += ax
                    ly += ay
                    newpoint = Point(lx, ly)
                    newpoint.setFill(races[i])
                    newpoint.draw(win)
                    (racepoints[i]).append((lx, ly))
                    allpoints.append((lx, ly))
                else:
                    pass
            maxsize -= 1


Window()

2 个答案:

答案 0 :(得分:1)

我稍微修改了代码,现在如果绘制的像素总数大于空白像素,它将检查空白像素上新像素的坐标。由于空白像素(准备上色的像素)越来越少,因此检查是否能够绘制新像素变得越来越容易。 200场比赛,25个散布点大小,x = 200,y = 200在更改前的512.4622814655304秒内完成,现在是384.0333812236786秒。 新版本:

from graphics import *
import time, random, io

date = "{}.{}.{}".format(time.strftime("%d"),time.strftime("%m"),time.strftime("%Y"))
racepoints = {} # {0:[(),()],1:[(),()]}
allpoints = []
space = []
races = {}
tx, ty = int(input("x=")), int(input("y="))

for i in range(tx+1):
    for a in range(ty+1):
        space.append((i, a))

def Window():
    global win, sure, spreadSize
    win = GraphWin("Pencere", tx, ty)
    Start()
    spreadSize = int(input("Başlangıç boyutu?"))
    starttime = time.time()
    Spread(spreadSize)
    finishtime = time.time()
    sure = (finishtime - starttime)
    writeTime()
    print("Bitti! Ve {} saniye sürdü!".format(sure))
    time.sleep(5)


def writeTime():
    with io.open("C:\\Python36\\timefile.py", "r", encoding="utf-8") as timefile:
        gotta_rewrite = timefile.readlines()
        timefile.close()
    gotta_rewrite.append("\n{} ırk, {} genişlik, {}*{} alan, {} saniye sürdü. {}".format(racecount, spreadSize, tx, ty, sure, date))
    with io.open("C:\\Python36\\timefile.py", "w", encoding="utf-8") as timefile:
        timefile.seek(0)
        timefile.writelines(gotta_rewrite)
        timefile.close()


def Start():
    global racecount
    racecount = int(input("Kaç tane ırk olsun?"))
    for i in range(racecount):
        randomcolor = color_rgb(random.randrange(255), random.randrange(255), random.randrange(255))
        races[i] = randomcolor
        racepoints[i] = []
        nx, ny = 0, 0
        while (nx, ny) == (0,0) or (nx,ny) in allpoints:
            nx = random.randrange(tx)
            ny = random.randrange(ty)
        randomstartpoint = Point(nx, ny)
        randomstartpoint.setFill(races[i])
        randomstartpoint.draw(win)
        allpoints.append((nx, ny))
        (racepoints[i]).append((nx, ny))
        space.remove((nx, ny))


def Spread(maxsize):
    defaultsize = maxsize
    for i in range(racecount):
        maxsize = defaultsize
        while maxsize > 0:
            for point in list(racepoints[i]):
                lx, ly = point
                ax, ay = 0, 0
                while ax == 0 and ay == 0:
                    ax = random.choice([-1, 0, 1])
                    ay = random.choice([-1, 0, 1])
                lx += ax
                ly += ay
                if len(space) > len(allpoints) and (lx, ly) not in allpoints and lx in range(tx) and ly in range(ty):
                    newpoint = Point(lx, ly)
                    newpoint.setFill(races[i])
                    newpoint.draw(win)
                    racepoints[i].append((lx, ly))
                    allpoints.append((lx, ly))
                    space.remove((lx, ly))
                elif len(allpoints) > len(space) and (lx, ly) in space and lx in range(tx) and ly in range(ty):
                    newpoint = Point(lx, ly)
                    newpoint.setFill(races[i])
                    newpoint.draw(win)
                    racepoints[i].append((lx, ly))
                    space.remove((lx, ly))
                else:
                    pass
            maxsize -= 1


Window()

答案 1 :(得分:1)

这次,与最初的尝试相比,我采用了不同的方法,因为此解决方案在很大程度上依赖于设置逻辑来维护要点。 (由于我使用的是win.plot()而不是Point.draw(),所以颜色有点柔和,但这只是次要的实现细节)

像以前一样,我将颜色用作字典键,因此我的代码可确保选择的随机颜色是唯一的。

import time
from random import randrange
from collections import defaultdict
from graphics import *

def Window():
    global tx, ty, win

    tx, ty = int(input("x = ")), int(input("y = "))
    race_count = int(input("How many races do you have? "))
    spread_size = int(input("Maximum spread? "))

    win = GraphWin("Window", tx, ty)

    start_time = time.time()

    Start(race_count)
    Spread(spread_size)

    finish_time = time.time()
    time_difference = finish_time - start_time

    print("Done! And it took {} seconds!".format(time_difference))
    writeTime(time_difference, spread_size, race_count)
    time.sleep(5)

def writeTime(sure, spread_size, race_count):
    try:
        with open("timefile.py") as time_file:
            gotta_rewrite = time_file.readlines()
    except FileNotFoundError:
        gotta_rewrite = []

    gotta_rewrite.append("\n{} race, {} width, {} * {} space, {} seconds.".format(race_count, spread_size, tx, ty, sure))

    with open("timefile.py", "w") as time_file:
        time_file.writelines(gotta_rewrite)

def Start(race_count):
    for _ in range(race_count):
        random_color = color_rgb(randrange(255), randrange(255), randrange(255))

        while random_color in races:
            random_color = color_rgb(randrange(255), randrange(255), randrange(255))

        nx, ny = randrange(tx), randrange(ty)
        win.plot(nx, ny, random_color)

        races[random_color].add((nx, ny))

def Spread(spread_size):
    for _ in range(spread_size):
        for color, points in races.items():
            for point in list(points):  # need copy of points as it'll be modified in loop

                candidates = set()

                x, y = point

                for dy in range(-1, 2):
                    for dx in range(-1, 2):
                        candidates.add((x + dx, y + dy))

                candidates = candidates.difference(*races.values())

                if candidates:
                    new_point = candidates.pop()
                    points.add(new_point)

                    nx, ny = new_point

                    if 0 < nx < tx and 0 < ny < ty:  # only draw visible points
                        win.plot(nx, ny, color)

races = defaultdict(set)

Window()

轮流处理积分,而不是完成一个积分而转到另一个积分上,这似乎更符合意图。您可以在左侧比较您的 new 解决方案,在右侧进行比较,找出他们都有50场比赛的地方:

enter image description here

在我的右边,您几乎可以算出全部50场比赛,但在您的比赛中,由于重叠而损失,您只能发现一半。