使用 Zelle graphics.py 将点一一更新为 window

Updating points one by one to a window using Zelle graphics.py

我写了一些代码来随机绘制点,想画多少就画多少,然后让它们像流体一样散布一会儿。我也希望他们不要互相接触。 运行 没有问题,但在某些情况下,完成一个点的传播需要很长时间,所以我意识到这不是那么有效。

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

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

我稍微更改了代码,现在如果绘制的像素总数大于空白像素,它将检查空白像素上新像素的坐标。由于空白像素(准备着色)越来越少,因此检查是否能够绘制新像素变得更加容易和快速。 200 场比赛,25 个 spreadSize,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()

与我最初的尝试相比,这次我采取了不同的方法,因为这个解决方案在很大程度上依赖于集合逻辑来维护点。 (由于我使用 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 场比赛:

在我的右侧,您几乎可以数出所有 50 场比赛,但在您的右侧,由于重叠造成的损失,您只能看到该数字的一半。