Nab
Nab

Reputation: 65

Trying to create diagonal patterns using graphics

I am trying to create a diagonal pattern using graphics, but only half of the pattern is filled. I am also trying to make it so that the same pattern fills the whole 500x500 but have no idea how. EDIT: Sorry I don't mean all of it filled, like from (0-100,500) has the line pattern and then the (100-200,500) is empty and so on.

from graphics import *

def patchwork():
    win = GraphWin('Lines test',500,500)
    for x in range(0,101,20):
        line = Line(Point(x,0), Point(100,100-x))
        line.setFill('red')
        line.draw(win)

     for x2 in range(101,0,-20):
        line2 = Line(Point(100,0+x2), Point(x2,100))
        line2.setFill('red')
        line2.draw(win)

I expected the pattern to fully fill the 100x100 with diagonal lines but only have of it is filled.

Upvotes: 0

Views: 364

Answers (1)

Savithru
Savithru

Reputation: 745

You can do it by drawing four sets of lines inside a single for loop, as shown below. The code is written in terms of the window size L, so that it can be easily changed if needed.

from graphics import *

def patchwork():
    L = 500;
    win = GraphWin('Lines test',L,L)
    for s in range(0,L+1,20):
        line1 = Line(Point(s,0), Point(L,L-s))
        line1.setFill('red')
        line1.draw(win)

        line2 = Line(Point(L,s), Point(s,L))
        line2.setFill('red')
        line2.draw(win)

        line3 = Line(Point(s,L), Point(0,L-s))
        line3.setFill('red')
        line3.draw(win)

        line4 = Line(Point(0,s), Point(s,0))
        line4.setFill('red')
        line4.draw(win)

Updated code to generate a piecewise pattern:

from graphics import *

def patchwork():
    L = 500;
    W = 100;
    f = L/W;
    win = GraphWin('Lines test',L,L)
    for xL in [0,200,400]:
      xR = xL + W;
      for s in range(0,W+1,20):
          line1 = Line(Point(xL + s,0), Point(xL,f*s))
          line1.setFill('red')
          line1.draw(win)

          line2 = Line(Point(xL + s,0), Point(xR,L - f*s))
          line2.setFill('red')
          line2.draw(win)

          line3 = Line(Point(xL + s,L), Point(xL,L - f*s))
          line3.setFill('red')
          line3.draw(win)

          line4 = Line(Point(xL + s,L), Point(xR,f*s))
          line4.setFill('red')
          line4.draw(win)

Upvotes: 1

Related Questions