Пример #1
2
def draw_automata(turing_machine=None):

    w = len(turing_machine.states)
    h = len(turing_machine.rules)

    root = Tk()
    frame = Frame(root, width=800, height=600)
    frame.grid(row=0, column=0)
    canvas = Canvas(frame, bg='#FFFFFF', width=800, height=600,
                    scrollregion=(0, -h * 15, w * 100, h * 15*3))
    hbar = Scrollbar(frame, orient=HORIZONTAL)
    hbar.pack(side=BOTTOM, fill=X)
    hbar.config(command=canvas.xview)
    vbar = Scrollbar(frame, orient=VERTICAL)
    vbar.pack(side=RIGHT, fill=Y)
    vbar.config(command=canvas.yview)
    canvas.config(width=800, height=600)
    canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
    canvas.pack(side=LEFT, expand=True, fill=BOTH)

    for position, state in enumerate(turing_machine.states):
        state_position[state] = position
        loop_occurrences[position] = 0
        canvas_id = canvas.create_text(10 + 80 * position, 400, anchor="nw")
        canvas.itemconfig(canvas_id, text="state-")
        canvas.insert(canvas_id, 12, "%d" % state)

    counter = 1
    for rule in turing_machine.rules:
        counter = draw_arrow(state_position[rule.current_state],
                             state_position[rule.next_state],
                             canvas, counter, rule)

    root.mainloop()
Пример #2
1
def clear_can():
    """
    캔버스를 초기화 하는 버튼명령
    """
    global can, tx_counter, count
    can.destroy()
    can = Canvas(frame_left, width=400, height=400, bg="#FFFFFF")
    tx_counter = can.create_text(20, 10, text="0")
    can.pack()
    count = 0
Пример #3
0
class ListDialog(object):
    def __init__ (self, master, items, message, accept_func):
        self.accept_func = accept_func

        self.top = Toplevel(master)
        self.top.transient(master)
        self.top.rowconfigure(0, weight=1)
        self.top.rowconfigure(1, weight=3)
        self.top.rowconfigure(2, weight=0)
        self.top.columnconfigure(0, weight=1)
        self.top.columnconfigure(1, weight=1)
        self.top.resizable(width=True, height=True)

        self.frame = Frame(self.top)
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=0)
        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=0)
        self.frame.grid(row=0, column=0, sticky=(N, S, W, E), columnspan=2)
        self.canvas = Canvas(self.frame)
        self.canvas.create_text(0, 0, text=message, anchor=NW)
        self.canvas.grid(row=0, column=0, sticky=(N, W, S, E))

        self.vscroll = Scrollbar(self.frame, command=self.canvas.yview)
        self.vscroll.grid(row=0, column=1, sticky=(N, S))
        self.canvas['yscrollcommand'] = self.vscroll.set

        self.hscroll = Scrollbar(self.frame, command=self.canvas.xview, orient=HORIZONTAL)
        self.hscroll.grid(row=1, column=0, sticky=(W, E), columnspan=2)
        self.canvas['xscrollcommand'] = self.hscroll.set

        self.canvas['scrollregion'] = self.canvas.bbox('all')
        self.canvas.bind('<Button-4>', self.scroll)
        self.canvas.bind('<Button-5>', self.scroll)
        self.canvas.bind('<MouseWheel>', self.scroll)

        self.view = NameView(self.top, sorted(items))
        self.view.widget.grid(row=1, column=0, columnspan=2, sticky=(N, W, E, S))

        self.delbutton = Button(self.top, text='Ok', command=self.accept )
        self.cancelbutton = Button(self.top, text='Cancel', command=self.cancel)
        self.delbutton.grid(row=2, column=0)
        self.cancelbutton.grid(row=2, column=1)
        self.view.widget.focus_set()

    def accept(self):
        self.accept_func(self.view.selection())
        self.top.destroy()

    def cancel(self):
        self.result = None
        self.top.destroy()

    def scroll(self, event):
        if event.num == 4 or event.delta > 0:
            self.canvas.yview(SCROLL, -1, UNITS)
        elif event.num == 5 or event.delta < 0:
            self.canvas.yview(SCROLL, 1, UNITS)
Пример #4
0
def show_mol( mol):
  try:
    from tkinter import Tk, Canvas, Frame
  except ImportError:
    from Tkinter import Tk, Canvas, Frame

  app = Tk()
  app.title( "oasa")

  mainFrame = Frame( app)
  mainFrame.pack( fill='both', expand=1)

  paper = Canvas( mainFrame, width=640, height=480, background="white", closeenough=5)
  paper.pack()

  xmin, xmax, ymin, ymax = None,None,None,None
  for a in mol.vertices:
    if xmin is None or a.x < xmin:
      xmin = a.x
    if xmax is None or a.x > xmax:
      xmax = a.x
    if ymin is None or a.y < ymin:
      ymin = a.y
    if ymax is None or a.y > ymax:
      ymax = a.y

  dx = xmax-xmin
  dy = ymax-ymin
  #print("dx", dy, ymax, ymin)
  range = min( (600.0/dx, 450.0/dy))/2
  xp = 640-range*dx
  yp = 480-range*dy
  xtrans = lambda xx: range*(xx - xmin)+xp/2
  ytrans = lambda xx: range*(xx - ymin)+yp/2

  for b in mol.edges:
    a1, a2 = b.vertices
    x1 = xtrans( a1.x)
    x2 = xtrans( a2.x)
    y1 = ytrans( a1.y)
    y2 = ytrans( a2.y)
    paper.create_line( x1, y1, x2, y2, fill='black')
    paper.create_text( (x1+x2)/2, (y1+y2)/2, text=str( b.order), fill="#F00")
  for v in mol.vertices:
    x = xtrans( v.x)
    y = ytrans( v.y)
    #paper.create_oval( x-5, y-5, x+5, y+5, fill="#0F0")
    paper.create_text( x, y, text=v.symbol, fill="#0F0")
  app.mainloop()
Пример #5
0
def demo2():
    try:
        if sys.version_info[0] == 3:
            from tkinter import Tk, Canvas
        else:
            from Tkinter import Tk, Canvas
    except ImportError:
        Tk = Canvas = None      

    if Tk: 
        from pykbool import connect
        import json, gzip
        
        with gzip.open(os.path.join('data','poly.json.gz'), 'r') as f:
            contour, holes = json.loads(f.readline().decode())
        
        try:
            connected = connect([contour]+holes)

            root1 = Tk()
            root1.title(string='not connected - contour (%d points) + holes (%d points)'%(len(contour), sum(map(len, holes))))
            canvas1 = Canvas(root1, width=810, height=510, background='white')
            canvas1.pack()
            canvas1.create_polygon(contour, outline='blue', fill='')
            for hole in holes:
                canvas1.create_polygon(hole, outline='red', fill='')

            root2 = Tk()
            root2.title(string='connected - keyhole polygon (%d points)' %(len(connected)))
            canvas2 = Canvas(root2, width=810, height=510, background='white',)
            canvas2.pack()

            canvas2.create_polygon(connected, outline='black', fill='#98BAD3', dash=(4,))

            canvas2.create_text(connected[0], text='P1', fill='red')
            canvas2.create_text(connected[int(len(connected)*0.5)], text='Pi', fill='red')
            canvas2.create_text(connected[int(len(connected)*2/3)], text='Pj', fill='red')

            root1.mainloop()
        except:
            traceback.print_exc()
Пример #6
0
def mainLoop():

    gui = Tk()


    MAX = 500

    canvas = Canvas(gui, width = MAX, height = MAX)

    o = canvas.create_line(MAX / 2, 0, MAX / 2, MAX) #Ordonnées
    a = canvas.create_line(0, MAX / 2, MAX, MAX / 2) #Abscisse
    nullP = canvas.create_text(243, 259, text = "0", fill = "red")

    canvas.pack()

    gui.mainloop()
Пример #7
0
class GameUI(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.game = Game()
        self.row, self.col = 0, 0
        self.init_UI()


    def init_UI(self):
        self.pack(fill=BOTH, expand=1)

        self.canvas = Canvas(self,
            width=WIDTH,
            height=HEIGHT,
            highlightthickness=0,
            relief='ridge',
            bg='gray10'
        )
        self.canvas.pack(fill=BOTH, side=TOP)

        Button(self,
            text='RESTART',
            height=24,
            fg='white',
            bg='gray20',
            activeforeground='white',
            activebackground='gray15',
            border=0,
            font=('Arial', 12, 'bold'),
            highlightthickness=0,
            relief='ridge',
            command=self.restart
        ).pack(fill=BOTH, side=BOTTOM)

        self.draw_grid()
        self.canvas.bind('<Button-1>', self.play)


    def restart(self):
        self.game = Game()
        self.row, self.col = 0, 0
        self.canvas.delete('all')
        self.draw_grid()


    def draw_grid(self):
        for i in range(self.game.width + 1):
            x0 = MARGIN + i * SIDE
            y0 = MARGIN
            x1 = MARGIN + i * SIDE
            y1 = HEIGHT - MARGIN
            self.canvas.create_line(x0, y0, x1, y1, fill='gray25')

            x0 = MARGIN
            y0 = MARGIN + i * SIDE
            x1 = HEIGHT - MARGIN
            y1 = MARGIN + i * SIDE
            self.canvas.create_line(x0, y0, x1, y1, fill='gray25')

        self.board = [ [ self.game.get_cell_value(x, y) for x in range(self.game.width + 1) ] for y in range(self.game.height + 1) ]
        self.load_board(self.board)


    def load_board(self, board):
        for y in range(self.game.height + 1):
            for x in range(self.game.width + 1):
                player = self.game.get_cell_value(y, x)
                if player != ' ':
                    self.row, self.col = (self.game.width - 1) - x, y
                    self.draw_player(player)


    def play(self, event):
        if self.game.get_winner():
            return

        x, y = event.x, event.y

        if MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN:
            row, col = int((y - MARGIN)  / SIDE), int((x - MARGIN) / SIDE)
            real_x, real_y = col, (self.game.width - 1) - row

            if self.game.is_cell_free(real_x, real_y):
                self.row, self.col = row, col
                player = self.game.get_next_players_turn()
                self.game.make_move(real_x, real_y, player)
                self.draw_player(player)
                winner = self.game.get_winner()
                if winner:
                    self.draw_victory(winner)


    def draw_player(self, player):
        if self.row >= 0 and self.col >=0:
            x0 = MARGIN + self.col * SIDE + 1
            y0 = MARGIN + self.row * SIDE + 1
            x1 = MARGIN + (self.col + 1) * SIDE - 1
            y1 = MARGIN + (self.row + 1) * SIDE - 1

            self.canvas.create_rectangle(
                x0, y0, x1, y1,
                fill=self.get_color(player),
                outline=''
            )

            x = x0 + SIDE / 2
            y = y0 + SIDE / 2

            self.canvas.create_text(
                x, y,
                text=player,
                fill='white',
                font=('Arial', 12)
            )


    def draw_victory(self, winner):
        x0 = y0 = MARGIN + SIDE * 2
        x1 = y1 = MARGIN + SIDE * 8
        self.canvas.create_oval(
            x0, y0, x1, y1,
            fill=self.get_color(winner),
            outline=''
        )

        x = y = MARGIN + 4 * SIDE + SIDE
        message = '{} player wins'.format(winner)
        self.canvas.create_text(
            x, y,
            text=message,
            fill='white',
            font=('Arial', 28)
        )


    def get_color(self, player):
        return 'dark slate gray' if player == 'X' else 'sea green'
Пример #8
0
        Segment(SEG_SIZE * 3, SEG_SIZE, "#009b76")
    ]
    return Snake(segments)


# Setting up window
root = Tk()
root.title("Snake_Game")
c = Canvas(root, width=WIDTH, height=HEIGHT, bg="#71bc66")
c.grid()

# catch keypressing
c.focus_set()
game_over_text = c.create_text(WIDTH / 2,
                               HEIGHT / 2 - 75,
                               text="GAME OVER!",
                               font='Arial 50',
                               fill='red',
                               state='hidden')
score_text = c.create_text(WIDTH / 2,
                           HEIGHT / 2 + 15,
                           text="Your score is: 0",
                           font='Arial 30',
                           fill='white',
                           state='hidden')
restart_text = c.create_text(WIDTH / 2,
                             HEIGHT - HEIGHT / 3,
                             font='Arial 30',
                             fill='white',
                             text="Press space to restart or escape to exit",
                             state='hidden')
win_text = c.create_text(WIDTH / 2,
Пример #9
0
    # создаем три блока змеи
    blocks = [
        Block(BLOCK_SIZE, BLOCK_SIZE),
        Block(BLOCK_SIZE * 2, BLOCK_SIZE),
        Block(BLOCK_SIZE * 3, BLOCK_SIZE)
    ]
    return Snake(blocks)


root = Tk()  # экз класса Tk, главное окно
root.title("Snake on Python")  # заголовок окна

c = Canvas(root, width=WIDTH, height=HEIGHT,
           bg="gray")  #экземляр класса canvas
c.grid()
c.focus_set()  # объект с в фокусе чтобы ловить нажатие клавиш
game_over_text = c.create_text(WIDTH / 2,
                               HEIGHT / 2,
                               text="GAME OVER!",
                               font='Arial 20',
                               fill='red',
                               state='hidden')
restart_text = c.create_text(WIDTH / 2,
                             HEIGHT - HEIGHT / 3,
                             font='Arial 30',
                             fill='white',
                             text="Начать заново",
                             state='hidden')
c.tag_bind(restart_text, "<Button-1>", clicked)
start_game()
root.mainloop()
Пример #10
0
class LpoView(Frame):
    """ This class implements a LPO widget.

    This class use a canvas to draw the Hasse diagram of a LPO.
    """

    def __init__(self, parent):
        """ This method creates a new, emtpy LpoView. """
        Frame.__init__(self, parent)
        self.__parent = parent
        self.__initUI()
        
        self.__lpo = None

    def __initUI(self):
        """ Set up user interface. """
        self.pack(fill=BOTH, expand=1)
        
        self.__canvas = Canvas(self) # canvas for LPO
        self.__canvas.pack(fill=BOTH, expand=1)
        # Scroll with mouse drag gestures
        self.__canvas.bind("<ButtonPress-1>", self.__scroll_start)
        self.__canvas.bind("<B1-Motion>", self.__scroll_move)

    def __scroll_start(self, event):
        """ Scroll LPO with mouse gestures: Start of scroll event. """
        self.__canvas.scan_mark(event.x, event.y)

    def __scroll_move(self, event):
        """ Scroll LPO with mouse gestures: Drag event. """
        self.__canvas.scan_dragto(event.x, event.y, gain=1)

        
    def showLpo(self, lpo_to_show):
        """ This method show the given LPO in this LpoView. """
        self.__lpo = lpo_to_show # set LPO reference
        self.__drawLpo() # create LPO graph

    def __drawLpo(self):
        """ This method draws the LPO. """
        # draw LPO arcs (arc layer is behind event layer)
        for arc in self.__lpo.arcs:
            # LPOs consists of all transitive arcs, the view shows only user defined arcs.
            if arc.user_drawn == True: 
                self.__drawArc(arc)

        # draw events
        for id, event in self.__lpo.events.items():
            self.__drawEvent(event)

    def __drawEvent(self, event):
        """ Draw the given event. """
        self.__canvas.create_rectangle(event.position[0] - 10, event.position[1] - 10, event.position[0] + 10, event.position[1] + 10, outline="#000", fill="#AAAAAA", width=2)
        self.__canvas.create_text(event.position[0], event.position[1] + 20, text=event.label)


    def __drawArc(self, arc):
        """ Draw the given arc. """
        start_event = self.__lpo.events[arc.source] # get start event
        end_event = self.__lpo.events[arc.target] # get end event

        intersections = self.__calculateIntersections(start_event, end_event) # calculate intersection points

        # start point of arc
        start = start_event.position[0] + intersections[0][0], start_event.position[1] + intersections[0][1]
        # end point of arc
        end = end_event.position[0] + intersections[1][0], end_event.position[1] + intersections[1][1]
        # create line with arrow head as end
        self.__canvas.create_line(start[0], start[1], end[0], end[1], arrow=LAST, arrowshape=(8.6, 10, 5), width=2)


    def __calculateIntersections(self, start, end):
        """ Calculate intersection point of start and end events with the arc.

        This method calculates two vectors which describe the intersection point of the arc from the
        given start event to the given end event.
        """

        # vector from the center of the start event to the center of the end event
        vector = float(end.position[0] - start.position[0]), float(end.position[1] - start.position[1])
        #calculate a factor to scale the x-component to 10px (half of side length)
        fact = 1
        if vector[0] != 0:
            fact = 10 / math.fabs(vector[0])
        # scale the vector
        start_vector = vector[0] * fact, vector[1] * fact

        # if y-component of vector is larger than 10px or x-component is 0, scale with y-component
        if math.fabs(start_vector[1]) > 10 or vector[0] == 0:
            fact = 10 / math.fabs(vector[1])
            start_vector = vector[0] * fact, vector[1] * fact
        #calculate intersection for arc end
        if vector[0] != 0:
            fact = 10 / math.fabs(vector[0])

        end_vector = -vector[0] * fact, -vector[1] * fact

        if math.fabs(end_vector[1]) > 10 or vector[0] == 0:
            fact = 10 / math.fabs(vector[1])
            end_vector = -vector[0] * fact, -vector[1] * fact

        return start_vector, end_vector
Пример #11
0
class prgCanvas(Frame):
    def __init__(self,window=None,height=500,width=500,bg="grey"):
        Frame.__init__(self,window,height=height,width=width,bg=bg)
        self.canvas = Canvas(self, bg=bg, height=height, width=width)
        self.flagDescription = False
        self.setdefault(mashtab=True,reper=True,normalization=True)
        self.canvas.pack(expand='y',fill="both")
        self.field = None #данные, блоки групп, графические примитивы, точки, #графические примитивы, надписи
        self.fileprogram = None #имя файла для загрузки

        self.filter = None #фильтр, по которому определяется выделенный фрагмент

    def setdefault(self,mashtab=False,reper=False,normalization=False):
        if mashtab:
            self.mashtab = 1.00 #масштаб
        if reper:
            self.reper = [10.00,10.00] #смещение
        if normalization:
            self.normalization = [0.00,0.00] #коэффициент для нормализации координат
        
    def configure(self,file=None,filter= None):
        if file!=None:
            self.fileprogram = file
        self.filter=filter

    def setMashtab(self):
        '''Эта функция устанавливает текущий масштаб, так чтобы вся плата была в зоне видимости'''
        def findcoord(field):
            mX,mY = field[0][0],field[0][1]
            # sX,sY = field[0][0],field[0][1]
            sX,sY = 0, 0
            for c in field:
                if c[0]<sX: sX = c[0]
                elif c[0]>mX: mX = c[0]
                if c[1]<sY: sY = c[1]
                elif c[1]>mY: mY = c[1]
            return [sX,sY,mX,mY]
        sX,sY,mX,mY=findcoord(self.field)
        lX = int(self.canvas["width"])
        lY = int(self.canvas["height"])
        lengthX = abs(mX-sX)
        lengthY = abs(mY-sY)
        if lengthX>0 and lengthY>0:
            cX = lX/lengthX
            cY = lY/lengthY
        else:
            cX,cY=1.0,1.0
        print("MSH",cX,cY)
        
        self.normalization = [abs(sX),abs(sY)]
        self.mashtab = int(min(cX,cY)*0.9)
    
    def transform(self,x,y,a,etalon):
        """
        точка отсчета - в центре эталона
        """
        new = list()
        for item in etalon:
            ca = cos(a)
            sa = sin(a)
            x2,y2 = item[0]-x, item[1]-y
            
            new.append([x2*ca + y2*sa+x, x2*sa - y2*ca+y])
        return new
        
    def genfield(self):
        x,y,d=0,1,2
        
        self.canvas.delete("all")

        for c in self.field:
            cx = (c[x]+self.normalization[x])*self.mashtab+self.reper[x]
            cy = (c[y]+self.normalization[y])*self.mashtab+self.reper[y]

            print("filter",self.filter)
            
            if self.flagDescription and self.filter==None:
                tag = "BLACK"
                _color1,_color2 = "black","black"
                font = "Verdana 8"
                self.canvas.create_text(cx,cy,anchor="nw",text=str(c[d][1]), fill=_color1,font=font,tag=("DESC",tag))
            elif (not self.flagDescription) and self.filter==None:
                tag = "BLACK"
                _color1,_color2 = "black","black"
            elif self.flagDescription and self.filter!=None and self.filter(c[d][2]):
                _color1,_color2 = ["red","red"]
                tag = "RED"
                font = "Verdana 10 bold"
                self.canvas.create_text(cx,cy,anchor="nw",text=str(c[d][1]), fill=_color1,font=font,tag=("DESC",tag))
            elif self.flagDescription:
                _color1,_color2 = "black","black"
                tag = "BLACK"
                # font = "Verdana 8"
                # self.canvas.create_text(cx,cy,anchor="nw",text=str(c[d][1]), fill=_color1,font=font,tag=("DESC",tag))
                pass
                
            # здесь может быть выбор фигуры
            # здесь может быть угол поворота
            print("c",c)
            if c[-2][0]=="25":
                angle = radians(c[-1])
                pattern = [[-3,-5.0],[3,-5.0],[0.0,3.0],[-3.0,-5.0]]
                et = [[cx+item[0],cy+item[1]] for item in pattern]
                new = self.transform(cx,cy,angle,et)
                self.canvas.create_polygon(new,activefill="white",fill=_color2,tag=("FIG",tag))
            else:
                self.canvas.create_rectangle(cx-1,cy-1,cx+1,cy+1,outline=_color1,fill=_color2,tag=("FIG",tag))
        self.canvas.tag_lower("RED")
        
    def move(self,x,y):
        #в группы
        self.reper[0]+=x
        self.reper[1]+=y
        self.canvas.move("FIG",x,y)
        self.canvas.move("DESC",x,y)

    def load(self):
        _p = prg(self.fileprogram)
        _p.download()
        _p.extract()
        #вариант кода для загрузки информации о установке
        self.field = [x[1:4]+[x[0]] for x in _p.progdigit if ("25" in x[3]) or ("107" in x[3])]
        print(_p.progdigit)
        #вариант кода для загрузки информации о дозировании:
        # self.field.group = [x[1:4] for x in _p.progdigit if "107" in x[3]]
        # print(self.field)

    def paint(self):
        self.load()
        try:
            self.setMashtab()
            self.genfield()
        except ZeroDivisionError:
            print("Zero division")
        except IndexError:
            print("Index error")
            #рисуем надпись
            self.canvas.delete("all")
            x,y = int(self.canvas["width"]),int(self.canvas["height"])
            self.canvas.create_text(x//2,y//2,text="FILE IS CORRUPTED", font="Verdana 12 bold",fill="red",tag="del")
Пример #12
0
class Snake:

    TITLE = 'Snake by Rim'
    BODY_W = 800
    BODY_H = 600
    BODY_BG = '#000000'
    PIX = 10
    PIX_BG = '#ffffff'
    FOOD_BG = '#889900'
    BUTTON_COLOR = '#ffffff'
    BUTTON_FONT = ('Tahoma', 24, 'bold')
    ERROR_COLOR = '#cc0000'
    ERROR_FONT = ('Tahoma', 18)
    COUNTER_COLOR = '#333333'
    COUNTER_FONT = ('Tahoma', 12)
    SPEED = 300
    SPEED_LINE = 50
    MOVES = {
        'Left': {'x': -1, 'y': 0},
        'Up': {'x': 0, 'y': -1},
        'Right': {'x': 1, 'y': 0},
        'Down': {'x': 0, 'y': 1}
    }
    MOVE = 'Right'

    def __init__(self):
        self.endgame = True
        self.timeout = self.SPEED
        self.pixels = []
        self.pixels_coords = []
        self.food = []
        self.food_coords = []
        self.score = 0
        self._createWindow()

    def _createWindow(self):
        self.root = Tk()
        self.root.title(self.TITLE)

        self.body = Canvas(self.root, width=self.BODY_W,
                           height=self.BODY_H, bg=self.BODY_BG)
        self.body.grid()
        self.body.focus_set()

    def _generatePixels(self, count):
        for i in range(count):
            pix = self._createPixel(x=(i+1) * self.PIX)
            self.pixels.append(pix)

    def _createElement(self, x, y, fill):
        return self.body.create_rectangle(x, y, x + self.PIX, y + self.PIX, fill=fill)

    def _createPixel(self, x=10, y=10):
        return self._createElement(x, y, self.PIX_BG)

    def _gameCreate(self, e):
        self.endgame = False
        self.body.itemconfig(self.text_error, state='hidden')
        self.body.itemconfig(self.text_start, state='hidden')
        self._generatePixels(3)
        self.MOVE = 'Right'

        self.body.itemconfig(self.counter, state='normal')

        self._game()

    def _game(self):
        self._move()
        if self.endgame != True:
            self.root.after(self.timeout, self._game)

    def _move(self):
        if self.endgame != True:
            self._eatFood()

            self.pixels_coords = []
            self._generateFood()
            for i in range(len(self.pixels)):
                try:
                    # Наступний елемент
                    x1, y1, x2, y2 = self.body.coords(self.pixels[i + 1])
                    self.body.coords(self.pixels[i], x1, y1, x2, y2)
                except IndexError as e:
                    # Голова
                    moves = self.MOVES[self.MOVE]
                    x1 = x1 + self.PIX * moves['x']
                    y1 = y1 + self.PIX * moves['y']
                    self.body.coords(
                        self.pixels[i], x1, y1, x1 + self.PIX, y1 + self.PIX)
                    self._endGame()

                head_coords = '{x}x{y}'.format(x=int(x1), y=int(y1))
                self.pixels_coords.append(head_coords)
                if head_coords in self.food_coords:
                    pass

    def _eatFood(self):
        if len(self.pixels_coords) > 0 and self.pixels_coords[-1] in self.food_coords:
            self._updateCounter()
            # додаємо новий піксель у змійку
            x1, y1, x2, y2 = self.body.coords(self.pixels[0])
            new_pix = self._createPixel(x1, y1)
            self.pixels.insert(0, new_pix)

            # Видаляємо їжу з екрану
            for food in self.food:
                self.body.delete(food)
            self.food = []
            self.food_coords = []

    def _moveChange(self, e):
        if e.keysym in ['Left', 'Up', 'Right', 'Down']:
            if (self.MOVE == 'Left' and e.keysym != 'Right') or \
                (self.MOVE == 'Up' and e.keysym != 'Down') or \
                (self.MOVE == 'Right' and e.keysym != 'Left') or \
                    (self.MOVE == 'Down' and e.keysym != 'Up'):
                self.MOVE = e.keysym

    def _generateFood(self):
        if len(self.food) == 0:
            rand_row = randint(1, (self.BODY_H - self.PIX) //
                               self.PIX) * self.PIX
            rand_col = randint(1, (self.BODY_W - self.PIX) //
                               self.PIX) * self.PIX
            food_coords = f'{rand_col}x{rand_row}'
            if food_coords in self.pixels_coords:
                self._generateFood()
            else:
                food = self._createElement(rand_col, rand_row, self.FOOD_BG)
                self.food_coords.append(food_coords)
                self.food.append(food)

    def _updateCounter(self, score=None):
        if score and int(score) > 0:
            self.score = score
        else:
            self.score = self.score + len(self.pixels)

        self.body.itemconfig(self.counter, text='Рахунок: %s' % self.score)
        self._changeSpeed()

    def _changeSpeed(self):
        points = self.score // self.SPEED_LINE
        self.timeout = self.SPEED - points * self.SPEED_LINE
        if self.timeout < self.SPEED_LINE:
            self.timeout = self.SPEED_LINE

    def _endGame(self):
        # Визначаємо позицію голови
        x1, y1, x2, y2 = self.body.coords(self.pixels[-1])
        head_cords = '{x}x{y}'.format(x=int(x1), y=int(y1))
        if x1 < 0 or x1 >= self.BODY_W or y1 < 0 or y1 >= self.BODY_H or head_cords in self.pixels_coords:
            for item in self.pixels + self.food:
                self.body.delete(item)
            self.pixels = []
            self.food = []
            self.endgame = True
            self._updateCounter(0)
            self.body.itemconfig(self.counter, state='hidden')
            self.body.itemconfig(self.text_error, state='normal')
            self.body.itemconfig(self.text_start, state='normal')

    def _start(self):
        self.counter = self.body.create_text(
            self.BODY_W - 60, 10, text='Рахунок: 0', fill=self.COUNTER_COLOR, font=self.COUNTER_FONT, state='hidden')
        self.text_error = self.body.create_text(
            self.BODY_W/2, self.BODY_H/2, text='Ви програли!', fill=self.ERROR_COLOR, font=self.ERROR_FONT, state='hidden')
        self.text_start = self.body.create_text(
            self.BODY_W/2, self.BODY_H/2.15, text='Почати гру', fill=self.BUTTON_COLOR, font=self.BUTTON_FONT)
        self.body.tag_bind(self.text_start, '<Button-1>', self._gameCreate)
        self.body.bind("<KeyPress>", self._moveChange)

    def run(self):
        self._start()
        self.root.mainloop()
Пример #13
0
class Gem:
	def __init__(self):
		self.frame = Tk();
		self.frame.resizable(False, False)

		self.status = 1
		self.scorePlayerA = 0
		self.scorePlayerB = 0

		self.scoreRoundA = 0
		self.scoreRoundB = 0

		self.countRound = 0
		self.quitMatch = 0
		self.isQuitRound = 0

		self.canvas_after_2 = 0
		self.canvas_after_1 = 0
		self.isPause = 0

		#register event
		self.frame.bind("<F4>", self.quitGame)
		self.frame.bind("<F5>", self.pauseGame)
		self.frame.protocol("WM_DELETE_WINDOW", self.on_closing)

		self.registerKeyboard()

	def setName(self, title):
		self.frame.title(title)

	def setBall(self, ball):
		self.ball = ball

	def setLeftBar(self, bar):
		self.leftBar = bar

	def setRightBar(self, bar):
		self.rightBar = bar

	def run(self):
		self.frame.mainloop()

	def getFrame(self):
		return self.frame;

	def getCanvas(self):
		return self.canvas

	def setSize(self, size):
		self.frame.geometry(("%dx%d")%(size[0], size[1]))
		self.frame.update()

	def getSize(self):
		return (self.frame.winfo_width(), self.frame.winfo_height())

	def setBackground(self, color):
		self.background = color

	def setPlayers(self, players):
		self.players = players

	def setScoreBoard(self):
		players = self.players
		size = self.getSize()
		mid = round(size[0]/2)
		# Board
		self.canvas.create_rectangle(mid - 100, 0, mid + 100, 35, fill="grey58", outline="white", tag="boarda")

		# Player name 1
		self.canvas.create_text(mid - 80, 15, text=players[0], fill="magenta2", tag="boardb")

		# Round score 1
		r1 = players[0]+"a"
		self.canvas.create_text(mid - 80, 28, text="0", fill="pale green", tag="scoreplayera")

		# Player name 2
		self.canvas.create_text(mid + 80, 15, text=players[1], fill="magenta2", tag="boardc")

		# Round score 2
		self.canvas.create_text(mid + 80, 28, text="0", fill="pale green", tag="scoreplayerb")

		# Box score 1
		self.canvas.create_rectangle(mid - 50, 5, mid - 10, 25, fill="thistle3", outline="white", tag="boardd")

		# Score 1
		self.canvas.create_text(mid - 30, 15, text="000", fill="cyan", tag=players[0])

		# Box score 2
		self.canvas.create_rectangle(mid + 10, 5, mid + 50, 25, fill="thistle3", outline="white", tag="boarde")

		# Score 2
		self.canvas.create_text(mid + 30, 15, text="000", fill="cyan", tag=players[1])

		self.canvas.pack()
		self.frame.update()

	def clearScoreBoard(self):
		self.canvas.delete(self.players[0])
		self.canvas.delete(self.players[1])
		self.canvas.delete("boarda")
		self.canvas.delete("boardb")
		self.canvas.delete("boardc")
		self.canvas.delete("boardd")
		self.canvas.delete("boarde")
		self.canvas.delete("scoreplayera")
		self.canvas.delete("scoreplayerb")
		self.canvas.update()

	def initCanvas(self):
		canvas_width = self.frame.winfo_width()
		canvas_height = self.frame.winfo_height()
		self.canvas = Canvas(self.frame, width=canvas_width, height=canvas_height, bg=self.background)
		self.frame.update()

	def setDashboard(self):
		size = self.getSize();
		midw = round(size[0]/2)
		midh = round(size[1]/2)
		self.canvas.create_oval(midw - 120, midh - 70, midw + 120, midh+70, fill="alice blue", outline="white", tag="dash1")
		self.canvas.create_text(midw, midh - 35, text="F1: Machine Vs Machine", fill="blue violet", tag="dash2")
		self.canvas.create_text(midw, midh - 10, text="F2: Human Vs Machine  ", fill="blue violet", tag="dash3")
		self.canvas.create_text(midw, midh + 15, text="F3: Human Vs Human     ", fill="blue violet", tag="dash4")
		self.canvas.create_text(midw, midh + 38, text="F4: Quit Game                  ", fill="blue violet", tag="dash5")
		self.canvas.pack()

	def clearDashboard(self):
		self.canvas.delete("dash1")
		self.canvas.delete("dash2")
		self.canvas.delete("dash3")
		self.canvas.delete("dash4")
		self.canvas.delete("dash5")
		self.canvas.update()

	def setWinter(self, status = -1):
		size = self.getSize();
		midw = round(size[0]/2)
		midh = round(size[1]/2)

		if status == 1:
			textstr = self.players[0] + " Win"
		elif status == 2:
			textstr = self.players[1] + " Win"
		elif self == 3 and self.scorePlayerA != self.scorePlayerB:
			if self.scoreRoundB > self.scorePlayerA:
				textstr = self.players[1] + " Win"
			else:
				textstr = self.players[0] + " Win"
		else:
			textstr = "Not Match"

		self.canvas.create_oval(midw - 50, midh - 20, midw + 50, midh+20, fill="alice blue", outline="white", tag="wintera")
		self.canvas.create_text(midw, midh, text=textstr, fill="blue violet", tag="winterb")

		self.canvas.pack()
		self.canvas.update();

	def clearWinter(self):
		self.canvas.delete("wintera")
		self.canvas.delete("winterb")
		self.canvas.update()

	def quitRound(self, status):
		if self.scorePlayerA >= self.maxRoundScore and self.scorePlayerB >= self.maxRoundScore:
			self.isQuitRound = 1
		if status == 1 or status == 2 or self.isQuitRound == 1 or self.quitMatch == 1:
			if self.isQuitRound == 0:
				self.updateScoreRound(status - 1)
			self.isQuitRound = 1
			self.ball.quit(self.canvas)
			self.leftBar.quit(self.canvas)
			self.rightBar.quit(self.canvas)
		return self.isQuitRound

	def nextRound(self, status):
		self.canvas.after_cancel(self.canvas_after_2)
		if status == 2 or status == 1:
			if self.maxRound > self.countRound:
				#self.ball.quit(self.canvas)
				#self.leftBar.quit(self.canvas)
				#self.rightBar.quit(self.canvas)
				self.resetRound()
				self.countRound += 1
				self.leftBar.reset(self.canvas)
				self.rightBar.reset(self.canvas)
				if status == 1:
					self.leftBar.transferBall(self.canvas, self.ball)
				else:
					self.leftBar.transferBall(self.canvas, self.ball)
				#print(self.canvas.find_withtag(self.ball.name))
			else:
				self.stopMatch()

	def play(self, event):
		self.clearDashboard()
		self.unRegisterKeyboard()

		if event.keycode == 112:
			self.isPause = 4
			self.startMatch()
			self.machineVSmachine()
		elif event.keycode == 113:
			self.isPause = 5
			self.leftBar.registerKeyboard(self.frame)
			self.startMatch()
			self.machineVShuman()
		elif event.keycode == 114:
			self.isPause = 6
			self.leftBar.registerKeyboard(self.frame)
			self.rightBar.registerKeyboard(self.frame)
			self.startMatch()
			self.humanVShuman()

	def machineVSmachine(self):
		try:
			if self.ball.exists == False:
				self.isQuitRound = 0
			if self.isQuitRound == 0:
				rs = self.ball.move(self.canvas)
				self.leftBar.autoMove(self.canvas)
				self.rightBar.autoMove(self.canvas)

				rs = self.update(rs)
				if rs == 1:
					return ;
			self.canvas_after_1 = self.canvas.after(10, self.machineVSmachine)
		except:
			print("I am so sorry!")
			self.stopMatch(0)

	def machineVShuman(self):
		try:
			if self.ball.exists == False:
				self.isQuitRound = 0

			if self.isQuitRound == 0:
				rs = self.ball.move(self.canvas)
				self.leftBar.move(self.canvas)
				self.rightBar.autoMove(self.canvas)

				rs = self.update(rs)
				if rs == 1:
					return ;
			self.canvas_after_1 = self.canvas.after(10, self.machineVShuman)
		except:
			print("I am so sorry!")
			self.stopMatch(0)

	def humanVShuman(self):
		try:
			if self.ball.exists == False:
				self.isQuitRound = 0
			if self.isQuitRound == 0:
				rs = self.ball.move(self.canvas)
				self.leftBar.move(self.canvas)
				self.rightBar.move(self.canvas)

				rs = self.update(rs)
				if rs == 1:
					return ;
			self.canvas_after_1 = self.canvas.after(10, self.humanVShuman)
		except:
			print("I am so sorry!")
			self.stopMatch(0)

	def startMatch(self):
		self.setScoreBoard()
		self.quitMatch = 0
		self.isQuitRound = 0
		self.countRound = 0
		self.nextRound(1)

	def resetRound(self):
		self.scorePlayerA = 0
		self.scorePlayerB = 0
		self.isQuitRound = 0
		self.updateScorePlayer()
		self.leftBar.registerKeyboard(self.frame)
		self.rightBar.registerKeyboard(self.frame)

	def update(self, status):
		self.updateScorePlayer(status-3)

		self.canvas.update()
		if self.quitRound(status) == 1 and self.quitMatch == 0:
			self.leftBar.unRegisterKeyboard(self.frame)
			self.rightBar.unRegisterKeyboard(self.frame)
			self.canvas_after_2 = self.canvas.after(800, self.nextRound, status)
		if self.quitMatch == 1:
			self.leftBar.unRegisterKeyboard(self.frame)
			self.rightBar.unRegisterKeyboard(self.frame)
			self.isQuitRound == 1
		return self.quitMatch

	def updateScoreRound(self, status):
		if self.scorePlayerB == 0 and self.scorePlayerA == 0:
			return
		if status == 0:
			self.scoreRoundA += 1
			self.canvas.itemconfig("scoreplayera", text=self.scoreRoundA)
		elif status == 1:
			self.scoreRoundB += 1
			self.canvas.itemconfig("scoreplayerb", text=self.scoreRoundB)

	def updateScorePlayer(self, status = 5):
		if status == 0:
			self.scorePlayerA += 1
			self.canvas.itemconfig(self.players[0], text=self.__countScore(self.scorePlayerA))
			if self.scorePlayerA != 0 and self.scorePlayerA % 5 == 0:
				self.ball.speed +=1
		elif status == 1:
			self.scorePlayerB += 1
			self.canvas.itemconfig(self.players[1], text=self.__countScore(self.scorePlayerB))
		elif status == 5:
			self.canvas.itemconfig(self.players[0], text=self.__countScore(self.scorePlayerA))
			self.canvas.itemconfig(self.players[1], text=self.__countScore(self.scorePlayerB))

		self.canvas.update()

	def __countScore(self, score):
		if score < 10:
			scorestr = "00" + str(score);
		elif score < 100:
			scorestr = "0" + str(score)
		else:
			scorestr = str(score)
		return scorestr

	def stopMatch(self, event = 0):
		self.isQuitRound = 1
		self.quitMatch = 1
		self.leftBar.unRegisterKeyboard(self.frame)
		self.rightBar.unRegisterKeyboard(self.frame)
		self.canvas.after_cancel(self.canvas_after_1);
		self.canvas_after_3 = self.canvas.after(500, self.returnMenu)

	def quitGame(self, event):
		self.isQuitRound = 1
		self.quitMatch = 1
		self.leftBar.unRegisterKeyboard(self.frame)
		self.rightBar.unRegisterKeyboard(self.frame)
		self.canvas.after_cancel(self.canvas_after_1);
		self.canvas_after_3 = self.canvas.after(200, self.destroy)

	def destroy(self):
		self.canvas.after_cancel(self.canvas_after_3)
		self.frame.destroy()

	def returnMenu(self):
		self.canvas.after_cancel(self.canvas_after_3)
		self.ball.quit(self.canvas)
		self.leftBar.quit(self.canvas)
		self.rightBar.quit(self.canvas)
		self.clearScoreBoard()
		self.clearWinter()
		self.setDashboard()
		self.registerKeyboard()

	def setMaxRound(self, max):
		self.maxRound = max

	def setMaxRoundScore(self, max):
		self.maxRoundScore = max

	def registerKeyboard(self):
		self.frame.bind("<F1>", self.play)
		self.frame.bind("<F2>", self.play)
		self.frame.bind("<F3>", self.play)
		self.frame.unbind("<Escape>")

	def unRegisterKeyboard(self):
		self.frame.unbind("<F1>")
		self.frame.unbind("<F2>")
		self.frame.unbind("<F3>")
		self.frame.bind("<Escape>", self.stopMatch)

	def on_closing(self):
		self.quitGame(0)
	def pauseGame(self, event):
		if self.isPause == 1:
			self.isPause += 3
			self.machineVSmachine()
		elif self.isPause == 2:
			self.isPause += 3
			self.machineVShuman()
		elif self.isPause == 3:
			self.isPause += 3
			self.humanVShuman()
		elif self.isPause > 3:
			self.canvas.after_cancel(self.canvas_after_1)
			self.isPause -= 3
##
# Create a canvas and print "It works!" on the canvas
#

from tkinter import Canvas, Tk

root = Tk()

C = Canvas(root, width=300, height=200)
C.pack()
C.create_text(140, 95, text='It works!')

root.mainloop()
Пример #15
0
class VisualGUI:
    def __init__(self,master,windowTitle,path):
        self.master = master
        self.windowTitle = windowTitle
        master.title(windowTitle)
        master.geometry("800x600")
        self.path = path

        self.canvasWidth = 800
        self.canvasHeight = 600

        self.canvas = Canvas(master, width=self.canvasWidth, height=self.canvasHeight)
        self.canvas.pack()

        self.loadData()


    def loadData(self):
        processArray = []
        frecuencyArray = []
        singleArray = []
        total = 0
        elements = 0

        scheduleFile = open("rm_report.txt","r")
        lines = scheduleFile.readlines()

        for line in lines:
            if line.rstrip("\n") not in processArray:
                singleArray.append(line.rstrip("\n"))
                elements+=1


            if not processArray:
                frecuencyArray.append(1)
                processArray.append(line.rstrip("\n"))
                total = 1

            elif (processArray[-1] != line.rstrip("\n")):
                frecuencyArray.append(1)
                processArray.append(line.rstrip("\n"))
                total += 1

            else:
                frecuencyArray[-1] += 1
                total += 1

        self.drawData(self.canvasWidth//total,self.canvasHeight//elements, processArray,frecuencyArray,total,elements,singleArray)


    def drawData(self, boxWidth, boxHeight, processArray, frecuencyArray,total,elements,singleArray):
        for i in range(total):
            for j in range(elements):
                self.canvas.create_rectangle(i*boxWidth,j*boxHeight,i*boxWidth+boxWidth,j*boxHeight+boxHeight)

        acum = 0
        for i in range(len(processArray)):
            frec = frecuencyArray[i]
            y = singleArray.index(processArray[i])
            color = self.colorPicker(y)

            for j in range(frec):
                self.canvas.create_rectangle(
                    acum*boxWidth,
                    boxHeight*y,
                    acum*boxWidth + boxWidth,
                    y*boxHeight + boxHeight, 
                    fill = color)
                acum += 1

        acum = 0
        for i in range(len(processArray)):
            frec = frecuencyArray[i]
            y = singleArray.index(processArray[i])

            x_text = ((acum*boxWidth) + ((((acum + frec) * boxWidth) - (acum*boxWidth))/2))
            y_text = ((boxHeight* y) + ((((boxHeight* y)+boxHeight) - (boxHeight* y))/2))

            self.canvas.create_text(x_text,y_text,fill="black",font="Helvetica 16", text = processArray[i])

            acum +=frec


    def colorPicker(self, number):
        if (number == 0):
            return "red"
        elif (number == 1):
            return "green"
        elif (number == 2):
            return "blue"
        elif (number == 3):
            return "yellow"
        elif (number == 4):
            return "magenta"
        elif (number == 5):
            return "cyan"
        return "black"
Пример #16
0
    else:
        c.happy_lvl -= 1
        print(c.happy_lvl)
    win.after(500, sad)


win = Tk()

c = Canvas(win, width=400, height=400)
c.configure(bg='dark blue', highlightthickness=0)

c.body_color = 'SkyBlue1'

guess = c.create_text(200,
                      370,
                      fill="black",
                      font="italic 20",
                      text="Pet me please",
                      state=HIDDEN)
guess1 = c.create_text(200,
                       390,
                       fill="black",
                       font="italic 10",
                       text="by double clicking",
                       state=HIDDEN)
thanks = c.create_text(200,
                       370,
                       fill="black",
                       font="italic 20",
                       text="Thanks sooo much :)",
                       state=HIDDEN)
Пример #17
0
class main:
    def __init__(self):
        # %%----------------------Constantes-----------------------------------------#
        self.width = 825
        self.height = 500
        self.backgroundColorGrey = '#A2A4AA'
        self.backgroundColorBlack = '#000000'
        self.foregroundColorWhite = '#FFFFFF'
        self.TaillePoliceInterface = 11
        self.TaillePoliceMessages = 20
        self.PositionTexteDebutLevelX = 320
        self.PositionTexteDebutLevelY = 300

        # %%----------------------Interface graphique---------------------------------#
        self.window = Tk()
        self.window.title('Space invaders')
        """on centre la fenêtre sur l'écran 
        on la rend non redimensionnable"""
        widthScreen = self.window.winfo_screenwidth()
        heightScreen = self.window.winfo_screenheight()
        x = (widthScreen // 2) - (self.width // 2)
        y = (heightScreen // 2) - (self.height // 2)
        self.window.geometry('{}x{}+{}+{}'.format(self.width, self.height, x,
                                                  y))
        self.window.resizable(width=False, height=False)
        """fenêtre de couleur grise"""
        self.window.config(bg=self.backgroundColorGrey)
        """Frame à gauche noir qui va contenir le Canvas et
         les deux Labels (score et vies)"""
        self.leftFrame = Frame(self.window, bg=self.backgroundColorBlack)
        self.leftFrame.grid(row=0, column=0)
        """Frame à droite grise qui va contenir les deux bouttons (quitter et rejouer) """
        self.rightFrame = Frame(self.window, bg=self.backgroundColorGrey)
        self.rightFrame.grid(row=0, column=1)
        """Label qui indique les nombre de vies restantes police blanche sur fond noir
        situé à la première ligne de la Frame de gauche"""
        self.stayLife = StringVar()
        self.stayLife.set('LIVES')
        self.lifeLabel = Label(self.leftFrame,
                               textvariable=self.stayLife,
                               bg=self.backgroundColorBlack,
                               fg=self.foregroundColorWhite,
                               font=("Terminal", self.TaillePoliceInterface))
        self.lifeLabel.grid(row=0, column=0, padx=(550, 0))
        """Label qui indique le score et le meilleur score police blanche sur fond noir
        situé à la première ligne de la Frame de gauche"""
        self.myScore = StringVar()
        self.myScore.set('SCORE')
        self.scoreLabel = Label(self.leftFrame,
                                textvariable=self.myScore,
                                bg=self.backgroundColorBlack,
                                fg=self.foregroundColorWhite,
                                font=("Terminal", self.TaillePoliceInterface))
        self.scoreLabel.grid(row=0, column=0, padx=(0, 600))
        """Canvas de couleur noir qui contient tout les éléments du jeu"""
        self.Canevas = Canvas(self.leftFrame,
                              width=650,
                              height=480,
                              bg=self.backgroundColorBlack,
                              highlightthickness=0)
        self.Canevas.grid(
            row=1,
            column=0,
        )
        """Boutons situé dans la Frame de droite l'un en dessous de l'autre
        de couleur de fond identique à window et de police noir"""
        self.replayButton = Button(self.rightFrame,
                                   text='New game',
                                   bg=self.backgroundColorGrey,
                                   fg=self.backgroundColorBlack,
                                   font=('Terminal',
                                         self.TaillePoliceInterface),
                                   command=self.restart)
        self.replayButton.grid(row=0, column=0, pady=(0, 50), padx=(20, 0))

        self.quitButton = Button(self.rightFrame,
                                 text='Quitter',
                                 bg=self.backgroundColorGrey,
                                 fg=self.backgroundColorBlack,
                                 font=('Terminal', self.TaillePoliceInterface),
                                 command=self.window.destroy)
        self.quitButton.grid(row=1, column=0, pady=(50, 0), padx=(20, 0))
        """Menu de window qui contient 3 commandes"""
        self.menuBar = Menu(self.window)
        self.menuGame = Menu(self.menuBar, tearoff=0)
        self.menuGame.add_command(label="Rejouer", command=self.restart)
        self.menuGame.add_command(label="Quitter", command=self.window.destroy)
        self.menuGame.add_command(label="A propos", command="")
        self.menuBar.add_cascade(label="Jeux", menu=self.menuGame)
        self.window.config(menu=self.menuBar)

    def reset(self):
        # %%----------------------Initialisations-------------------------------------#
        """Création de la partie"""
        self.Partie = Game(self.window, self.Canevas)

        self.frame_buffer = 0  #Permettra l'annimation des ennemis
        self.myScore.set('SCORE : {} (Record : {})'.format(
            str(self.Partie.Score),
            self.Partie.TopScore))  #Affichage du score et du Highscore
        self.start_time = time.time(
        )  #Permet d'enregistrer le temps de début de la partie
        """Affichage du texte pour le début de la partie"""
        texteLigne1 = "Niveau {} GO ! Utilisez espace pour tirer et ".format(
            self.Partie.Niveau)  #Textes pour le début du niveau
        texteLigne2 = "les fleches directionnelles pour vous deplacer"
        self.TextId1 = self.Canevas.create_text(
            self.PositionTexteDebutLevelX,
            self.PositionTexteDebutLevelY,
            font=("Terminal", self.TaillePoliceMessages),
            text=texteLigne1,
            fill=self.foregroundColorWhite)
        self.TextId2 = self.Canevas.create_text(
            self.PositionTexteDebutLevelX,
            self.PositionTexteDebutLevelY + 25,
            font=("Terminal", self.TaillePoliceMessages),
            text=texteLigne2,
            fill=self.foregroundColorWhite)
        while time.time(
        ) - self.start_time < 3:  #Permet d'afficher le texte pendant 3 secondes
            self.window.update()
        self.Canevas.delete(self.TextId1)
        self.Canevas.delete(
            self.TextId2)  #Supprime les textes à la fin des 3 secondes
        self.Partie.Pause = False  #Enlève la pause du jeu pour qu'il puisse commencer

    def start(self):
        # %%----------------------Boucle principale-----------------------------------#
        while self.Partie.Vie > 0:  #La condition d'arret du jeu est que le joueur n'ai plus de vie
            try:
                """Verification de level up"""
                if self.Partie.OnAGagneChef(
                ) == True:  #Permet de vérifier que le niveau n'est pas fini, auquel cas :
                    self.Partie.LevelUp()
                    """Texte de level up"""
                    texte = "Niveau {} GO !".format(self.Partie.Niveau)
                    self.TextId = self.Canevas.create_text(
                        self.PositionTexteDebutLevelX,
                        self.PositionTexteDebutLevelY,
                        font=("Terminal", self.TaillePoliceMessages),
                        text=texte,
                        fill=self.foregroundColorWhite)
                    self.pause_time = time.time(
                    )  #Sauvegarde du temps pour gerer l'affichage
                    while time.time(
                    ) - self.pause_time < 3:  #Permet d'afficher le texte pendant 3 secondes
                        self.window.update()
                    self.Canevas.delete(
                        self.TextId
                    )  #Supprime le texte à la fin des 3 secondes
                    self.Partie.Pause = False  #Enlève la pause pour le texte entre les niveaux
                    self.start_time = time.time(
                    )  #Enregistrement du temps du début du niveau, pour faire apparaitre l'ennemi rouge
                """Execution nomminale"""
                self.InitframeTime = time.time(
                )  #Enregistre le temps au début du l'execution de la boucle
                self.clock = self.InitframeTime - self.start_time  #Temps depuis le début du niveau (pour faire apparaitre l'ennemi rouge)
                self.window.bind(
                    "<Key>", self.Partie.ActionJoueur
                )  #Detection des touches du clavier pour exectuer le méthode ActionJoueur)
                self.frame = abs(
                    (math.floor(self.clock * (self.Partie.Niveau / 3))) % -2
                )  #Numéro de frame, pour savoir quelle image afficher pour les ennemis, dépend de self.Partie.Niveau pour rendre le jeu plus dur au fur et à mesure des niveaux
                if self.frame != self.frame_buffer:  #Lors d'un changement de frame, on change l'image des ennemis
                    self.Partie.position_ennemis_update(
                    )  #Pour déplacer et changer l'image des ennemis
                    self.Partie.fTirsEnnemi()  #Pour faire tirer les ennemis
                self.frame_buffer = self.frame  #Une fois le déplacement effectué, on enregistre quel était le numéro de frame précédent
                self.Partie.clock_update(
                    self.frame, self.clock
                )  #Update générale et afficahge de tous les éléments du jeu
                self.myScore.set('SCORE : {} (Record : {})'.format(
                    str(self.Partie.Score),
                    self.Partie.TopScore))  #Affichage du score et du Highscore
                self.stayLife.set('VIES : ' + str(self.Partie.Vie))
                """Verrou du taux de rafraichissement"""
                frameTime = time.time(
                ) - self.InitframeTime  #Enregistre le temps mis par le programme à être exécuté
                if frameTime < 0.03333:  #0.033333ms, permet de limiter le taux de rafraichissement et de mise à jour du jeu à 30 images par secondes
                    time.sleep(0.03333 - frameTime)
                """Mise à jour de l'affichage tkitner"""
                self.window.update()

            except:
                break
        """Fin de jeu"""
        if int(self.Partie.Score) > int(
                self.Partie.TopScore
        ):  #Enregistrement du HighScore s'il est battu
            open(self.Partie.texteFile, 'w').write(str(self.Partie.Score))
        self.Partie.Pause = True
        self.Canevas.delete(
            "all"
        )  #On supprime tout les elements du canvas pour afficher le game over
        """Textes de fin de jeu"""
        texte1 = "Game Over ! Vous etes mort au niveau {}. Votre score est de {}.".format(
            self.Partie.Niveau, str(self.Partie.Score))
        texte2 = "Appuyez sur New Game pour relancer"
        TextId1 = self.Canevas.create_text(320,
                                           300,
                                           font=("Terminal",
                                                 self.TaillePoliceMessages),
                                           text=texte1,
                                           fill=self.foregroundColorWhite)
        TextId2 = self.Canevas.create_text(340,
                                           330,
                                           font=("Terminal",
                                                 self.TaillePoliceMessages),
                                           text=texte2,
                                           fill=self.foregroundColorWhite)
        self.window.mainloop(
        )  #On boucle tant que le joueur ne quitte pas la fenêtre

    def restart(self):
        # %% Fonction pour rejouer
        try:

            self.Canevas.delete(
                "all")  #On réinitialise les éléments affiché sur le canvas
            self.Partie.Pause = True  #On met le jeu en pause pour bloquer les actions du joueur
            play.reset()
            play.start()
        except:
            pass
Пример #18
0
def create_snake():
    """create segments and snake"""
    segments = [
        Segment(SEG_SIZE, SEG_SIZE),
        Segment(SEG_SIZE * 2, SEG_SIZE),
        Segment(SEG_SIZE * 3, SEG_SIZE)
    ]
    return Snake(segments)


root = Tk()
root.title("Snake")
c = Canvas(root, width=WIDTH, height=HEIGHT, bg="violet")
c.grid()

c.focus_set()
game_over_text = c.create_text(WIDTH / 2,
                               HEIGHT / 2,
                               text="Game over",
                               font='Arial 30',
                               fill='black',
                               state='hidden')
restart_text = c.create_text(WIDTH / 2,
                             HEIGHT - HEIGHT / 3,
                             font='Arial 30',
                             fill='red',
                             text="Game over",
                             state='hidden')
c.tag_bind(restart_text, "<Button-1>", clicked)
start_game()
root.mainloop()
Пример #19
0
def incrementa_score():
    global pontos
    pontos += 100
    score = canvas.find_withtag('score')
    canvas.itemconfigure(score, text=f'Pontos: {pontos}', tag='score')
 

root = Tk()

cancel = None
canvas = Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack()

canvas.create_text(
    350, 50, text=f'Pontos: {pontos}', tag='score'
)

tam = 0
cobra = []
cobra.append(canvas.create_rectangle(x, y, x + 10, y + 10, fill='blue'))
tam += 1

gera_coord_comida()
comida = canvas.create_rectangle(xc, yc, xc + 10, yc + 10, fill='red')

limite_sup = canvas.create_line(10, 10, 300, 10)
limite_dir = canvas.create_line(300, 10, 300, 400)
limite_inf = canvas.create_line(10, 400, 300, 400)
limite_esq = canvas.create_line(10, 10, 10, 400)
Пример #20
0
class View():
    def __init__(self, root, controller):
        self.__controller = controller
        root.wm_title("Bomber")
        self.__windowsystem = root.call('tk', 'windowingsystem')
        self.__frame = root
        self.__canvas = Canvas(self.__frame, width=int(CANVAS_WIDTH),
                               height=int(CANVAS_HEIGHT), bg="white")
        self.__canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        self.__init_fonts()
        self.__init_arena()
        self.__init_score()
        self.__block_views = [] # type: List[BlockView]
        self.__blockfield_view = BlockfieldView()
        self.__messages = []

    def __init_fonts(self):
        self.bigfont = font.nametofont("TkDefaultFont")
        self.bigfont.configure(size=int(48))
        self.scorefont = font.nametofont("TkDefaultFont")
        self.scorefont.configure(size=int(20))


    def __init_score(self):
        self.score_text = self.__canvas.create_text(5, 5, anchor="nw")
        self.__canvas.itemconfig(self.score_text, text="Score:", font=self.scorefont)

    def __init_arena(self):
        self.__canvas.create_rectangle(LEFT_OFFSET, TOP_OFFSET,
                                       LEFT_OFFSET + MAXCOL*GRID_SIZE,
                                       TOP_OFFSET+MAXROW*GRID_SIZE, fill="black")

        nextblocktext = self.__canvas.create_text(GRID_SIZE,
                                                  TOP_OFFSET + GRID_SIZE * 4, anchor="nw")
        self.__canvas.itemconfigure(nextblocktext, text="Next:",
                                    font=self.bigfont, fill="black")

        self.__autoplay_text = self.__canvas.create_text(LEFT_OFFSET + GRID_SIZE * 5,
                                                         TOP_OFFSET - GRID_SIZE, anchor="c")
        self.__canvas.itemconfigure(self.__autoplay_text, text="Play mode",
                                    font=self.bigfont, fill="black")

    def register_block(self, block):
        block_view = BlockView(block)
        self.__block_views.append(block_view)

    def unregister_block(self, block):
        for block_view in self.__block_views:
            if block_view.block is block:
                block_view.erase(self.__canvas)
                self.__block_views.remove(block_view)

    def update_blockfield(self, blockfield):
        self.__blockfield_view.redraw(self.__canvas, blockfield)

    def display_score(self):
        self.__canvas.itemconfig(self.score_text, text="Score: " + str(self.__controller.score),
                                 font=self.scorefont)

    def show_autoplay(self, autoplay):
        if autoplay:
            self.__canvas.itemconfig(self.__autoplay_text, text="Auto-play mode",
                                     font=self.scorefont, fill="black")
        else:
            self.__canvas.itemconfig(self.__autoplay_text, text="Manual mode",
                                     font=self.scorefont, fill="black")

    def game_over(self):
        text1 = self.__canvas.create_text(LEFT_OFFSET + GRID_SIZE*MAXCOL//2,
                                          CANVAS_HEIGHT/2, anchor="c")
        text2 = self.__canvas.create_text(LEFT_OFFSET + GRID_SIZE*MAXCOL//2,
                                          CANVAS_HEIGHT/2 + 100, anchor="c")
        text1_shadow = self.__canvas.create_text(2 + LEFT_OFFSET + GRID_SIZE*MAXCOL//2,
                                                 2 + CANVAS_HEIGHT/2, anchor="c")
        text2_shadow = self.__canvas.create_text(2 + LEFT_OFFSET + GRID_SIZE*MAXCOL//2,
                                                 2 + CANVAS_HEIGHT/2 + 100, anchor="c")
        self.__messages.append(text1)
        self.__messages.append(text2)
        self.__messages.append(text1_shadow)
        self.__messages.append(text2_shadow)
        self.__canvas.itemconfig(text1, text="GAME OVER!",
                                 font=self.bigfont, fill="white")
        self.__canvas.itemconfig(text2, text="Press r to play again.",
                                 font=self.scorefont, fill="white")
        self.__canvas.itemconfig(text1_shadow, text="GAME OVER!",
                                 font=self.bigfont, fill="black")
        self.__canvas.itemconfig(text2_shadow, text="Press r to play again.",
                                 font=self.scorefont, fill="black")
        self.__canvas.tag_raise(text1)
        self.__canvas.tag_raise(text2)

    def clear_messages(self):
        for txt in self.__messages:
            self.__canvas.delete(txt)
        self.__messages.clear()

    def update(self):
        for block_view in self.__block_views:
            block_view.redraw(self.__canvas)
        self.display_score()
Пример #21
0
    )
"""
캔버스에 선 추가
"""
w.create_line(
    0, 100,
    300, 0,
    fill="#331dcc",
    width=2
    )
"""
캔버스에 텍스트 입력
"""
w.create_text(
    100, 30,  # 텍스트의 위치
    text="충북대학교 물리학과",  # 텍스트의 내용
    fill="#330033"  # 텍스트의 색상
    )
"""
캔버스에 원 그리기
"""
w.create_oval(
    50, 50,  # 원 시작시점 (사각형의 내부를 채우는 원을 그린다)
    100, 100,  # 원이 끝나는 지점
    fill="#696299",  # 원 채우기
    width=3,  # 선 두께
    outline="#f42288"  # 선 색상
    )

mainloop()
Пример #22
0
class Plateau:
    def __init__(self):

        self.fenetre = Tk()
        self.fenetre.title("Unblock Car")

        self.fenetre.state("zoomed")
        self.fenetre.attributes("-fullscreen", True)
        self.fenetre.bind(
            "<Escape>", ecran_classique
        )  #créer une fonction pour re-rentrer dans le mode plein écran

        self.f_largeur = self.fenetre.winfo_screenwidth()
        self.f_hauteur = self.fenetre.winfo_screenheight()

        self.z_dessin = Canvas(self.fenetre,
                               width=self.f_largeur,
                               height=self.f_hauteur,
                               background='white')
        self.z_dessin.pack()

        self.z_dessin.create_text(
            5,
            5,
            anchor="nw",
            text="UNBLOCK CAR",
            font="Arial 30 bold",
            fill='blue'
        )  #modifier taille font pour que s'adapte à tous les écrans ?
        self.z_dessin.create_text(
            4 * (f_largeur / 5) + 5,
            5,
            anchor="nw",
            text="Sortir du mode Plein Ecran :\npresser echap",
            font="Arial 15")  #idem

        self.p_cote = self.f_hauteur

        self.parking()

        self.z_dessin.bind("<B1-Motion>", Voiture_v4.v_deplacement)
        self.z_dessin.bind("<Button-1>", Voiture_v4.clic)

    def ecran_classique(event):
        self.fenetre.attributes("-fullscreen", False)

    def parking():

        xr0 = 4 * (self.f_largeur / 5) - self.f_hauteur
        yr0 = 0
        xr1 = 4 * (self.f_largeur / 5)
        yr1 = self.f_hauteur
        self.z_dessin.create_rectangle(xr0,
                                       yr0,
                                       xr1,
                                       yr1,
                                       fill='light grey',
                                       outline='light grey')

        for i in range(1, 6):
            #places du haut
            xl = i * (slef.p_cote / 6) + xr0
            yl0 = 0
            yl1 = self.p_cote / 3
            self.z_dessin.create_line(xl, yl0, xl, yl1, fill='white', width=2)
            #places du bas
            xl = i * (self.p_cote / 6) + xr0
            yl0 = 2 * self.p_cote / 3
            yl1 = self.p_cote
            self.z_dessin.create_line(xl, yl0, xl, yl1, fill='white', width=2)
Пример #23
0
def demo1():
    try:
        
        if sys.version_info[0] == 3:
            from tkinter import Tk, Canvas, PhotoImage, NW, SW
        else:
            from Tkinter import Tk, Canvas, PhotoImage, NW, SW
    except ImportError:
        Tk = Canvas = None      

    if Tk: 
        from pykbool import connect
        
        contour = [(491.1025968497233, 19.886736214605065), (491.1025968497233, 5.524093392945851), (455.34269902086, 5.524093392945851), (455.34269902086, 19.886736214605065), (353.68241805023416, 17.677098857426728), (353.68241805023416, 8.838549428713364), (323.20136228182207, 8.838549428713364), (323.20136228182207, 17.677098857426728), (210.81311196253725, 14.362642821659207), (210.81311196253725, 3.3144560357675132), (175.05321413367392, 3.3144560357675132), (175.05321413367392, 14.362642821659207), (73.22264793529162, 14.362642821659207), (73.22264793529162, 10.0), (34.05704555129843, 10.0), (32.18390804597701, 110.48186785891704), (10.0, 110.48186785891704), (10.0, 162.40834575260803), (48.36100468284376, 156.88425235966218), (75.09578544061303, 156.88425235966218), (128.56534695615156, 162.40834575260803), (178.62920391656024, 176.77098857426725), (226.81992337164752, 196.65772478887232), (249.9787143465304, 211.02036761053148), (291.18773946360153, 246.374565325385), (328.65048957002983, 283.9384003974168), (337.5053214133674, 298.30104321907595), (337.5053214133674, 341.3889716840536), (448.1907194550873, 350.22752111276696), (448.1907194550873, 333.6552409339294), (685.7386121753938, 350.22752111276696), (683.8654746700724, 356.856433184302), (771.3920817369094, 364.5901639344262), (774.9680715197957, 318.18777943368104), (767.816091954023, 318.18777943368104), (789.272030651341, 60.765027322404364), (796.4240102171137, 60.765027322404364), (800.0, 8.838549428713364), (757.088122605364, 8.838549428713364), (757.088122605364, 23.20119225037257), (644.6998722860792, 19.886736214605065), (644.6998722860792, 8.838549428713364), (610.8131119625373, 5.524093392945851), (608.9399744572158, 19.886736214605065)]
        holea = [(162.62239250744997, 127.0541480377546), (189.35717326521925, 135.89269746646795), (239.42103022562793, 159.09388971684052), (287.6117496807152, 187.81917536015894), (308.8974031502767, 205.49627421758566), (348.2332907620264, 246.374565325385), (366.1132396764581, 266.26130153999003), (389.272030651341, 301.6154992548435), (450.0638569604087, 307.13959264778936), (451.7667092379736, 57.45057128663686), (355.38527032779905, 55.24093392945852), (355.38527032779905, 66.28912071535022), (323.20136228182207, 66.28912071535022), (323.20136228182207, 55.24093392945852), (210.81311196253725, 55.24093392945852), (210.81311196253725, 60.765027322404364), (173.35036185610898, 60.765027322404364), (173.35036185610898, 55.24093392945852), (73.22264793529162, 51.926477893691), (71.51979565772669, 116.00596125186286), (107.27969348659005, 119.32041728763039)]
        holeb = [(749.9361430395913, 60.765027322404364), (498.254576415496, 57.45057128663686), (494.67858663260967, 294.9865871833085), (566.0280970625798, 301.6154992548435), (566.0280970625798, 292.77694982613014), (591.0600255427842, 292.77694982613014), (589.3571732652192, 303.8251366120218), (730.3533418475947, 315.9781420765027)]
          
        connected_polygon = connect([contour, holea, holeb])

        root = Tk()
        root.title(string='connect holes to contour / fill resulting polygon')
        canvas1 = Canvas(root, width=900, height=415, background='white')
        canvas1.pack()

        canvas1.create_polygon(contour, outline='blue', fill='')
        canvas1.create_text(contour[0], text='C(1)')
        canvas1.create_text(contour[20], text='C(i)')
        canvas1.create_text(contour[-1], text='C(n)')

        canvas1.create_polygon(holea, outline='red', fill='')
        canvas1.create_text(holea[0], text='H1(1)')
        canvas1.create_text(holea[9], text='H1(i)')
        canvas1.create_text(holea[-1], text='H1(n)')

        canvas1.create_polygon(holeb, outline='green', fill='')
        canvas1.create_text(holeb[0], text='H2(1)')
        canvas1.create_text(holeb[2], text='H2(i)')
        canvas1.create_text(holeb[-1], text='H2(n)')
        
        canvas1.create_text((10, 350), text='# More info in setup.py\n'
            'from pykbool import connect\n'
            'contour=[(... , ...) ... ]; hole1=[(... , ...) ... ]; hole2=...\n'
            'polygon=connect([contour, hole1, hole2, ...])', anchor=SW)
        
        canvas2 = Canvas(root, width=900, height=415, background='white')
        canvas2.pack()
        image=PhotoImage(file=os.path.join('data','demo.gif'))
        canvas2.create_image((0,0), image=image, anchor=NW)
        canvas2.image=image
        canvas2.create_polygon(connected_polygon, outline='black', fill='grey')
        canvas2.create_text(connected_polygon[0], text='P1')
        canvas2.create_text(connected_polygon[62], text='Pi')
        canvas2.create_text(connected_polygon[-1], text='Pn')

        root.mainloop()
class ShipDamagePanel(Frame):
    class TileState(Enum):
        NORMAL = 0
        HIT = 1

    FILL_COLORS = {TileState.NORMAL: "forest green", TileState.HIT: "red"}

    SQUARE_DIM = 15
    SPACING = 12
    PADDING = 10
    OUTLINE_COLOR = "black"

    def __init__(self, master):
        Frame.__init__(self, master)

        self._canvas = Canvas(self)
        self._canvas.grid(row=1)

        self._shipTiles = {}

        self._create_ship_damage_trackers()

        self._canvas.pack()

    """Repack canvas element"""

    def repack_canvas(self):
        return self._canvas.pack()

    """Update the panel based on new list of hit tiles"""

    def update_panel(self, ship, hitList=None):
        assert ship is not None
        if hitList is None:
            hitList = ship.get_hits()

        for i, hit in enumerate(hitList):
            self._canvas.itemconfig(
                self._shipTiles[ship.get_type()][i],
                fill=self.FILL_COLORS[self.TileState.HIT]
                if hit else self.FILL_COLORS[self.TileState.NORMAL])

    """Reset the panel"""

    def reset(self):
        for shipType in Ship.SHIPS:
            ship = Ship((0, 0), shipType, Ship.Orientation.VERTICAL)
            self.update_panel(ship, [0] * ship.get_size())

    """Create elements for tracking ship damage"""

    def _create_ship_damage_trackers(self):
        for i, (shipType, shipSize) in enumerate(Ship.SIZES.items()):
            y = i * (self.SPACING * 2 + self.SQUARE_DIM) + self.PADDING
            self._canvas.create_text(self.PADDING, y, text=shipType, anchor=NW)

            self._shipTiles[shipType] = [None] * shipSize

            for j in range(shipSize):
                self._shipTiles[shipType][j] = \
                    self._canvas.create_rectangle(self.PADDING + j * self.SQUARE_DIM,
                                                  self.SPACING + y,
                                                  self.PADDING + (j + 1) * self.SQUARE_DIM,
                                                  self.SPACING + self.SQUARE_DIM + y,
                                                  fill=self.FILL_COLORS[self.TileState.NORMAL],
                                                  outline=self.OUTLINE_COLOR)
Пример #25
0
class rmap():
    _var = [1]
    _nc = 0
    _nr = 0
    _r = 0
    _c = 0
    _size = 0
    _w = 0
    _d = 0
    _NoneUpdate = False
    _Nonelabel = False
    _Nonegettext = False
    _field = []
    _endPoint = (0,0)

    _robot = '' # рисунок Робота (синее кольцо)
    _park = ''

    _canvas = ''
    sleep = 0.5
    _task = ''
    _solve = ''
    _test = ''
    _res = ''
    _bum = 0

    m = []
    m.append('task1')
    m.append('task2')
    m.append('task3')
    m.append('task4')
    m.append('task5')

    m.append('task6')
    m.append('task7')
    m.append('task8')
    m.append('task9')
    m.append('task10')
    m.append('task11')
    m.append('task12')
    m.append('task13')

    class _v: # будет содержать изображение текста и квадратиков закраски и меток. Чтобы можно было "поднимать изображение"
        text = '' 
        label = '' 
        color = ''

    class _Tcell():
        color = ''
        text = ''
        label = '' # color
        wUp = False
        wLeft = False
        v = ''

    def help(self):
        """ Вывести список команд Робота
Примеры использования по команде r.help_full()
"""
        print("""
Пояснение по каждой команде: print команда.__doc__
Например:
print r.color.__doc__

---=: Команды перемещения :=---
r.rt() # Вправо
r.lt() # Влево
r.dn() # Вниз
r.up() # Вверх
r.jumpTo(r,c) # Прыжок в точку. Без особых указаний в задачах не использовать
-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=

---=: Команды изменения среды :=---
r.pt([цвет]) # Закрасить указанным цветом. По умолчанию зеленым
r.sw(направление) # Установить стену с указанной стороны
r.settext(тест) # Вписать в клетку текст
-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=

---=: Команды обратной связи :=---
r.cl() # Каким цветом закрашена клетка? r.color()
r.label() # Какого цвета метка в клетке?
r.gettext() # Какой текст в клетке?

r.getCoords() # Где Робот?
r.getCoordR() # В какой строке Робот?
r.getCoordС() # В каком столбце Робот?

r.fu() # Сверху свободно?
r.fd() # Снизу свободно?
r.fr() # Справа свободно?
r.fl() # Слева свободно?

r.wu() # Сверху стена?
r.wd() # Снизу стена?
r.wr() # Справа стена?
r.wl() # Слева стена?

r.isPark # Робот на парковке?
-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=

---=: Дополнительно :=---
r.sleep = 0.4 # Установить размер задержки после каждого хода. Меньше значение - быстрее Робот.
r._NoneUpdate = False # Отключить прорисовку поля
r._NoneUpdate = True # Включить прорисовку поля
r.demo() # Показать, что нужно сделать в текущей задаче
r.demoAll() # Показать все задачи (с решениями, по очереди)
r.randcolor() # Генерировать случайный цвет
-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=

""")

    def help_full(self):
        """ Примеры. Для получения списка команд r.help()
Примеры использования по команде r.help_full()
Больше информации по каждой команде: print команда.__doc__
Например:
print r.color.__doc__
"""
        print("""
Не реализовано в данной версии. 
Если нужно - пишите на [email protected] или на сайте progras.ru
""")

    def demo(self):
        """Показать выполнение задачи
Пример использования:
#-------------------
r.demo()
#-------------------

Для уcкорения использовать r.sleep = 0.01
В задании 10-3(4/5) можно отключить обновление экрана
#-------------------
r._NoneUpdate = True
r.demo()
r._NoneUpdate = False
#-------------------
"""
        global r
        r = self
        exec(self._solve)

    def demoAll(self):
        """Показать выполнение всех заданий в автоматическом режиме
Пример использования:

#-------------------
r.demoAll()
#-------------------

Для того, чтобы Робот двигался быстрее, используйте
#-------------------
r.sleep = 0 
r.demoAll()
#-------------------

"""
        global r
        r = self
        for x in r.m:
            r.lm(x)
            print(x)
            r.demo()
            r.pause()
          
    def __init__(self):
        self._w = 4 # толщина стен
        self._d = 4 # на столько меньше клетки закраска (с каждой стороны)
        self.sleep = 0.5 # замедление
        self._font_size = self._size // 2
        self._tk = Tk()
        self._tk.geometry('+0+0')
        x = (self._tk.winfo_screenwidth() - self._tk.winfo_reqwidth()) / 3
        y = (self._tk.winfo_screenheight() - self._tk.winfo_reqheight()) / 4
        self._tk.wm_geometry("+%d+%d" % (x, y))
        self._tk.title('Robot-hobot')
        self._canvas = Canvas(self._tk, width=(self._size*(self._nc+1)), height=(self._size*(self._nr+1)), bg="gray")

        buttons = Frame(self._tk)

        self.task = Label (self._tk, justify = 'left')
        self.res = Label (self._tk, justify = 'left')

        self._but_start = Button(buttons,text = 'start',width=10,height=1)
        self._but_start.bind('<ButtonRelease-1>',self.but1)

        self._but_demo = Button(buttons,text = 'demo',width=10,height=1)
        self._but_demo.bind('<ButtonRelease-1>',self.but_demo)

        self._but_reload = Button(buttons,text = 'reload',width=10,height=1)
        self._but_reload.bind('<ButtonRelease-1>',self.but_reload)

        self._but_load_next = Button(buttons,text = 'load next',width=10,height=1)
        self._but_load_next.bind('<ButtonRelease-1>',self.but_load_next)

        buttons.grid(row=0, column=0, sticky = "w") 
        self._canvas.grid(row=1, column=0, sticky = "e")
        self._but_start.pack(side = "left")
        self._but_demo.pack(side = "left")
        self._but_reload.pack(side = "left")
        self._but_load_next.pack(side = "left")
        self.task.grid(row=3, column=0, sticky = "w")
        self.res.grid(row=4, column=0, sticky = "w")

##        self.loadmap()
    def but_load_next(self,event):
        print ("load next")
        index = self.m.index(self._cur_map)
        if index < len(self.m)-1:
            self.lm(self.m[index+1])
        else:
            self.lm(self.m[0])

    	
    def but_demo(self,event):
        print ("demo")
        self.demo()

    def but1(self,event):
        print ('start')
        #self.lm(self._cur_map)
        self.solve_task()

    def but_reload(self,event):
        print ("reload")
        self.lm(self._cur_map)

            
    def clear (self):
        "Очистка данных (без перерисовки)"
        self._canvas.delete('all')
        self._field = []
        self._park = []
        self._Nonelabel = False
        self._NoneisPark = False
        self._Nonesettext = False
        self._test = ''
        self._res = ''
        self._bum = 0

        for r in range(1,self._nr+2):
            row = []
            for c in range(1,self._nc+2):
                row.append (self._Tcell())
            self._field.append(row)

        for r in range (1,self._nr):
            for c in range(1,self._nc):
                self._field[r][c].text = ''
                self._field[r][c].color = ''
                self._field[r][c].label = ''
                self._field[r][c].wUp = False
                self._field[r][c].wLeft = False
                self._field[r][c].v = self._v()
                
        for c in range (1,self._nc):
            self._field[1][c].wUp = True
            self._field[self._nr][c].wUp = True

        for r in range (1,self._nr):
            self._field[r][1].wLeft = True
            self._field[r][self._nc].wLeft = True

        self._solve = ''
        self._r = 1
        self._c = 1

    def _paintMap(self): 
        "Перерисовка  по имеющимся данным"
        remc = self._c
        remr = self._r
        size = self._size
        sleep = self.sleep
        self.sleep = 0

        self._bg = [self._canvas.create_rectangle(1,1,(size*(self._nc+1)), (size*(self._nr+1)), fill="gray")]
        # создать поле
        
        for r in range (1, self._nr+1):
            self._bg.append(self._canvas.create_line(size,r*size,self._nc*size,r*size))
            if r < self._nr: self._canvas.create_text(size/2,r*size+size/2,text=r)
        for c in range (1, self._nc+1):
            self._bg.append(self._canvas.create_line(c*size,size,c*size,self._nr*size))
            if c < self._nc: self._bg.append(self._canvas.create_text(c*size+size/2,size/2,text=c))
        # клетки и номера столбцов и строк

        for r in range (1,self._nr): 
            for c in range(1,self._nc):
                self._r = r
                self._c = c
                if  self._field[r][c].wUp: # стена сверху
                    self.setWall('up')
                if  self._field[r][c].wLeft: # стена слева
                    self.setWall('left')
                if  self._field[r][c].color != '' : # закраска
                    self.paint(self._field[r][c].color)
                if  self._field[r][c].label != '' : # метка0000
                    d = self._d 
                    x1 = self._size*(c)
                    x2 = self._size*(c+1)
                    y1 = self._size*(r)
                    y2 = self._size*(r+1)
                    self._canvas.delete(self._field[r][c].v.label)
                    self._field[r][c].v.label = self._canvas.create_rectangle(x1+d,y1+d,x2-d,y2-d, width = d-1, outline = self._field[r][c].label)
                    self._canvas.lift(self._robot)
                self.settext(self._field[r][c].text) # текст

        for self._c in range (1,self._nc): 
                if  self._field[self._nr][self._c].wUp: # стена сверху
                    self.setWall('down')

        for self._r in range (1,self._nr): 
                if  self._field[self._r][self._nc].wLeft: # стена слева
                    self.setWall('right')

        r = self._endPoint[0]
        c = self._endPoint[1]
        self._canvas.delete(self._park)
        if r > 0 and c > 0:
            self._park = self._canvas.create_oval (c*size+6,r*size+6, c*size+size-6,r*size+size-6, width = 3, outline = 'yellow')
        # конечная точка
        
        self.jumpTo((remr,remc))
        self._task = '\n'+self._task
        self.task.config(text = self._task)
        self.res.config()
        self._update()
        self.sleep = sleep
        #self.pause()

        
    def _update(self):
        "Обновить canvas"
        if not self._NoneUpdate:
            self._canvas.update()
            time.sleep(self.sleep)
        

    def start(self,fun):
        self.solve_task = fun
        self._tk.mainloop()


##Робот    

    def pause(self,t=1):
        """Приостановка выполнения программы. Пауза в секундах. 
#-------------------
r.pause() # пауза в одну секунду
#-------------------
r.pause(2) # пауза две секунды
#-------------------
"""
        time.sleep(t)
		
    def left(self, a = 1):
        """Шаг влево
#-------------------
r.left()
#-------------------
r.lt()
#-------------------
r.lt(3) 
#-------------------
"""
        if a == 1:
            if self.freeLeft():
                self._c -= 1
                self._canvas.move(self._robot,-self._size*a,0)
                self._update()
            else:
                self._stop()
        else :
            for z in range(0,a):
                self.left()

    def right(self, a = 1):
        """ Шаг вправо        
#-------------------
r.right()
#-------------------
r.rt()
#-------------------
r.rt(5)
#-------------------
"""        
        if a == 1:
            if self.freeRight():
                self._c += 1
                self._canvas.move(self._robot,self._size*a,0)
                self._update()
            else:
                self._stop()
                
        else :
            for z in range(0,a):
                self.right()
        
    def up(self, a = 1):
        """Шаг вверх
#-------------------
r.up()
#-------------------
r.up(3)
#-------------------
"""
        if a == 1:
            if self.freeUp():
                self._r -= 1
                self._canvas.move(self._robot,0,-self._size*a)
                self._update()
            else:
                self._stop()
        else :
            for z in range(0,a):
                self.up()
        
    def down(self, a = 1):
        """ Шаг вниз
#-------------------
r.down()
#-------------------
r.dn()
#-------------------
r.dn(4)
#-------------------
"""
        if a == 1:
            if self.freeDown():
                self._r += 1
                self._canvas.move(self._robot,0,self._size*a)
                self._update()
            else:
                self._stop()
        else :
            for z in range(0,a):
                self.down()
                
    def jumpTo(self,coord=(1,1)):
        """Прыжок в клетку с указанными координами. Через стены.
#-------------------
r.jumpTo((2,3)) # Робот окажется в третьем столбце второй строки
#-------------------
"""

        r = coord[0]
        c = coord[1]
        if ( 0 < r < self._nc) and (0 < c < self._nc):
            self._r = r
            self._c = c
            size = self._size
            self._canvas.coords(self._robot, c*size+4,r*size+4, c*size+size-4,r*size+size-4)
            self._canvas.lift(self._robot)
            self._update()
        else:
            print("Попытка переместиться за пределы поля. Отказано.")

    def paint (self, color = 'green'):
        """ Закрасить текущую клетку выбранным цветом. Если цвет не указан, то зеленым
#-------------------
r.paint() # Закрасит текущую клетку зеленым цветом
#-------------------
r.pt() # Закрасит текущую клетку зеленым цветом
#-------------------
r.pt('red') # Закрасит текущую клетку красным цветом
#-------------------
r.pt(r.randcolor()) # Закрасит текущую клетку случайным цветом
#-------------------
r.pt(r.label()) # Закрасит текущую клетку цветом метки в этой клетке
#-------------------
"""
        d = self._d+1
        self._field[self._r][self._c].color = color

        x1 = self._size*(self._c)
        x2 = self._size*(self._c+1)
        y1 = self._size*(self._r)
        y2 = self._size*(self._r+1)
        self._canvas.delete(self._field[self._r][self._c].v.color)
        self._field[self._r][self._c].v.color = self._canvas.create_rectangle(x1+d,y1+d,x2-d,y2-d, width = 0, fill = color)
        self._canvas.lift(self._field[self._r][self._c].v.text)
        self._canvas.lift(self._robot)
        self._canvas.lift(self._park)
        self._update()

    def setWall (self, target):
        """ Установить стену с указанной стороны
#-------------------
r.sw('up') # Установить стену сверху
#-------------------
r.sw('left') # Установить стену слева 
#-------------------
r.sw('down') # Установить стену снизу
#-------------------
r.sw('right') # Установить стену справа
#-------------------
"""
        size = self._size
        w = self._w
        if target == 'up':
            r = self._r
            c = self._c
            x1 = size*(c)-1
            x2 = size*(c+1)+1
            y1 = size*(r)
            y2 = size*(r+1)
            self._field[r][c].wUp = True
            self._canvas.create_line(x1,y1,x2,y1, width = w)
        elif target == 'left':
            r = self._r
            c = self._c
            x1 = size*(c)
            x2 = size*(c+1)
            y1 = size*(r)-1
            y2 = size*(r+1)+1
            self._field[r][c].wLeft = True
            self._canvas.create_line(x1,y1,x1,y2, width = w)
        elif target == 'down':
            r = self._r+1
            c = self._c
            x1 = size*(c)-1
            x2 = size*(c+1)+1
            y1 = size*(r)
            y2 = size*(r+1)
            self._field[r][c].wDown = True
            self._canvas.create_line(x1,y1,x2,y1, width = w)
        elif target == 'right':
            r = self._r
            c = self._c+1
            x1 = size*(c)
            x2 = size*(c+1)
            y1 = size*(r)-1
            y2 = size*(r+1)+1
            self._field[r][c].wRight = True
            self._canvas.create_line(x1,y1,x1,y2, width = 4)
        self._update()

    def wallUp (self):
        """ Возвращает истину, если сверху есть стена
#-------------------
if r.wallUp(): r.pt() # Закрасить, если сверху стена
#-------------------
if r.wu(): r.pt() # Закрасить, если сверху стена
#-------------------
if r.wu(): 
    r.pt() # Закрасить, если сверху стена
    r.rt() # Перейти вправо
#-------------------
while r.wu(): # Идти вправо, пока сверху есть стена
    r.rt()
"""
        return self._field[self._r][self._c].wUp 

    def wallDown (self):
        """ Возвращает истину, если снизу есть стена
#-------------------
if r.wallDown(): r.pt() # Закрасить, если снизу стена
#-------------------
if r.wd(): r.pt() # Закрасить, если снизу стена
#-------------------
if r.wd(): 
    r.pt() # Закрасить, если снизу стена
    r.rt() # Перейти вправо
#-------------------
while r.wd(): # Идти вправо, пока снизу есть стена
    r.rt()
"""
        return self._field[self._r+1][self._c].wUp 

    def wallLeft (self):
        """ Возвращает истину, если слева есть стена
#-------------------
if r.wallLeft(): r.pt() # Закрасить, если слева стена
#-------------------
if r.wl(): r.pt() # Закрасить, если слева стена
#-------------------
if r.wl(): 
    r.pt() # Закрасить, если слева стена
    r.dn() # Перейти вниз
#-------------------
while r.wl(): # Идти вниз, пока слева есть стена
    r.dn()
"""
        return self._field[self._r][self._c].wLeft

    def wallRight (self):
        """ Возвращает истину, если справа есть стена
#-------------------
if r.wallRight(): r.pt() # Закрасить, если справа стена
#-------------------
if r.wr(): r.pt() # Закрасить, если справа стена
#-------------------
if r.wr(): 
    r.pt() # Закрасить, если справа стена
    r.dn() # Перейти вниз
#-------------------
while r.wr(): # Идти вниз, пока справа есть стена
    r.dn()
"""
        return self._field[self._r][self._c+1].wLeft

    def freeUp (self):
        """ Возвращает истину, если сверху свободно (нет стены)
#-------------------
if r.freeUp(): r.pt() # Закрасить, если сверху свободно
#-------------------
if r.fu(): r.up() # Шагнуть вверх, если сверху свободно
#-------------------
if r.fu(): 
    r.up() # Шагнуть вверх
    r.pt() # Закрасить
    r.dn() # Перейти вниз
#-------------------
while r.fu(): # Идти вверх, пока сверху свободно
    r.up()
"""
        return not self._field[self._r][self._c].wUp 

    def freeDown (self):
        """ Возвращает истину, если снизу свободно (нет стены)
#-------------------
if r.freeDown(): r.pt() # Закрасить, если снизу свободно
#-------------------
if r.fd(): r.dn() # Шагнуть вверх, если снизу свободно
#-------------------
if r.fd(): 
    r.dn() # Шагнуть снизу
    r.pt() # Закрасить
    r.up() # Перейти вверх
#-------------------
while r.fd(): # Идти вниз, пока снизу свободно
    r.dn()
"""
        return not self._field[self._r+1][self._c].wUp 

    def freeLeft (self):
        """ Возвращает истину, если слева свободно (нет стены)
#-------------------
if r.freeLeft(): r.pt() # Закрасить, если слева свободно
#-------------------
if r.fl(): r.lt() # Шагнуть влево, если слева свободно
#-------------------
if r.fl(): 
    r.lt() # Шагнуть влево
    r.pt() # Закрасить
    r.rt() # Перейти вправо
#-------------------
while r.fl(): # Идти влево, пока слева свободно
    r.lt()
"""
        return not self._field[self._r][self._c].wLeft

    def freeRight (self):
        """ Возвращает истину, если снизу свободно (нет стены)
#-------------------
if r.freeDown(): r.pt() # Закрасить, если снизу свободно
#-------------------
if r.fd(): r.dn() # Шагнуть вверх, если снизу свободно
#-------------------
if r.fd(): 
    r.dn() # Шагнуть снизу
    r.pt() # Закрасить
    r.up() # Перейти вверх
#-------------------
while r.fd(): # Идти вниз, пока снизу свободно
    r.dn()
"""
        return not self._field[self._r][self._c+1].wLeft

    def getCoords(self):
        " Возвращает координаты в виде (row,column)"
        return (self._r,self._c)

    def getCoordR(self):
        " Возвращает номер строки, в которой находиться Робот"
        return self._r

    def getCoordC(self):
        " Возвращает номер столбца, в которой находиться Робот"
        return self._c

    def isPark (self):
        " Возвращает истину, если Робот находиться на парковке"
        if self._NoneisPark: self.null()
        else: return self._endPoint == self.getCoords()

    def color (self):
        """ Возвращает цвет, которым закрашена клетка
Можно использовать для проверки, закрашена ли клетка:
#-------------------
# Закрасить, если сверху закрашено
r.up()
if r.color():
    r.dn()
    r.pt()
else:
    r.dn()
#-------------------
if r.color() == 'red': r.rt() # Вправо, если закрашено красным
#-------------------
"""
        return self._field[self._r][self._c].color
    
    def randcolor (self):
        """ Возвращает случайный цвет
#-------------------
r.pt(r.randcolor()) # Закрасить случайным цветом
#-------------------
# Закрасить соседнюю клетку тем же цветом, что и текущая
x = r.color()
r.rt()
r.pt(x)
#-------------------
"""
        cr = rnd(1,255,10)
        cg = rnd(1,255,10)
        cb = rnd(1,255,10)
        color =  "#%02X%02X%02X" %(cr,cg,cb)
        return str(color)


    def label (self):
        """ Возвращает цвет метки текущей клетки
#-------------------
if r.label() == 'red': r.pt('red') # Закрасить клетку красным, если метка красная
#-------------------
"""
        if self._Nonelabel: self.null()
        else: return self._field[self._r][self._c].label
    
    def gettext(self):
        """ Возвращает текст, записанный в ячейке. 
#-------------------
if r.gettext() != '': r.rt() # Перейти вправо, если в ячейке есть какой-нибудь текст
#-------------------
if r.gettext() == '3': r.rt() # Перейти вправо, если в ячейке записано 3
#-------------------
n = r.gettext()
if n: r.rt(n) # Перейти вправо на количество шагов, указанное в клетке
#-------------------
"""
        if self._Nonegettext: self.null()
        else: return self._field[self._r][self._c].text
    
    def settext(self,text):
        """ Записать текст в клетку
#-------------------
r.settext(3)
#-------------------
"""
        self._field[self._r][self._c].text = text
        d = 1
        x1 = self._size*(self._c)
        x2 = self._size*(self._c+1)
        y1 = self._size*(self._r)
        y2 = self._size*(self._r+1)
        self._canvas.delete(self._field[self._r][self._c].v.text)
        self._field[self._r][self._c].v.text =  self._canvas.create_text(self._c*self._size+self._size/2,self._r*self._size+self._size/2,text =
                                 self._field[self._r][self._c].text, font = ('Helvetica', self._font_size,'bold'))
        self._update()

    def _stop (self):
        print ("Bum!")
        self._bum = 1
        self._canvas.delete(self._robot)
        x = self._c
        y = self._r
        
        self._robot = self._canvas.create_oval(
            x*self._size+2*self._d,y*self._size+2*self._d,
            x*self._size+self._size-2*self._d,y*self._size+self._size-2*self._d,
            fill = '#FF0000')

    def null (self, *args):
        print('Эта команда запрещена к использованию в данной задаче. Ищите другой способ')
        return ''


    def loadmap(self,mn=m[0],variant=0):
        """ Загрузить карту (задачу)
#-------------------
r.loadmap('task10-5')
#-------------------
r.lm('task10-5') # Загрузить задачу по названию
#-------------------
r.lm(r.m[5]) # Загрузить задачу по номеру
#-------------------
# Вывести полный список названий и номеров заданий
for x in r.m:
    print r.m.index(x),x
#-------------------
"""
        self._tk.title(mn)
        self._cur_map = mn
        self._NoneUpdate = False
        self._endPoint = (0, 0)
#        self._NoneUpdate = True

        if mn == 'task1':
            self._nc = 7
            self._nr = 5
            self._size = 30

            self.clear()
            self._r = 3
            self._c = 2

            self._solve = ''
            self._endPoint = (3,5)
            self._task = 'Необходимо перевести Робота по лабиринту\n' \
                         ' из начального положения в конечное.\n'

            self._field[2][2].wUp = True
            self._field[2][3].wUp = True
            self._field[2][4].wUp = True
            self._field[2][5].wUp = True

            self._field[4][2].wUp = True
            self._field[4][3].wUp = True
            self._field[4][4].wUp = True
            self._field[4][5].wUp = True

            self._field[2][4].wLeft = True
            self._field[3][3].wLeft = True
            self._field[3][5].wLeft = True

        ##--------------------------------------------------------------------------------------------
        elif mn == 'task2':
            self._nc = 16
            self._nr = 4
            self._size = 30

            self.clear()
            self._r = 3
            self._c = 1

            self._solve = ''
            
            self._task = 'Составьте программу рисования узора.\n'

        ##--------------------------------------------------------------------------------------------
        elif mn == 'task3':
            self._nc = 10
            self._nr = 5
            self._size = 30
            self.clear()
            self._r = 2
            self._c = 1

            self._endPoint = (2,9)
            self._solve = ''
            self._task = 'Необходимо провести Робота вдоль коридора\n' \
                         ' из начального положения в конечное,\n' \
                         ' заглядывая в каждый боковой коридор.'

            for i in range(2, 9):
                self._field[2][i].wUp = True
                if i%2 == 0:
                    self._field[3][i].wUp = True
                else:
                    self._field[4][i].wUp = True

                if i < 8:
                    self._field[3][i+1].wLeft = True

        ##--------------------------------------------------------------------------------------------
        elif mn == 'task4':
            self._nc = 8
            self._nr = 12
            self._size = 30
            self.clear()
            self._r = rnd(1, self._nr)
            self._c = rnd(1, self._nc)

            for i in range(0, 5):
                for j in range(0, 3):
                    self._field[6+2*j-i][2+i].label = 'red'

            self._solve = ''
            self._task = 'Составьте программу закрашивания\n' \
                         ' клеток поля, отмеченных звездочкой.\n'

        ##--------------------------------------------------------------------------------------------
        elif mn == 'task5':
            self._nc = 11
            self._nr = 10
            self._r = 1
            self._c = 1
            self._size = 30

            self.clear()
            self._solve = ''
            self._task = 'Составьте программу рисования узора.'

        ##--------------------------------------------------------------------------------------------
        ##--------------------------------------------------------------------------------------------
        elif mn == 'task6':
            self._nc = 25
            self._nr = 25
            self._r = 1
            self._c = 1
            self._size = 20
            self.clear()
            self._solve = ''
            self._task = 'Составьте программу рисования фигуры в виде буквы "Т".\n' \
                         ' Вертикальные и горизонтальные размеры пользователь вводит\n' \
                         ' с клавиатуры. Ввод данных можно осуществлять любым способом.\n'

        ##-------------------------------------------------------------------------------------------------------
        elif mn == 'task7':
            self._nc = 16
            self._nr = 11
            self._size = 25
                
            self.clear()

            self._r = rnd(1, self._nr)
            self._c = rnd(1, self._nc)

            self._field[3][2].wUp = True
            self._field[2][9].wUp = True
            self._field[3][12].wUp = True
            self._field[6][12].wUp = True
            self._field[7][3].wUp = True
            self._field[7][9].wUp = True
            self._field[8][6].wUp = True
            self._field[9][2].wUp = True
            self._field[9][11].wUp = True

            for i in range(0, 4):
                self._field[4][5+i].wUp = True
                self._field[5][5+i].wUp = True


            self._solve = ''
        
            self._task = 'Где-то в поле Робота находится горизонтальный коридор шириной в одну клетку\n' \
                         ' неизвестной длины. Робот из верхнего левого угла поля должен дойти до\n' \
                         ' коридора и закрасить клетки внутри него, как указано в задании. По полю\n' \
                         ' Робота в произвольном порядке располагаются стены, но расстояние \n' \
                         'между ними больше одной клетки.\n'
        ##--------------------------------------------------------------------------------------------
        elif mn == 'task8':
            self._nc = 16
            self._nr = 11
            self._size = 25

            self.clear()

            self._r = rnd(1, self._nr)
            self._c = rnd(1, self._nc)

            self._field[2][6].wLeft = True
            self._field[3][6].wLeft = True
            self._field[5][6].wLeft = True
            self._field[6][6].wLeft = True
            self._field[7][6].wLeft = True
            self._field[8][6].wLeft = True

            self._solve = ''
            self._task = 'Где-то в поле Робота находится вертикальная стена с отверстием в одну клетку,\n' \
                         ' размеры которой неизвестны. Робот из произвольной клетки должен дойти до\n' \
                         ' стены и закрасить клетки как показано в задании.\n'

        ##--------------------------------------------------------------------------------------------
        elif mn == 'task9':
            self._nc = 20
            self._nr = 20
            self._size = 25

            self.clear()

            self._r = rnd(1, self._nr)
            self._c = rnd(1, self._nc)

            c = rnd(2,16)
            r = rnd(2,16)
            w = rnd(3,8)
            h = rnd(3,8)
            if c + w >= self._nc: w = self._nc-c
            if r + h >= self._nc: h = self._nr-r

            for rcount in range(0,h):
                for ccount in range(0,w):
                    self._field[r + rcount][c+ccount].label = 'green'

            self._solve = ''

            self._task = 'На поле находится квадрат из закрашенных клеток. Вычислить и вывести на экран площадь квадрата.\n'

        ##--------------------------------------------------------------------------------------------
        elif mn == 'task10':
            self._nc = 15
            self._nr = 11
            self._size = 30
            self.clear()
            self._r = 2
            self._c = 1

            self._field[2][1].wUp = True
            self._field[2][2].wUp = True
            self._field[2][4].wUp = True
            self._field[2][5].wUp = True
            self._field[2][6].wUp = True
            self._field[2][8].wUp = True
            self._field[2][9].wUp = True
            self._field[2][11].wUp = True
            self._field[2][12].wUp = True
            self._field[2][13].wLeft = True

            self._field[3][1].wUp = True
            self._field[3][2].wUp = True
            self._field[3][3].wUp = True
            self._field[3][4].wUp = True
            self._field[3][6].wUp = True
            self._field[3][7].wUp = True
            self._field[3][8].wUp = True
            self._field[3][10].wUp = True
            self._field[3][11].wUp = True
            self._field[3][12].wLeft = True

            self._field[4][3].wLeft = True
            self._field[4][3].wUp = True
            self._field[4][4].wUp = True
            self._field[4][5].wUp = True
            self._field[4][6].wUp = True
            self._field[4][8].wUp = True
            self._field[4][9].wUp = True
            self._field[4][10].wUp = True
            self._field[4][11].wUp = True
            self._field[4][13].wLeft = True

            self._field[5][3].wLeft = True
            self._field[5][4].wLeft = True
            self._field[5][4].wUp = True
            self._field[5][6].wUp = True
            self._field[5][7].wUp = True
            self._field[5][8].wUp = True
            self._field[5][10].wUp = True
            self._field[5][11].wUp = True
            self._field[5][12].wUp = True

            self._field[6][3].wLeft = True
            self._field[6][4].wUp = True
            self._field[6][5].wLeft = True

            self._field[7][3].wUp = True
            self._field[7][4].wLeft = True
            self._field[7][6].wUp = True
            self._field[7][7].wLeft = True

            self._field[8][4].wUp = True
            self._field[8][5].wUp = True
            self._field[8][6].wLeft = True
            self._field[8][7].wUp = True
            self._field[8][8].wLeft = True

            self._field[9][6].wUp = True
            self._field[9][7].wLeft = True
            self._field[9][8].wUp = True
            self._field[9][9].wUp = True
            self._field[9][10].wLeft = True

            self._field[10][7].wUp = True
            self._field[10][9].wLeft = True
            self._field[10][10].wLeft = True

            self._endPoint = (10,1)
            self._solve = """
"""

            self._task = 'Необходимо провести Робота по коридору шириной в одну клетку из начального положения до конца коридора, \n' \
                         'закрашивая при этом все клетки коридора, которые имеют выход. Выходы размером в одну клетку располагаются \n' \
                         'произвольно по всей длине коридора. Коридор заканчивается тупиком. Коридор имеет два горизонтальных и \n' \
                         'диагональный участки. Пример коридора показан на рисунке.\n'

        elif mn == 'task11':
            self._nc = 15
            self._nr = 11
            self._size = 30
            self.clear()

            self._r = rnd(1, self._nr)
            self._c = rnd(1, self._nc)

            for i in range(1,self._nr):
                for j in range(1,self._nc):
                    self._field[i][j].text = str(rnd(0, 10))

            self._task = 'На поле 10х15 каждой в каждой клетке записана цифра (от 0 до 9).\n Закрасить квадрат 2х2 с наименьшей суммой значений клеток.'

        elif mn == 'task12':
            self._nc = 15
            self._nr = 6
            self._size = 30
            self.clear()

            self._r = 2
            self._c = 13

            self._field[2][2].wUp = True
            self._field[2][3].wLeft = True
            self._field[3][3].wLeft = True
            self._field[4][3].wLeft = True
            self._field[5][3].wUp = True
            self._field[5][4].wUp = True
            self._field[4][5].wLeft = True
            self._field[3][5].wLeft = True
            self._field[2][5].wLeft = True
            self._field[2][5].wUp = True
            self._field[2][6].wLeft = True
            self._field[3][6].wLeft = True
            self._field[4][6].wLeft = True
            self._field[5][6].wUp = True
            self._field[5][7].wUp = True
            self._field[5][8].wUp = True
            self._field[4][9].wLeft = True
            self._field[3][9].wLeft = True
            self._field[2][9].wLeft = True
            self._field[2][9].wUp = True
            self._field[2][10].wUp = True
            self._field[2][11].wLeft = True
            self._field[3][11].wLeft = True
            self._field[4][11].wLeft = True
            self._field[5][11].wUp = True
            self._field[4][12].wLeft = True
            self._field[3][12].wLeft = True
            self._field[2][12].wLeft = True
            self._field[2][12].wUp = True
            self._field[2][13].wUp = True


            self._task = 'Робот движется вдоль стены, профиль которой показан на рисунке,\n' \
                         ' от начального положения до конца стены. Необходимо закрасить\n' \
                         ' все внутренние углы стены, как показано на примере. Размеры стены\n могут быть произвольны.'

        elif mn == 'task13':
            self._nc = 20
            self._nr = 20
            self._size = 25

            self.clear()

            self._r = rnd(self._nr/2, self._nr)
            self._c = rnd(self._nc/2, self._nc)

            col = rnd(2, self._nc/2)
            row = rnd(4, self._nr/2)
            height = rnd(4, self._nr-4)

            if row + height >= self._nr:
                height = self._nr - row-1

            for i in range(row, row+height):
                self._field[i][col].wLeft = True

        ##--------------------------------------------------------------------------------------------

        ##--------------------------------------------------------------------------------------------
# сделать прямое управление с демонстрацией датчиков и возможностей
# при запуске робота создавать task.py и справочник :)
# сделать робота без клеток !!!
        ##--------------------------------------------------------------------------------------------
        ##--------------------------------------------------------------------------------------------
        else:
            print(mn)
            self._task = "Нет задачи с таким номером"
            self._test = '-'

        self._canvas.config(
            width=(self._size*(self._nc+1)),
            height=(self._size*(self._nr+1)))
        x = y = 1
        d = self._d
        d = 6
        self._robot = self._canvas.create_oval(
            x*self._size+d,y*self._size+d,
            x*self._size+self._size-d,y*self._size+self._size-d,
            outline = '#4400FF', width = 3)

        self._paintMap()

    lm = loadmap
    lt = left
    rt = right
    dn = down
    pt = paint
    sw = setWall
    wu = wallUp
    wd = wallDown
    wl = wallLeft
    wr = wallRight
    fu = freeUp
    fd = freeDown
    fl = freeLeft
    fr = freeRight
    cl = color
Пример #26
0
FONTSIZE1 = "Arial 15"
FONTSIZE2 = "Arial 20"


def clicked(event):
    print("click")
    c.itemconfigure(restart_text, state='hidden')
    c.itemconfigure(game_over_text, state='hidden')

root = Tk()
root.title("My Game")



c = Canvas(root, width=WIDTH, height=HEIGHT, bg=BACKCOLOR)
c.grid()

c.focus_set()


game_over_text = c.create_text(WIDTH/2, HEIGHT/2, text="GAME OVER!",
                               font=FONTSIZE1, fill='red',
                               state='normal')
restart_text = c.create_text(WIDTH/2, HEIGHT-HEIGHT/3,
                             font=FONTSIZE2,
                             fill='white',
                             text="Click here to restart",
                             state='normal')

c.tag_bind(restart_text, "<Button-1>", clicked)
root.mainloop()
Пример #27
0
def Schedules(profBook, profBook0):

	from tkinter import Tk
	from tkinter import Canvas
	import os

	mod = 1
	try: profBook[-1]
	except: mod = 0
	for professor in (range(len(profBook)-mod)):
		master = Tk()

		w=1240
		h=1754
		x=86
		y=86

		c = Canvas(master, width=1240, height=1754)
		c.pack()
	
		# Initial solution
	
		c.create_text(w/2, y, font=("Ubuntu","16", "bold"), text="Professor "+str(professor)+" schedule in initial solution")

		c.create_rectangle(x, y+30, x+124, y+48, fill="#fff", tags=("00n","init")) # Blank rectangle

		c.create_rectangle(x, y+48, x+124, y+120, fill="#fff", tags=("01n","init"))     # 
		xp = (c.coords("01n")[0]+c.coords("01n")[2])/2                                   # 8:00 am 
		yp = (c.coords("01n")[1]+c.coords("01n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="8:00 am - 10:00 am")          # 

		c.create_rectangle(x, y+120, x+124, y+192, fill="#fff", tags=("02n","init"))    # 
		xp = (c.coords("02n")[0]+c.coords("02n")[2])/2                                   # 10:00 am 
		yp = (c.coords("02n")[1]+c.coords("02n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="10:00 am - 12:00 pm")         # 

		c.create_rectangle(x, y+192, x+124, y+228, fill="#fff", tags=("03n","init"))    # 
		xp = (c.coords("03n")[0]+c.coords("03n")[2])/2                                   # 12:00 pm 
		yp = (c.coords("03n")[1]+c.coords("03n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="12:00 pm - 2:00 pm")          #

		c.create_rectangle(x, y+228, x+124, y+300, fill="#fff", tags=("04n","init"))    # 
		xp = (c.coords("04n")[0]+c.coords("04n")[2])/2                                   # 2:00 pm 
		yp = (c.coords("04n")[1]+c.coords("04n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="2:00 pm - 4:00 pm")           #

		c.create_rectangle(x, y+300, x+124, y+372, fill="#fff", tags=("05n","init"))    # 
		xp = (c.coords("05n")[0]+c.coords("05n")[2])/2                                   # 4:00 pm 
		yp = (c.coords("05n")[1]+c.coords("05n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="4:00 pm - 6:00 pm")           #

		c.create_rectangle(x, y+372, x+124, y+408, fill="#fff", tags=("06n","init"))    # 
		xp = (c.coords("06n")[0]+c.coords("06n")[2])/2                                   # 6:00 pm 
		yp = (c.coords("06n")[1]+c.coords("06n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="6:00 pm - 7:00 pm")           #

		c.create_rectangle(x, y+408, x+124, y+480, fill="#fff", tags=("07n","init"))    # 
		xp = (c.coords("07n")[0]+c.coords("07n")[2])/2                                   # 7:00 pm 
		yp = (c.coords("07n")[1]+c.coords("07n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="7:00 pm - 9:00 pm")           #

		c.create_rectangle(x, y+480, x+124, y+552, fill="#fff", tags=("08n","init"))    # 
		xp = (c.coords("08n")[0]+c.coords("08n")[2])/2                                   # 9:00 pm 
		yp = (c.coords("08n")[1]+c.coords("08n")[3])/2                                   # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="9:00 pm - 11:00 pm")          #

		week = ['Monday','Tuesday','Wednesday', 'Thursday', 'Friday']
		for i in range(5):
			c.create_rectangle(x+124+i*186, y+30, x+310+i*186, y+48, fill="#fff")
			c.create_rectangle(x+124+i*186, y+48, x+310+i*186, y+120, fill="#fff", tags=("00,0"+str(2*i),"init"))
			c.create_rectangle(x+124+i*186, y+120, x+310+i*186, y+192, fill="#fff", tags=("00,0"+str(2*i+1),"init"))
			c.create_rectangle(x+124+i*186, y+192, x+310+i*186, y+228, fill="#fff")
			c.create_rectangle(x+124+i*186, y+228, x+310+i*186, y+300, fill="#fff", tags=("01,0"+str(2*i),"init"))
			c.create_rectangle(x+124+i*186, y+300, x+310+i*186, y+372, fill="#fff", tags=("01,0"+str(2*i+1),"init"))
			c.create_rectangle(x+124+i*186, y+372, x+310+i*186, y+408, fill="#fff")
			c.create_rectangle(x+124+i*186, y+408, x+310+i*186, y+480, fill="#fff", tags=("02,0"+str(2*i),"init"))
			c.create_rectangle(x+124+i*186, y+480, x+310+i*186, y+552, fill="#fff", tags=("02,0"+str(2*i+1),"init"))
			c.create_text(x+217+i*186, y+39, font=("Arial","12"), text=week[i])

		halfSlots = []
		for i in range(len(profBook0[professor])):
			for j in range(5,len(profBook0[professor][i])):
			
				sbj = profBook0[professor][i][0]
				slot = profBook0[professor][i][j]
			
				if(j+1==len(profBook0[professor][i]) and profBook0[professor][i][2]%2==1):
				
					coord = c.coords("0"+str(profBook0[professor][i][1])+",0"+str(slot))
					coord = [int(i) for i in coord]
					if("0"+str(profBook0[professor][i][1])+",0"+str(slot) in halfSlots):
						c.create_rectangle((coord[0]+coord[2])/2, coord[1], coord[2], coord[3], fill="#ccc")
						c.create_text((coord[0]+3*coord[2])/4,(coord[1]+coord[3])/2, font=("Ubuntu","15"), justify='center', text="Subject "+str(sbj))
					else:
						c.create_rectangle(coord[0], coord[1], (coord[0]+coord[2])/2, coord[3], fill="#ccc")
						halfSlots.append("0"+str(profBook0[professor][i][1])+",0"+str(slot))
						c.create_text((3*coord[0]+coord[2])/4,(coord[1]+coord[3])/2, font=("Ubuntu","15"), justify='center', text="Subject "+str(sbj))
				else:
			
					coord = c.coords("0"+str(profBook0[professor][i][1])+",0"+str(slot))
					coord = [int(i) for i in coord]
					c.create_rectangle(coord[0], coord[1], coord[2], coord[3], fill="#ccc")
					c.create_text((coord[0]+coord[2])/2,(coord[1]+coord[3])/2, font=("Ubuntu","15"), justify='center', text="Subject "+str(sbj))

		# Tabu Search solution
	
		y += h/2
	
		c.create_text(w/2, y, font=("Ubuntu","16", "bold"), text="Professor "+str(professor)+" schedule in Tabu Search solution")

		c.create_rectangle(x, y+30, x+124, y+48, fill="#fff", tag="0n") # Blank rectangle

		c.create_rectangle(x, y+48, x+124, y+120, fill="#fff", tag="1n")       # 
		xp = (c.coords("1n")[0]+c.coords("1n")[2])/2                           # 8:00 am 
		yp = (c.coords("1n")[1]+c.coords("1n")[3])/2                           # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="8:00 am - 10:00 am")  # 

		c.create_rectangle(x, y+120, x+124, y+192, fill="#fff", tag="2n")      # 
		xp = (c.coords("2n")[0]+c.coords("2n")[2])/2                           # 10:00 am 
		yp = (c.coords("2n")[1]+c.coords("2n")[3])/2                           # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="10:00 am - 12:00 pm") # 

		c.create_rectangle(x, y+192, x+124, y+228, fill="#fff", tag="3n")      # 
		xp = (c.coords("3n")[0]+c.coords("3n")[2])/2                           # 12:00 pm 
		yp = (c.coords("3n")[1]+c.coords("3n")[3])/2                           # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="12:00 pm - 2:00 pm")  #

		c.create_rectangle(x, y+228, x+124, y+300, fill="#fff", tag="4n")      # 
		xp = (c.coords("4n")[0]+c.coords("4n")[2])/2                           # 2:00 pm 
		yp = (c.coords("4n")[1]+c.coords("4n")[3])/2                           # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="2:00 pm - 4:00 pm")   #

		c.create_rectangle(x, y+300, x+124, y+372, fill="#fff", tag="5n")      # 
		xp = (c.coords("5n")[0]+c.coords("5n")[2])/2                           # 4:00 pm 
		yp = (c.coords("5n")[1]+c.coords("5n")[3])/2                           # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="4:00 pm - 6:00 pm")   #

		c.create_rectangle(x, y+372, x+124, y+408, fill="#fff", tag="6n")      # 
		xp = (c.coords("6n")[0]+c.coords("6n")[2])/2                           # 6:00 pm 
		yp = (c.coords("6n")[1]+c.coords("6n")[3])/2                           # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="6:00 pm - 7:00 pm")   #

		c.create_rectangle(x, y+408, x+124, y+480, fill="#fff", tag="7n")      # 
		xp = (c.coords("7n")[0]+c.coords("7n")[2])/2                           # 7:00 pm 
		yp = (c.coords("7n")[1]+c.coords("7n")[3])/2                           # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="7:00 pm - 9:00 pm")   #

		c.create_rectangle(x, y+480, x+124, y+552, fill="#fff", tag="8n")      # 
		xp = (c.coords("8n")[0]+c.coords("8n")[2])/2                           # 9:00 pm 
		yp = (c.coords("8n")[1]+c.coords("8n")[3])/2                           # rectangle
		c.create_text(xp, yp, font=("Arial","12"), text="9:00 pm - 11:00 pm")  #

		week = ['Monday','Tuesday','Wednesday', 'Thursday', 'Friday']
		for i in range(5):
			c.create_rectangle(x+124+i*186, y+30, x+310+i*186, y+48, fill="#fff")
			c.create_rectangle(x+124+i*186, y+48, x+310+i*186, y+120, fill="#fff", tag="0,"+str(2*i))
			c.create_rectangle(x+124+i*186, y+120, x+310+i*186, y+192, fill="#fff", tag="0,"+str(2*i+1))
			c.create_rectangle(x+124+i*186, y+192, x+310+i*186, y+228, fill="#fff")
			c.create_rectangle(x+124+i*186, y+228, x+310+i*186, y+300, fill="#fff", tag="1,"+str(2*i))
			c.create_rectangle(x+124+i*186, y+300, x+310+i*186, y+372, fill="#fff", tag="1,"+str(2*i+1))
			c.create_rectangle(x+124+i*186, y+372, x+310+i*186, y+408, fill="#fff")
			c.create_rectangle(x+124+i*186, y+408, x+310+i*186, y+480, fill="#fff", tag="2,"+str(2*i))
			c.create_rectangle(x+124+i*186, y+480, x+310+i*186, y+552, fill="#fff", tag="2,"+str(2*i+1))
			c.create_text(x+217+i*186, y+39, font=("Arial","12"), text=week[i])

		halfSlots = []
		for i in range(len(profBook[professor])):
			for j in range(5,len(profBook[professor][i])):
			
				sbj = profBook[professor][i][0]
				slot = profBook[professor][i][j]
			
				if(j+1==len(profBook[professor][i]) and profBook[professor][i][2]%2==1):
				
					coord = c.coords(str(profBook[professor][i][1])+","+str(slot))
					coord = [int(i) for i in coord]
					if(str(profBook[professor][i][1])+","+str(slot) in halfSlots):
						c.create_rectangle((coord[0]+coord[2])/2, coord[1], coord[2], coord[3], fill="#ccc")
						c.create_text((coord[0]+3*coord[2])/4,(coord[1]+coord[3])/2, font=("Ubuntu","15"), justify='center', text="Subject "+str(sbj))
					else:
						c.create_rectangle(coord[0], coord[1], (coord[0]+coord[2])/2, coord[3], fill="#ccc")
						halfSlots.append(str(profBook[professor][i][1])+","+str(slot))
						c.create_text((3*coord[0]+coord[2])/4,(coord[1]+coord[3])/2, font=("Ubuntu","15"), justify='center', text="Subject "+str(sbj))
				else:
			
					coord = c.coords(str(profBook[professor][i][1])+","+str(slot))
					coord = [int(i) for i in coord]
					c.create_rectangle(coord[0], coord[1], coord[2], coord[3], fill="#ccc")
					c.create_text((coord[0]+coord[2])/2,(coord[1]+coord[3])/2, font=("Ubuntu","15"), justify='center', text="Subject "+str(sbj))
	
		c.update()
		c.postscript(file = "professor_"+str(professor)+"_schedule.ps", pageheight="29.70c",x="0",y="0",height="1754",width="1240") 

	os.system("convert -density 300 *.ps  schedules.pdf")
	os.system("find . -name \*.ps -type f -delete")
Пример #28
0
class Draw(Frame):
    '''
    Draw class for tkinter
    '''
    def __init__(self, root):
        super().__init__()

        self.initUI(root)

    def initUI(self, root):
        self.master.title("Auto Detected Robot")
        self.pack(fill=BOTH, expand=1)

        #some basic setting
        self.nowx = 600
        self.nowy = 545
        self.direction = 270
        self.interval = 0.1
        self.degree_per_second = 90 / 1.160
        self.basespeed = 2
        self.currentspeed = 0
        self.infobuffer = ''

        #setup canvas
        self.canvas = Canvas(self)
        self.currentcar = self.canvas.create_oval(self.nowx - 5,
                                                  self.nowy - 5,
                                                  self.nowx + 5,
                                                  self.nowy + 5,
                                                  fill="blue",
                                                  width=0)
        self.temptext = self.canvas.create_text(800,
                                                100,
                                                text="Temp:",
                                                font=("Times", "24"))
        self.lightext = self.canvas.create_text(800,
                                                150,
                                                text="Light:",
                                                font=("Times", "24"))

        self.canvas.pack(fill=BOTH, expand=1)
        '''
        self.left = Button(self.canvas,text='left',font=("","16"))
        self.right = Button(self.canvas,text='right',font=("","16"))
        self.left.pack(side="top", expand=False, anchor='w',padx=4, pady=4)
        self.right.pack(side="top", expand=False, anchor='w',padx=4, pady=4)
        '''

        #bind events
        root.bind('<Left>', leftArrow)
        root.bind('<Right>', rightArrow)
        root.bind('<Up>', upArrow)
        root.bind('<Down>', downArrow)

    def newPosition(self, deltax, deltay, color='blue'):
        # paint new position for the rebot
        cor = self.canvas.coords(self.currentcar)
        x0 = (cor[0] + cor[2]) / 2
        y0 = (cor[1] + cor[3]) / 2
        step = 5  # how many points between the previous position
        for i in range(step):
            dx = (deltax / step) * (i + 1)
            dy = (deltay / step) * (i + 1)
            self.currentcar = self.canvas.create_oval(x0 + dx - 5,
                                                      y0 + dy - 5,
                                                      x0 + dx + 5,
                                                      y0 + dy + 5,
                                                      fill=color,
                                                      width=0)
            time.sleep(self.interval / step)
            self.canvas.update()

    @staticmethod
    def rendercolor(light, temp):
        #change the function to get different color
        return 'blue'

    def parser(self, data):
        sp = data.split()
        #gprint(sp)
        try:
            result = {
                'direction': int(sp[0]),
                "light": int(sp[1]),
                "temp": float(sp[2])
            }
        except:
            return None
        else:
            return result

    def move(self, direction):
        degree = self.degree_per_second * self.interval

        #check if is turning
        if direction == 0:
            degree = 0
        elif direction == 2:
            degree = -degree

        #check whether stop or not
        if direction == 3:
            self.currentspeed = 0
        else:
            self.currentspeed = self.basespeed

        self.direction = (self.direction + degree) % 360
        dx = math.cos(d2r(self.direction)) * self.currentspeed
        dy = math.sin(d2r(self.direction)) * self.currentspeed

        # return deltax and deltay
        if direction != 0:
            return (0, 0)
        else:
            return (dx, dy)

    def recvinfor(self, data):
        self.infobuffer += data.decode('utf8', errors='ignore')
        buf = self.infobuffer
        newlinepos = buf.find('@\r\n')

        #if there is not a complete message, then return
        if newlinepos == -1:
            return

        onemessage = buf[:newlinepos]
        self.infobuffer = buf[newlinepos + 1:]
        info = self.parser(onemessage)  #parse one message
        if info == None:
            return

        print(info)
        direction = info['direction']
        (dx, dy) = self.move(direction)
        color = Draw.rendercolor(info['light'], info['temp'])
        self.canvas.itemconfig(self.temptext,
                               text='Temp: {} °C'.format(info['temp']))
        self.canvas.itemconfig(self.lightext,
                               text='Light: {}'.format(info['light']))
        self.newPosition(dx, dy, color)
Пример #29
0
class text_canvas(Frame):

    def __init__(self, parent, font_size, input_handler, filename):
        Frame.__init__(self, parent)
        self.parent = parent
        self.text_font = tkFont.Font(
            family='Monaco', size=font_size, weight='bold'
        )
        self.filename = filename
        self.cheight, self.cwidth = font_size, self.text_font.measure('c')
        self.line_num_spacing = 50
        self.line_height = (
            (self.winfo_screenheight() - self.cheight)//(self.cheight + 2) - 4
        )
        self.init_UI(input_handler)

    def init_UI(self, input_handler):
        self.parent.title('')
        self.pack(fill=BOTH, expand=1)
        self.init_canvas(input_handler)

    def get_dimensions(self):
        """
        Getting the dimensions might be helpful
        for plugin writers
        """
        return {
            'cheight': self.cheight,
            'cwidth': self.cwidth,
            'line_num_spacing': self.line_num_spacing,
            'line_height': self.line_height,
            'screen_width': self.winfo_screenwidth(),
            'screen_height': self.winfo_screenheight()
        }

    def init_canvas(self, input_handler):
        self.canvas = Canvas(
            self, highlightthickness=0, width=self.winfo_screenwidth(),
            height=self.winfo_screenheight(), bg=options['background_color']
        )
        self.canvas.pack()
        self.canvas.focus_set()
        self.bind_events(input_handler)

    def clear_all(self):
        self.canvas.delete('all')

    def get_line_height(self):
        """
        return number of lines per page
        """
        return self.line_height

    def get_grid_y(self, y):
        """
        return character height * y
        in addition distane of the spaces inbetwen
        """
        return self.cheight * y + (y * 2)

    def write_line_grid(self, y, line):
        """
        Write to line of text on grid using tokens passed in
        """
        for token in line:
            self.write_text_grid(token[0], y, token[1], token[2])

    def write_text_grid(self, x, y, text, color=options['text_color']):
        """
        Write text to x, y location on grid
        """
        x_val = self.cwidth * x + self.line_num_spacing
        y_val = self.cheight * y + (y * 2)  # 2 pixel spacing between each line
        self.canvas.create_text(
            x_val, y_val, anchor='nw', text=text,
            font=self.text_font, fill=color
        )

    def write_status_line(
        self, text, textcolor=options['status_text_color'],
        backgroundcolor=options['status_background_color']
    ):
        """
        Writen a line of text to status line
        this function could take in different data if desired
        """
        y = self.line_height + 1
        self.canvas.create_rectangle(
            0, self.cheight * y + (y * 2), self.winfo_screenwidth(),
            self.cheight * y + (y * 2) + self.cheight + 4,
            fill=backgroundcolor, outline=backgroundcolor
        )
        self.write_text_grid(0, self.line_height + 1, text, textcolor)

    def draw_highlight_grid(
        self, y, x1, x2,
        highlightcolor=options['text_highlight_color']
    ):
        """
        Draw highlights onto text canvas
        i.e selections during visual mode
        """
        y_val = self.cheight * y + (y * 2)
        x1_val = self.cwidth * x1 + self.line_num_spacing
        x2_val = self.cwidth * x2 + self.line_num_spacing
        self.canvas.create_rectangle(
            x1_val, y_val, x2_val, y_val + self.cheight + 4,
            fill=highlightcolor, outline=highlightcolor
        )

    def draw_line_numbers(
        self, start,
        highlightcolor=options['line_num_highlight_color'],
        textcolor=options['line_num_text_color']
    ):
        self.canvas.create_rectangle(
            0, 0, self.line_num_spacing / 2,
            self.winfo_screenheight(),
            fill=highlightcolor, outline=highlightcolor
        )
        for i in range(self.line_height + 1):
            self.canvas.create_text(
                0, self.cheight * i + (i * 2), anchor='nw',
                text=str(start + i), font=self.text_font,
                fill=textcolor
            )

    def draw_cursor(
        self, x, y,
        highlightcolor=options['cursor_highlight_color'],
        cursorcolor=options['cursor_color']
    ):
        """
        draw cursor as well as line and column highlights
        TODO: users should have the option to disable line
        and column highlights
        """
        x_val = self.cwidth * x + self.line_num_spacing
        y_val = self.cheight * y + (y * 2)

        self.canvas.create_rectangle(
            0, y_val, self.winfo_screenwidth(),
            y_val + self.cheight + 4,
            fill=highlightcolor, outline=highlightcolor
        )
        self.canvas.create_rectangle(
            x_val, 0, x_val + self.cwidth,
            self.winfo_screenheight(), fill=highlightcolor,
            outline=highlightcolor
        )
        self.canvas.create_rectangle(
            x_val, y_val, x_val + self.cwidth,
            y_val + self.cheight + 4,
            fill=cursorcolor, outline=cursorcolor
        )

    def draw_rectangle_absolute(
        self, x1, y1, x2, y2, color
    ):
        """
        draw rectangle onto screen
        TODO: flesh out what this function should actually
        look like
        """
        self.canvas.create_rectangle(
            x1, y1, x2, y2,
            fill=color, outline=color
        )

    def bind_events(self, input_handler):
        """
        bind events for use in input_handler
        TODO: this should be cleaned up ideally into a separate handler list
        """
        input_handler.set_GUI_reference(self)
        self.canvas.bind('<Key>', input_handler.key)
        self.canvas.bind_all('<Escape>', input_handler.escape)
        self.canvas.bind_all('<Control-a>', input_handler.control_a)
        self.canvas.bind_all('<Control-b>', input_handler.control_b)
        self.canvas.bind_all('<Control-c>', input_handler.control_c)
        self.canvas.bind_all('<Control-d>', input_handler.control_d)
        self.canvas.bind_all('<Control-e>', input_handler.control_e)
        self.canvas.bind_all('<Control-f>', input_handler.control_f)
        self.canvas.bind_all('<Control-g>', input_handler.control_g)
        self.canvas.bind_all('<Control-h>', input_handler.control_h)
        self.canvas.bind_all('<Control-i>', input_handler.control_i)
        self.canvas.bind_all('<Control-j>', input_handler.control_j)
        self.canvas.bind_all('<Control-k>', input_handler.control_k)
        self.canvas.bind_all('<Control-l>', input_handler.control_l)
        self.canvas.bind_all('<Control-m>', input_handler.control_m)
        self.canvas.bind_all('<Control-n>', input_handler.control_n)
        self.canvas.bind_all('<Control-o>', input_handler.control_o)
        self.canvas.bind_all('<Control-p>', input_handler.control_p)
        self.canvas.bind_all('<Control-q>', input_handler.control_q)
        self.canvas.bind_all('<Control-r>', input_handler.control_r)
        self.canvas.bind_all('<Control-s>', input_handler.control_s)
        self.canvas.bind_all('<Control-t>', input_handler.control_t)
        self.canvas.bind_all('<Control-u>', input_handler.control_u)
        self.canvas.bind_all('<Control-v>', input_handler.control_v)
        self.canvas.bind_all('<Control-w>', input_handler.control_w)
        self.canvas.bind_all('<Control-x>', input_handler.control_x)
        self.canvas.bind_all('<Control-y>', input_handler.control_y)
        self.canvas.bind_all('<Control-z>', input_handler.control_z)
        self.canvas.bind_all("<MouseWheel>", input_handler.mouse_scroll)
        self.canvas.bind_all(
            '<Control-braceright>', input_handler.control_braceright
        )
        self.canvas.bind_all(
            '<Control-braceleft>', input_handler.control_braceleft
        )
Пример #30
0
from tkinter import Canvas, Tk
import helpers

# initialize window
gui = Tk()
canvas = Canvas(gui, width=700, height=350, background='white')
canvas.pack()

########################## YOUR CODE BELOW THIS LINE ##############################

# make a label:
canvas.create_text(
    (210, 210),
    text="Hello world!",
    font=("Purisa", 32),
    anchor='nw'  # align to "northwest" corner
)

# make an oval:
canvas.create_oval(
    [(50, 150), (150, 250)],  # top left x-y, bottom right x-y
    fill='#FF4136',
    width=5)

# make a polygon
canvas.create_polygon(
    [(370, 150), (630, 150), (500, 350)],  # list of x-y pairs
    width=2,
    fill='#BCD39C',
    smooth=True)  #make smooth false for angular polygon
Пример #31
0
class Cube(MatrixHelpers):

    last_x = 0
    last_y = 0

    def __init__(self, root):
        self.root = root
        self.init_data()
        self.create_canvas()
        self.create_frame()
        self.create_control()
        self.epsilon = lambda d: d * 0.01

    def init_data(self):
        self.cube = self.transpose_matrix([[-100, -100,
                                            -100], [-100, 100, -100],
                                           [-100, -100, 100], [-100, 100, 100],
                                           [100, -100, -100], [100, 100, -100],
                                           [100, -100, 100], [100, 100, 100]])


# print(self.cube)
#[(-100, -100, -100, -100, 100, 100, 100, 100),
# (-100, 100, -100, 100, -100, 100, -100, 100),
# (-100, -100, 100, 100, -100, -100, 100, 100)]

    def create_canvas(self):
        self.canvas = Canvas(self.root, width=400, height=400)
        self.canvas.pack(fill=BOTH, expand=YES)

    def create_frame(self):
        self.frame = Frame(self.root, width=400, height=400)
        self.frame.pack(fill=BOTH, expand=YES)

    def create_control(self):
        self.rotX = Button(self.frame, text="Draw", command=self.rotaX)
        self.rotX.pack()
        self.rotX = Button(self.frame,
                           text="Rotate along X",
                           command=self.rotaX)
        self.rotX.pack()
        self.rotY = Button(self.frame,
                           text="Rotate along Y",
                           command=self.rotaY)
        self.rotY.pack()

    def draw_cube(self):
        cube_points = [[0, 1, 2, 4], [3, 1, 2, 7], [5, 1, 4, 7], [6, 2, 4, 7]]
        '''
            2..........6
          . .         ..
        .   .       .  .
       0..........4    .
       .    3     .    7
       .  .       .   .
       . .        . .
       1..........5

    '''
        w = self.canvas.winfo_width() / 2
        h = self.canvas.winfo_height() / 2
        self.canvas.delete(ALL)
        for i in cube_points:
            for j in i:
                self.canvas.create_line(
                    self.translate_vector(self.cube[0][i[0]],
                                          self.cube[1][i[0]], w, h),
                    self.translate_vector(self.cube[0][j], self.cube[1][j], w,
                                          h))
                self.canvas.create_text(
                    self.translate_vector(self.cube[0][i[0]],
                                          self.cube[1][i[0]], w, h),
                    text=str("{0:.2f}".format(self.cube[0][i[0]])) + " , " +
                    str("{0:.2f}".format(self.cube[1][i[0]])) + " , " +
                    str("{0:.2f}".format(self.cube[2][i[0]])))
                self.canvas.create_text(
                    self.translate_vector(self.cube[0][j], self.cube[1][j], w,
                                          h),
                    text=str("{0:.2f}".format(self.cube[0][j])) + " , " +
                    str("{0:.2f}".format(self.cube[1][j])) + " , " +
                    str("{0:.2f}".format(self.cube[2][j])))

    def rotaX(self):
        self.cube = self.rotate_along_x(self.epsilon(5), self.cube)
        self.draw_cube()

    def draw(self):
        self.cube = self.rotate_along_x(0, self.cube)
        self.draw_cube()

    def rotaY(self):
        self.cube = self.rotate_along_y(self.epsilon(5), self.cube)
        self.draw_cube()
Пример #32
0
catcher_start_y2 = catcher_start_y + catcher_height

catcher = c.create_arc(catcher_start_x,
                       catcher_start_y,
                       catcher_start_x2,
                       catcher_start_y2,
                       start=200,
                       extent=140,
                       style='arc',
                       outline=catcher_color,
                       width=3)

score = 0
score_text = c.create_text(10,
                           10,
                           anchor='nw',
                           font=('Arial', 18, 'bold'),
                           fill='darkblue',
                           text='Score : ' + str(score))

lives_remaning = 3
lives_text = c.create_text(canvas_width - 10,
                           10,
                           anchor='ne',
                           font=('Arial', 18, 'bold'),
                           fill='darkblue',
                           text='Lives : ' + str(lives_remaning))

eggs = []


def create_eggs():
Пример #33
0
class SudokuUI(Frame):
    """
    The Tkinter UI, responsible for displaying the UI.
    """
    def __init__(self, parent, game):
        self.game = game
        self.parent = parent
        Frame.__init__(self, parent)

        self.row, self.col = 0, 0

        self.__initUI()

        def __initUI(self):
            self.parent.title("Sudoku")
            self.pack(fill=BOTH, expand=1)  # Use all available space
            self.canvas = Canvas(self, width=WIDTH, heigh=HEIGHT)
            self.canvas.pack(fill=BOTH, side=TOP)  # Pull board to top of frame
            clear_button = Button(self, text="Clear answers", command=self.__clear_answers)
            clear_button.pack(fill=BOTH, side=BOTTOM)

            self.__draw_grid()
            self.__draw_puzzle()

            self.canvas.bind("<Button-1>", self.__cell_clicked)
            self.canvas.bind("<Key>", self.__key_pressed)

        def __draw_grid(self):
            """
            Draws grid divided with blue lines into 3 x 3 grid
            :return:
            """
            for i in range(10):
                color = 'blue' if i % 3 == 0 else "gray"

                x0 = MARGIN + i * SIDE
                y0 = MARGIN
                x1 = MARGIN + i * SIDE
                y1 = HEIGHT - MARGIN
                self.canvas.create_line(x0, y0, x1, y1, fill=color)

                x0 = MARGIN
                y0 = MARGIN + i * SIDE
                x1 = WIDTH - MARGIN
                y1 = MARGIN + i * SIDE
                self.canvas.create_line(x0, y0, x1, y1, fill=color)

        def __draw_puzzle(self):
            self.canvas.delete("numbers")
            for i in xrange(9):
                for j in xrange(9):
                    answer = self.game.puzzle[i][j]
                    if answer != 0:
                        x = MARGIN + j * SIDE + SIDE / 2
                        y = MARGIN + i * SIDE + SIDE / 2
                        original = self.game.start_puzzle[i][j]
                        color = "black" if answer == original else "sea green"
                        self.canvas.create_text(x, y, text=answer, tags="number", fill=color)

        def __clear_answers(self):
            self.game.start()
            self.canvas.delete("victory")
            self.__draw_puzze()

        def __cell_clicked(self, event):  # event has x, y coords of mouse click
            if self.game.game_over:
                return

            x, y = event.x, event.y
            if (MARGIN < x < WIDTH - MARGIN) and (MARGIN < Y < HEIGHT - MARGIN):
                self.canvas.focus_set()

                # get row and col numbers from x, y coords
                row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE

                # if cell already selected then deselect it
                if (row, col) == (self.row, self.col):
                    self.row, self.col = -1, -1  # outside the grid
                elif self.game.puzzle[row][col] == 0:
                    self.row, self.col = row, col

            self.__draw_cursor()

        def __draw_cursor(self):
            self.canvas.delete("cursor")
            if self.row >= 0 and self.col >= 0:
                x0 = MARGIN + self.col * SIDE + 1
                y0 = MARGIN + self.row * SIDE + 1
                x1 = MARGIN + (self.col + 1) * SIDE - 1
                y1 = MARGIN + (self.row + 1) * SIDE - 1
                self.canvas.create_rectangle(
                    x0, y0, x1, y1,
                    outline ="red", tags ="cursor"
                )
Пример #34
0
gui.title('Tour of options...')

# initialize canvas:
window_width = gui.winfo_screenwidth()
window_height = gui.winfo_screenheight()
canvas = Canvas(gui, width=window_width, height=window_height, background='white')
canvas.pack()

########################## YOUR CODE BELOW THIS LINE ##############################
MOUSE_CLICK = '<Button-1>'
MOUSE_DRAG = '<B1-Motion>'
RIGHT_CLICK = '<Button-2>'
KEY_PRESS = '<Key>'
canvas.create_text(
    (window_width / 2, window_height / 2), 
    text='Click circle to select it. Drag selected circle to move it.', 
    font=("Purisa", 32)
)

# need a global variable to store which item should be clicked:
active_tag = None

def select_circle(event):
    global active_tag
    
    # if something is already active, deactivate it:
    if active_tag:
        utilities.update_fill_by_tag(canvas, active_tag, 'hotpink')
        active_tag = None
    
    # get new active tag:
Пример #35
0
class World(Tk):
    def __init__(self, filename=None, block=50, debug=True, delay=0.25,
                 image=False, width=10, height=10):
        Tk.__init__(self)
        self.title("")
        arg = block
        self.width = width
        self.height = height
        self.beepers = {}
        self.ovals = {}
        self.numbers = {}
        self.robots = {}
        self.walls = {}
        self.m = arg * (width + 3)
        self.n = arg * (height + 3)
        self.t = arg
        self.delay = delay
        self.debug = debug
        self.use_image = image
        a = self.t + self.t / 2
        b = self.m - self.t / 2
        c = self.n - self.t / 2
        self.canvas = Canvas(self, bg="white", width=self.m, height=self.n)
        self.canvas.pack()
        count = 1
        for k in range(2*self.t, max(self.m, self.n)-self.t, self.t):
            if k < b:
                self.canvas.create_line(k, c, k, a, fill="red")
                self.canvas.create_text(k, c+self.t/2, text=str(count),
                                        font=("Times",
                                              max(-self.t*2/3, -15), ""))
            if k < c:
                self.canvas.create_line(b, k, a, k, fill="red")
                self.canvas.create_text(a-self.t/2, self.n-k, text=str(count),
                                        font=("Times",
                                              max(-self.t*2/3, -15), ""))
            count += 1
        self.canvas.create_line(a, c, b, c, fill="black", width=3)
        self.canvas.create_line(a, a, a, c, fill="black", width=3)
        if filename is not None:
            self.read_world(filename)
        self.refresh()

    def read_world(self, filename):
        try:
            infile = open("worlds\\{0}.wld".format(filename), "r")
        except IOError:
            try:
                infile = open("worlds/{0}.wld".format(filename), "r")
            except IOError:
                infile = open(filename, "r")
        text = infile.read().split("\n")
        infile.close()
        for t in text:
            if t.startswith("eastwestwalls"):
                s = t.split(" ")
                y, x = int(s[1]), int(s[2])
                self.add_wall(x, y, -1, y)
            if t.startswith("northsouthwalls"):
                s = t.split(" ")
                x, y = int(s[1]), int(s[2])
                self.add_wall(x, y, x, -1)
            if t.startswith("beepers"):
                s = t.split(" ")
                y, x, n = int(s[1]), int(s[2]), int(s[3])
                if n is INFINITY:
                    self.add_infinite_beepers(x, y)
                else:
                    for k in range(n):
                        self.add_beeper(x, y)

    def pause(self):
        sleep(self.delay)

    def is_beeper(self, x, y):
        return (x, y) in list(self.beepers.keys()) and not \
            self.beepers[(x, y)] == 0

    def count_robots(self, x, y):
        if (x, y) not in list(self.robots.keys()):
            return 0
        return len(self.robots[(x, y)])

    def crash(self, x1, y1, x2, y2):
        if 0 in (x1, y1, x2, y2):
            return True
        if (x2, y2) in list(self.walls.keys()) and \
                (x1, y1) in self.walls[(x2, y2)]:
            return True
        if (x1, y1) in list(self.walls.keys()) and \
                (x2, y2) in self.walls[(x1, y1)]:
            return True
        return False

    def add_infinite_beepers(self, x, y):
        flag = (x, y) not in list(self.beepers.keys()) or \
            self.beepers[(x, y)] is 0
        self.beepers[(x, y)] = INFINITY
        text = "oo"
        a = self.t + x * self.t
        b = self.n - (self.t + y * self.t)
        t = self.t / 3
        if flag:
            self.ovals[(x, y)] = self.canvas.create_oval(a-t, b-t, a+t,
                                                         b+t, fill="black")
            self.numbers[(x, y)] = self.canvas.create_text(a, b, text=text,
                                                           fill="white",
                                                           font=("Times",
                                                                 max(-self.t/2,
                                                                     -20),
                                                                 ""))
        else:
            self.canvas.itemconfig(self.numbers[(x, y)], text=text)
        if (x, y) in list(self.robots.keys()):
            for robot in self.robots[(x, y)]:
                robot.lift()

    def add_beeper(self, x, y):
        if (x, y) in list(self.beepers.keys()) and \
                self.beepers[(x, y)] is INFINITY:
            return
        flag = (x, y) not in list(self.beepers.keys()) or \
            self.beepers[(x, y)] is 0
        if flag:
            self.beepers[(x, y)] = 1
        else:
            self.beepers[(x, y)] += 1
        text = str(self.beepers[(x, y)])
        a = self.t + x * self.t
        b = self.n - (self.t + y * self.t)
        t = self.t / 3
        if flag:
            self.ovals[(x, y)] = self.canvas.create_oval(a-t, b-t, a+t, b+t,
                                                         fill="black")
            self.numbers[(x, y)] = self.canvas.create_text(a, b, text=text,
                                                           fill="white",
                                                           font=("Times",
                                                                 max(-self.t/2,
                                                                     -20),
                                                                 ""))
        else:
            self.canvas.itemconfig(self.numbers[(x, y)], text=text)
        if (x, y) in list(self.robots.keys()):
            for robot in self.robots[(x, y)]:
                robot.lift()

    def remove_beeper(self, x, y):
        if self.beepers[(x, y)] is INFINITY:
            return
        self.beepers[(x, y)] -= 1
        flag = self.beepers[(x, y)] is 0
        text = str(self.beepers[(x, y)])
        if flag:
            self.canvas.delete(self.ovals[(x, y)])
            self.canvas.delete(self.numbers[(x, y)])
        else:
            self.canvas.itemconfig(self.numbers[(x, y)], text=text)
        if (x, y) in list(self.robots.keys()):
            for robot in self.robots[(x, y)]:
                robot.lift()

    def add_wall(self, x1, y1, x2, y2):
        if not x1 == x2 and not y1 == y2:
            return
        if x1 == x2:
            y1, y2 = min(y1, y2), max(y1, y2)
            if y1 == -1:
                y1 = y2
            for k in range(y1, y2+1):
                self.walls.setdefault((x1, k), []).append((x1+1, k))
                a = self.t + x1 * self.t+self.t / 2
                b = self.n - (self.t + k * self.t) + self.t / 2
                c = self.t + x1 * self.t + self.t / 2
                d = self.n - (self.t + k * self.t) - self.t / 2
                self.canvas.create_line(a, b+1, c, d-1, fill="black", width=3)
        else:
            x1, x2 = min(x1, x2), max(x1, x2)
            if x1 == -1:
                x1 = x2
            for k in range(x1, x2+1):
                self.walls.setdefault((k, y1), []).append((k, y1+1))
                a = self.t + k * self.t - self.t / 2
                b = self.n - (self.t + y1 * self.t) - self.t / 2
                c = self.t + k * self.t + self.t / 2
                d = self.n - (self.t + y1 * self.t) - self.t / 2
                self.canvas.create_line(a-1, b, c+1, d, fill="black", width=3)

    def draw(self, x, y, d, img):
        t = self.t / 2
        angle = 120
        x = self.t + x * self.t
        y = self.n - (self.t + y * self.t)
        x1 = x + 3 ** 0.5 * t / 2 * cos(radians(d))
        y1 = y - 3 ** 0.5 * t / 2 * sin(radians(d))
        x2 = x + t * cos(radians(d + angle))
        y2 = y - t * sin(radians(d + angle))
        x3 = x + t / 4 * cos(radians(d + 180))
        y3 = y - t / 4 * sin(radians(d + 180))
        x4 = x + t * cos(radians(d - angle))
        y4 = y - t * sin(radians(d - angle))
        if img is not None:
            self.canvas.delete(img)
        return self.canvas.create_polygon(x1, y1, x2, y2, x3, y3, x4, y4,
                                          fill="blue")

    def erase(self, img):
        self.canvas.delete(img)

    def record_move(self, count, x1, y1, x2, y2):
        for robot in self.robots[(x1, y1)]:
            if robot.count == count:
                self.robots[(x1, y1)].remove(robot)
                self.robots.setdefault((x2, y2), []).append(robot)
                break

    def lift(self, img):
        self.canvas.lift(img)

    def refresh(self):
        self.canvas.update()
        self.pause()

    def register(self, x, y, robot):
        self.robots.setdefault((x, y), []).append(robot)

    def remove(self, x, y, robot):
        self.robots[(x, y)].remove(robot)
Пример #36
0
class FullScreenApp(object):
    def __init__(self):
        self.master = tk.Tk()
        self._geom = '200x200+0+0'
        self.master.attributes('-fullscreen', True)
        self.width = self.master.winfo_screenwidth()
        self.height = self.master.winfo_screenheight()
        self.w = Canvas(self.master)
        self.w.focus_set()
        self.w.pack(fill="both", expand=True)
        self.counter = 0

        # if want to use another photo, convert it (code at defines) and make it a tk photo image. then add to button
        self.calib_photo = tk.PhotoImage(file="Calibration/morty_eyes.ppm")
        self.end_calib_photo = tk.PhotoImage(
            file="Calibration/morty_happy.ppm")
        self.recalibrate_photo = tk.PhotoImage(
            file="Calibration/morty_angry.ppm")
        self.exit_photo = tk.PhotoImage(file="Calibration/morty_exit.ppm")
        self.wait_photo = tk.PhotoImage(file="Calibration/morty_happy.ppm")

        self.var = tk.IntVar()
        self.button = tk.Button(self.master,
                                text="#",
                                image=self.calib_photo,
                                command=lambda: self.var.set(1))
        self.second_button = tk.Button(self.master,
                                       text="I'm satisfied with the result",
                                       command=lambda: self.setvar())
        self.text_box = 0
        self.finish = False

    def print_calib_stage(self, stage):
        s = "Current stage number: " + str(stage) + "\n Please look on the "
        if stage == 0:
            self.text_box = self.w.create_text((850, 120),
                                               text="Starting Calibration",
                                               font="MSGothic 20 bold",
                                               fill="#652828")
            my_text = s + "left Morty"
        elif stage == 1:
            my_text = s + "upper left Morty"
        elif stage == 2:
            my_text = s + "upper Morty"
        elif stage == 3:
            my_text = s + "upper right Morty"
        elif stage == 4:
            my_text = s + "right Morty"
        elif stage == 5:
            my_text = s + "downer right Morty"
        elif stage == 6:
            my_text = s + "downer Morty"
        elif stage == 7:
            my_text = s + "downer left Morty"
        elif stage == 8:
            my_text = s + "center Morty"
        elif stage == 9:
            self.w.itemconfig(self.text_box,
                              text="Check your calibration points")
            self.button.place(relx=0.25, rely=0.5, anchor="c")
            self.button.config(text="I want to Recalibrate",
                               image=self.recalibrate_photo,
                               compound="left")
            self.second_button.place(relx=.75, rely=.5, anchor="c")
            self.second_button.config(image=self.end_calib_photo,
                                      compound="left")
            return
        else:
            my_text = " "
        x = stage_dot_locations[stage][0]
        y = stage_dot_locations[stage][1]
        self.button.place(relx=x, rely=y, anchor="c")
        self.w.itemconfig(self.text_box, text=my_text)

    def setvar(self):
        self.finish = True
        self.var.set(1)

    def move_button_to_pixel(self, pixel):
        self.w.focus_set()
        self.button.place_forget()
        self.button.place(x=pixel[0], y=pixel[1], anchor="c")
        self.master.update()

    def arrange_live_draw(self):
        self.button.place(relx=0.25, rely=0.5, anchor="c")
        self.button.config(text="Click to re-Draw")
        self.second_button.place(relx=.75, rely=.5, anchor="c")
        self.second_button.config(text="Click to Exit")
        self.wait_key()
        self.button.place_forget()
        self.second_button.place_forget()
        self.counter = 0
        self.w.delete("all")
        self.master.update()

    def only_exit_button(self):
        self.button.place_forget()
        self.second_button.place(relx=.5, rely=.5, anchor="c")
        self.second_button.config(text="Click to Exit",
                                  image=self.exit_photo,
                                  compound="left")
        self.wait_key()
        self.second_button.place_forget()
        self.counter = 0
        self.w.delete("all")
        self.master.update()

    def print_pixel(self,
                    pixel,
                    colour=None,
                    clear_prev=False,
                    with_button=False,
                    delta=15):
        if clear_prev:
            self.w.delete("all")
            self.master.update()
        self.w.focus_set()
        self.w.create_oval(pixel[0],
                           pixel[1],
                           pixel[0] + delta,
                           pixel[1] + delta,
                           fill=colour if colour is not None else "#FF0000")
        if with_button:
            self.move_button_to_pixel(pixel)
        self.counter += 1
        self.master.update()
        return pixel

    def print_calib_points(self, center, colour=None):
        perimeter = 24
        radius = 0.5 * perimeter
        if colour is None:
            self.w.create_oval(center[0],
                               center[1],
                               center[0] + perimeter,
                               center[1] + perimeter,
                               fill="#FF0000")
        else:
            self.w.create_oval(center[0],
                               center[1],
                               center[0] + perimeter,
                               center[1] + perimeter,
                               fill=colour)

        self.w.create_text((center[0] + radius, center[1] + radius),
                           text="center dot",
                           font="MSGothic 8 bold",
                           fill="#652828")

    def wait_key(self):
        self.button.wait_variable(self.var)

    def post_process(self,
                     precent=0,
                     process_name="Getting Pixels from video"):
        if self.finish:
            self.post_text_box = self.w.create_text((850, 120),
                                                    text="",
                                                    font="MSGothic 20 bold",
                                                    fill="#652828")
            self.master.update()
            self.finish = False
        self.w.itemconfig(self.post_text_box,
                          text="Postprocess. \n {} \n {:.2f}%".format(
                              process_name, precent))
        self.master.update()
Пример #37
0
def Schedules(profBook, profBook0):

    from tkinter import Tk
    from tkinter import Canvas
    import os

    mod = 1
    try:
        profBook[-1]
    except:
        mod = 0
    for professor in (range(len(profBook) - mod)):
        master = Tk()

        w = 1240
        h = 1754
        x = 86
        y = 86

        c = Canvas(master, width=1240, height=1754)
        c.pack()

        # Initial solution

        c.create_text(w / 2,
                      y,
                      font=("Ubuntu", "16", "bold"),
                      text="Professor " + str(professor) +
                      " schedule in initial solution")

        c.create_rectangle(x,
                           y + 30,
                           x + 124,
                           y + 48,
                           fill="#fff",
                           tags=("00n", "init"))  # Blank rectangle

        c.create_rectangle(x,
                           y + 48,
                           x + 124,
                           y + 120,
                           fill="#fff",
                           tags=("01n", "init"))  #
        xp = (c.coords("01n")[0] + c.coords("01n")[2]) / 2  # 8:00 am
        yp = (c.coords("01n")[1] + c.coords("01n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="8:00 am - 10:00 am")  #

        c.create_rectangle(x,
                           y + 120,
                           x + 124,
                           y + 192,
                           fill="#fff",
                           tags=("02n", "init"))  #
        xp = (c.coords("02n")[0] + c.coords("02n")[2]) / 2  # 10:00 am
        yp = (c.coords("02n")[1] + c.coords("02n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="10:00 am - 12:00 pm")  #

        c.create_rectangle(x,
                           y + 192,
                           x + 124,
                           y + 228,
                           fill="#fff",
                           tags=("03n", "init"))  #
        xp = (c.coords("03n")[0] + c.coords("03n")[2]) / 2  # 12:00 pm
        yp = (c.coords("03n")[1] + c.coords("03n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="12:00 pm - 2:00 pm")  #

        c.create_rectangle(x,
                           y + 228,
                           x + 124,
                           y + 300,
                           fill="#fff",
                           tags=("04n", "init"))  #
        xp = (c.coords("04n")[0] + c.coords("04n")[2]) / 2  # 2:00 pm
        yp = (c.coords("04n")[1] + c.coords("04n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="2:00 pm - 4:00 pm")  #

        c.create_rectangle(x,
                           y + 300,
                           x + 124,
                           y + 372,
                           fill="#fff",
                           tags=("05n", "init"))  #
        xp = (c.coords("05n")[0] + c.coords("05n")[2]) / 2  # 4:00 pm
        yp = (c.coords("05n")[1] + c.coords("05n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="4:00 pm - 6:00 pm")  #

        c.create_rectangle(x,
                           y + 372,
                           x + 124,
                           y + 408,
                           fill="#fff",
                           tags=("06n", "init"))  #
        xp = (c.coords("06n")[0] + c.coords("06n")[2]) / 2  # 6:00 pm
        yp = (c.coords("06n")[1] + c.coords("06n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="6:00 pm - 7:00 pm")  #

        c.create_rectangle(x,
                           y + 408,
                           x + 124,
                           y + 480,
                           fill="#fff",
                           tags=("07n", "init"))  #
        xp = (c.coords("07n")[0] + c.coords("07n")[2]) / 2  # 7:00 pm
        yp = (c.coords("07n")[1] + c.coords("07n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="7:00 pm - 9:00 pm")  #

        c.create_rectangle(x,
                           y + 480,
                           x + 124,
                           y + 552,
                           fill="#fff",
                           tags=("08n", "init"))  #
        xp = (c.coords("08n")[0] + c.coords("08n")[2]) / 2  # 9:00 pm
        yp = (c.coords("08n")[1] + c.coords("08n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="9:00 pm - 11:00 pm")  #

        week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
        for i in range(5):
            c.create_rectangle(x + 124 + i * 186,
                               y + 30,
                               x + 310 + i * 186,
                               y + 48,
                               fill="#fff")
            c.create_rectangle(x + 124 + i * 186,
                               y + 48,
                               x + 310 + i * 186,
                               y + 120,
                               fill="#fff",
                               tags=("00,0" + str(2 * i), "init"))
            c.create_rectangle(x + 124 + i * 186,
                               y + 120,
                               x + 310 + i * 186,
                               y + 192,
                               fill="#fff",
                               tags=("00,0" + str(2 * i + 1), "init"))
            c.create_rectangle(x + 124 + i * 186,
                               y + 192,
                               x + 310 + i * 186,
                               y + 228,
                               fill="#fff")
            c.create_rectangle(x + 124 + i * 186,
                               y + 228,
                               x + 310 + i * 186,
                               y + 300,
                               fill="#fff",
                               tags=("01,0" + str(2 * i), "init"))
            c.create_rectangle(x + 124 + i * 186,
                               y + 300,
                               x + 310 + i * 186,
                               y + 372,
                               fill="#fff",
                               tags=("01,0" + str(2 * i + 1), "init"))
            c.create_rectangle(x + 124 + i * 186,
                               y + 372,
                               x + 310 + i * 186,
                               y + 408,
                               fill="#fff")
            c.create_rectangle(x + 124 + i * 186,
                               y + 408,
                               x + 310 + i * 186,
                               y + 480,
                               fill="#fff",
                               tags=("02,0" + str(2 * i), "init"))
            c.create_rectangle(x + 124 + i * 186,
                               y + 480,
                               x + 310 + i * 186,
                               y + 552,
                               fill="#fff",
                               tags=("02,0" + str(2 * i + 1), "init"))
            c.create_text(x + 217 + i * 186,
                          y + 39,
                          font=("Arial", "12"),
                          text=week[i])

        halfSlots = []
        for i in range(len(profBook0[professor])):
            for j in range(5, len(profBook0[professor][i])):

                sbj = profBook0[professor][i][0]
                slot = profBook0[professor][i][j]

                if (j + 1 == len(profBook0[professor][i])
                        and profBook0[professor][i][2] % 2 == 1):

                    coord = c.coords("0" +
                                     str(profBook0[professor][i][1] - 1) +
                                     ",0" + str(slot))
                    coord = [int(i) for i in coord]
                    if ("0" + str(profBook0[professor][i][1] - 1) + ",0" +
                            str(slot) in halfSlots):
                        c.create_rectangle((coord[0] + coord[2]) / 2,
                                           coord[1],
                                           coord[2],
                                           coord[3],
                                           fill="#ccc")
                        c.create_text((coord[0] + 3 * coord[2]) / 4,
                                      (coord[1] + coord[3]) / 2,
                                      font=("Ubuntu", "15"),
                                      justify='center',
                                      text="Subject " + str(sbj))
                    else:
                        c.create_rectangle(coord[0],
                                           coord[1], (coord[0] + coord[2]) / 2,
                                           coord[3],
                                           fill="#ccc")
                        halfSlots.append("0" +
                                         str(profBook0[professor][i][1] - 1) +
                                         ",0" + str(slot))
                        c.create_text((3 * coord[0] + coord[2]) / 4,
                                      (coord[1] + coord[3]) / 2,
                                      font=("Ubuntu", "15"),
                                      justify='center',
                                      text="Subject " + str(sbj))
                else:

                    coord = c.coords("0" +
                                     str(profBook0[professor][i][1] - 1) +
                                     ",0" + str(slot))
                    coord = [int(i) for i in coord]
                    c.create_rectangle(coord[0],
                                       coord[1],
                                       coord[2],
                                       coord[3],
                                       fill="#ccc")
                    c.create_text((coord[0] + coord[2]) / 2,
                                  (coord[1] + coord[3]) / 2,
                                  font=("Ubuntu", "15"),
                                  justify='center',
                                  text="Subject " + str(sbj))

        # Tabu Search solution

        y += h / 2

        c.create_text(w / 2,
                      y,
                      font=("Ubuntu", "16", "bold"),
                      text="Professor " + str(professor) +
                      " schedule in Tabu Search solution")

        c.create_rectangle(x, y + 30, x + 124, y + 48, fill="#fff",
                           tag="0n")  # Blank rectangle

        c.create_rectangle(x, y + 48, x + 124, y + 120, fill="#fff",
                           tag="1n")  #
        xp = (c.coords("1n")[0] + c.coords("1n")[2]) / 2  # 8:00 am
        yp = (c.coords("1n")[1] + c.coords("1n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="8:00 am - 10:00 am")  #

        c.create_rectangle(x, y + 120, x + 124, y + 192, fill="#fff",
                           tag="2n")  #
        xp = (c.coords("2n")[0] + c.coords("2n")[2]) / 2  # 10:00 am
        yp = (c.coords("2n")[1] + c.coords("2n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="10:00 am - 12:00 pm")  #

        c.create_rectangle(x, y + 192, x + 124, y + 228, fill="#fff",
                           tag="3n")  #
        xp = (c.coords("3n")[0] + c.coords("3n")[2]) / 2  # 12:00 pm
        yp = (c.coords("3n")[1] + c.coords("3n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="12:00 pm - 2:00 pm")  #

        c.create_rectangle(x, y + 228, x + 124, y + 300, fill="#fff",
                           tag="4n")  #
        xp = (c.coords("4n")[0] + c.coords("4n")[2]) / 2  # 2:00 pm
        yp = (c.coords("4n")[1] + c.coords("4n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="2:00 pm - 4:00 pm")  #

        c.create_rectangle(x, y + 300, x + 124, y + 372, fill="#fff",
                           tag="5n")  #
        xp = (c.coords("5n")[0] + c.coords("5n")[2]) / 2  # 4:00 pm
        yp = (c.coords("5n")[1] + c.coords("5n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="4:00 pm - 6:00 pm")  #

        c.create_rectangle(x, y + 372, x + 124, y + 408, fill="#fff",
                           tag="6n")  #
        xp = (c.coords("6n")[0] + c.coords("6n")[2]) / 2  # 6:00 pm
        yp = (c.coords("6n")[1] + c.coords("6n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="6:00 pm - 7:00 pm")  #

        c.create_rectangle(x, y + 408, x + 124, y + 480, fill="#fff",
                           tag="7n")  #
        xp = (c.coords("7n")[0] + c.coords("7n")[2]) / 2  # 7:00 pm
        yp = (c.coords("7n")[1] + c.coords("7n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="7:00 pm - 9:00 pm")  #

        c.create_rectangle(x, y + 480, x + 124, y + 552, fill="#fff",
                           tag="8n")  #
        xp = (c.coords("8n")[0] + c.coords("8n")[2]) / 2  # 9:00 pm
        yp = (c.coords("8n")[1] + c.coords("8n")[3]) / 2  # rectangle
        c.create_text(xp, yp, font=("Arial", "12"),
                      text="9:00 pm - 11:00 pm")  #

        week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
        for i in range(5):
            c.create_rectangle(x + 124 + i * 186,
                               y + 30,
                               x + 310 + i * 186,
                               y + 48,
                               fill="#fff")
            c.create_rectangle(x + 124 + i * 186,
                               y + 48,
                               x + 310 + i * 186,
                               y + 120,
                               fill="#fff",
                               tag="0," + str(2 * i))
            c.create_rectangle(x + 124 + i * 186,
                               y + 120,
                               x + 310 + i * 186,
                               y + 192,
                               fill="#fff",
                               tag="0," + str(2 * i + 1))
            c.create_rectangle(x + 124 + i * 186,
                               y + 192,
                               x + 310 + i * 186,
                               y + 228,
                               fill="#fff")
            c.create_rectangle(x + 124 + i * 186,
                               y + 228,
                               x + 310 + i * 186,
                               y + 300,
                               fill="#fff",
                               tag="1," + str(2 * i))
            c.create_rectangle(x + 124 + i * 186,
                               y + 300,
                               x + 310 + i * 186,
                               y + 372,
                               fill="#fff",
                               tag="1," + str(2 * i + 1))
            c.create_rectangle(x + 124 + i * 186,
                               y + 372,
                               x + 310 + i * 186,
                               y + 408,
                               fill="#fff")
            c.create_rectangle(x + 124 + i * 186,
                               y + 408,
                               x + 310 + i * 186,
                               y + 480,
                               fill="#fff",
                               tag="2," + str(2 * i))
            c.create_rectangle(x + 124 + i * 186,
                               y + 480,
                               x + 310 + i * 186,
                               y + 552,
                               fill="#fff",
                               tag="2," + str(2 * i + 1))
            c.create_text(x + 217 + i * 186,
                          y + 39,
                          font=("Arial", "12"),
                          text=week[i])

        halfSlots = []
        for i in range(len(profBook[professor])):
            for j in range(5, len(profBook[professor][i])):

                sbj = profBook[professor][i][0]
                slot = profBook[professor][i][j]

                if (j + 1 == len(profBook[professor][i])
                        and profBook[professor][i][2] % 2 == 1):

                    coord = c.coords(
                        str(profBook[professor][i][1] - 1) + "," + str(slot))
                    coord = [int(i) for i in coord]
                    if (str(profBook[professor][i][1] - 1) + "," + str(slot)
                            in halfSlots):
                        c.create_rectangle((coord[0] + coord[2]) / 2,
                                           coord[1],
                                           coord[2],
                                           coord[3],
                                           fill="#ccc")
                        c.create_text((coord[0] + 3 * coord[2]) / 4,
                                      (coord[1] + coord[3]) / 2,
                                      font=("Ubuntu", "15"),
                                      justify='center',
                                      text="Subject " + str(sbj))
                    else:
                        c.create_rectangle(coord[0],
                                           coord[1], (coord[0] + coord[2]) / 2,
                                           coord[3],
                                           fill="#ccc")
                        halfSlots.append(
                            str(profBook[professor][i][1] - 1) + "," +
                            str(slot))
                        c.create_text((3 * coord[0] + coord[2]) / 4,
                                      (coord[1] + coord[3]) / 2,
                                      font=("Ubuntu", "15"),
                                      justify='center',
                                      text="Subject " + str(sbj))
                else:

                    coord = c.coords(
                        str(profBook[professor][i][1] - 1) + "," + str(slot))
                    coord = [int(i) for i in coord]
                    c.create_rectangle(coord[0],
                                       coord[1],
                                       coord[2],
                                       coord[3],
                                       fill="#ccc")
                    c.create_text((coord[0] + coord[2]) / 2,
                                  (coord[1] + coord[3]) / 2,
                                  font=("Ubuntu", "15"),
                                  justify='center',
                                  text="Subject " + str(sbj))

        c.update()
        c.postscript(file="professor_" + str(professor) + "_schedule.ps",
                     pageheight="29.70c",
                     x="0",
                     y="0",
                     height="1754",
                     width="1240")

    os.system("convert -density 300 *.ps  schedules.pdf")
    os.system("find . -name \*.ps -type f -delete")
Пример #38
0
class SkylineUI(Frame):
    """
    GUI for the skyline game
    """
    def __init__(self, parent, game):
        self.game = game
        self.parent = parent
        Frame.__init__(self, parent)

        self.row, self.col = 0, 0

        self.__initUI()

    def __initUI(self):
        self.parent.title("Skyline")
        self.pack(fill=BOTH, expand=1)
        self.canvas = Canvas(self,
                             width=WIDTH,
                             height=HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)
        clear_button = Button(self,
                              text="Reset",
                              command=self.__clear_answers)
        clear_button.pack(fill=BOTH, side=BOTTOM)

        self.__draw_grid()
        self.__draw_game()

        self.canvas.bind("<Button-1>", self.__cell_clicked)
        self.canvas.bind("<Key>", self.__key_pressed)


    def __draw_grid(self):
        """
        Draws grid divided with blue lines into 3x3 squares
        """
        for i in range(self.game.size + 3):
            color = "blue" if i % 6 == 0 else "gray"
            if i == 1 or i == self.game.size + 1:
                color = "red"

            x0 = MARGIN + i * SIDE
            y0 = MARGIN
            x1 = MARGIN + i * SIDE
            y1 = HEIGHT - MARGIN
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

            x0 = MARGIN
            y0 = MARGIN + i * SIDE
            x1 = WIDTH - MARGIN
            y1 = MARGIN + i * SIDE
            self.canvas.create_line(x0, y0, x1, y1, fill=color)


    def __draw_game(self):
        
        self.canvas.delete("numbers")
        for i in range(0, self.game.size):
            for j in range(0, self.game.size):
                answer = self.game.board[i][j]
                #if answer != 0:
                x = MARGIN + (j+1) * SIDE + SIDE / 2
                y = MARGIN + (i+1) * SIDE + SIDE / 2
                original = self.game.board_object.empty_board[i][j]
                color = "black" if answer == 0 else "sea green"
                self.canvas.create_text(
                    x, y, text=answer, tags="numbers", fill=color
                )
        self.__draw_hints()


    def __clear_answers(self):
        self.game.start()
        self.canvas.delete("victory")
        self.__draw_game()


    def __draw_cursor(self):
        self.canvas.delete("cursor")
        if self.row >= 0 and self.col >= 0:
            x0 = MARGIN + self.col * SIDE + 1
            y0 = MARGIN + self.row * SIDE + 1
            x1 = MARGIN + (self.col + 1) * SIDE - 1
            y1 = MARGIN + (self.row + 1) * SIDE - 1
            self.canvas.create_rectangle(
                x0, y0, x1, y1,
                outline="red", tags="cursor"
            )


    def __cell_clicked(self, event):
        if self.game.hasWon:
            return
        x, y = event.x, event.y
        if (MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN):
            self.canvas.focus_set()

            # get row and col numbers from x,y coordinates
            row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE

            # if cell was selected already - deselect it
            if (row, col) == (self.row, self.col):
                self.row, self.col = -1, -1
            else:
                self.row, self.col = int(row), int(col)
        else:
            self.row, self.col = -1, -1

        self.__draw_cursor()


    def __key_pressed(self, event):
        if self.game.hasWon:
            return
        if self.row >= 0 and self.col >= 0 and event.char in "1234":
            self.game.board[self.row-1][self.col-1] = int(event.char)
            self.col, self.row = -1, -1
            self.__draw_game()
            self.__draw_cursor()
            if self.game.check_game():
                self.__draw_victory()


    def __draw_victory(self):
        # create text
        x = y = MARGIN + 3 * SIDE + SIDE / 2
        self.canvas.create_text(
            x, y,
            text="You win!", tags="victory",
            fill="orange", font=("Arial", 32)
        )


    def __draw_hints(self):

        #draw top hints:
        for i in range(0, self.game.size):
            color = "red"
            hint = self.game.hints_top[i]
            if hint == 0:
                color="white"
            x = SIDE + MARGIN + i * SIDE + SIDE / 2
            y = MARGIN + 0 * SIDE + SIDE / 2

            self.canvas.create_text(
                x, y, text=hint, tags="numbers", fill=color
            )

        #draw bottom hints:
        for i in range(0, self.game.size):
            color = "red"
            hint = self.game.hints_bottom[i]
            if hint == 0:
                color="white"
            x = SIDE + MARGIN + i * SIDE + SIDE / 2
            y = MARGIN + (self.game.size+1) * SIDE + SIDE / 2

            self.canvas.create_text(
                x, y, text=hint, tags="numbers", fill=color
            )     

        #draw left hints:
        for i in range(0, self.game.size):
            color = "red"
            hint = self.game.hints_left[i]
            if hint == 0:
                color="white"
            x =  MARGIN + 0 * SIDE + SIDE / 2
            y = MARGIN + (i+1) * SIDE + SIDE / 2

            self.canvas.create_text(
                x, y, text=hint, tags="numbers", fill=color
            )

        #draw right hints:
        for i in range(0, self.game.size):
            color = "red"
            hint = self.game.hints_right[i]
            if hint == 0:
                color="white"
            x =  MARGIN + (self.game.size+1) * SIDE + SIDE / 2
            y = MARGIN + (i+1) * SIDE + SIDE / 2

            self.canvas.create_text(
                x, y, text=hint, tags="numbers", fill=color
            )
Пример #39
0
class KlicketyGUI:
    """Interface pour le jeu Klickety."""
    def __init__(self):
        # initialisation des structures de données ----------------------------
        self.dim_plateau = (10,                 # nombre de colonnes du plateau
                            16)                 # nombre de lignes du plateau
        self.cote_case = 32          # la longueur du côté d'un bloc à dessiner
        self.largeur_plateau = self.cote_case * self.dim_plateau[0]
        self.hauteur_plateau = self.cote_case * self.dim_plateau[1]
        self.plateau = []
        self.compteur_de_coups = 0

        # initialisation des éléments graphiques ------------------------------
        self.window = Tk()                              # la fenêtre principale
        self.window.resizable(0, 0)           # empêcher les redimensionnements
        self.partie_haut = Frame(self.window, width=self.largeur_plateau,
                                              height=self.hauteur_plateau)
        self.partie_haut.pack(side=TOP)
        self.partie_bas = Frame(self.window)
        self.partie_bas.pack(side=BOTTOM)

        # le canevas affichant le plateau de jeu
        self.plateau_affiche = Canvas(self.partie_haut,
                                      width=self.largeur_plateau,
                                      height=self.hauteur_plateau)
        self.plateau_affiche.pack()
        self.plateau_affiche.bind('<ButtonPress-1>', self.clicPlateau)

        # le bouton "Réinitialiser"
        self.btn = Button(self.partie_bas, text='Réinitialiser',
                          command=self.reinitialiserJeu)
        self.btn.pack(fill=BOTH)

        # Zone d'affichage du nombre de coups
        self.nb_coups_affiche = Canvas(self.partie_bas,
                                       width=self.largeur_plateau, height=32)
        self.nb_coups_affiche.create_text(
            self.largeur_plateau // 2, self.cote_case // 2,
            text="Coups effectués: 0", fill="black"
        )
        self.nb_coups_affiche.pack(fill=BOTH)

        # affichage du nombre de blocs restants
        self.nb_blocs_affiche = Canvas(self.partie_bas,
                                       width=self.largeur_plateau, height=32)
        self.nb_blocs_affiche.pack(fill=BOTH)

        self.reinitialiserJeu()

        self.window.title('Klickety')
        self.window.mainloop()

    def rafraichirNombreBlocs(self, piece=None):
        """Rafraîchit l'affichage du nombre de blocs restants, sur base de la
        pièce que l'on vient de retirer."""
        self.nb_blocs_affiche.delete(ALL)
        if piece is None:  # appel initial, tous les blocs sont encore présents
            self.nb_blocs = self.dim_plateau[0] * self.dim_plateau[1]

        else:  # soustraire du nombre de blocs celui de la pièce retirée
            self.nb_blocs -= len(piece)

        self.nb_blocs_affiche.create_text(
            self.largeur_plateau // 2, self.cote_case // 2,
            text="Blocs restants: " + str(self.nb_blocs), fill="black"
        )

    def compteCoups(self, compteur_de_coups):
        """Compte le nombre de coups effectués durant cette partie."""
        self.nb_coups_affiche.delete(ALL)
        self.nb_coups_affiche.create_text(
            self.largeur_plateau // 2, self.cote_case // 2,
            text="Coups effectués: " + str(compteur_de_coups), fill="black"
        )

    def rafraichirPlateau(self):
        """Redessine le plateau de jeu à afficher."""
        # tracer les blocs
        self.plateau_affiche.delete(ALL)
        couleur_fond = "black"
        for i in range(self.dim_plateau[0]):                    # par défaut 10
            for j in range(self.dim_plateau[1]):                # par défaut 16
                case = self.plateau[i][j]
                if case is not None:  # afficher le pion
                    self.plateau_affiche.create_rectangle(
                        i * self.cote_case, j * self.cote_case,
                        (i + 1) * self.cote_case, (j + 1) * self.cote_case,
                        outline=case, fill=case
                    )
                else:
                    self.plateau_affiche.create_rectangle(
                        i * self.cote_case, j * self.cote_case,
                        (i + 1) * self.cote_case, (j + 1) * self.cote_case,
                        outline=couleur_fond, fill=couleur_fond
                    )

        # tracer le contour des pièces
        # 1) tracer les séparations entre deux pièces adjacentes de
        # couleurs différentes dans la même colonne
        for i in range(0, self.dim_plateau[0]):                 # par défaut 10
            colonne = self.plateau[i]
            for j in range(1, self.dim_plateau[1]):             # par défaut 16
                if colonne[j - 1] != colonne[j]:
                    self.plateau_affiche.create_rectangle(
                        (i) * self.cote_case, j * self.cote_case,
                        (i + 1) * self.cote_case, j * self.cote_case,
                        outline=couleur_fond, fill=couleur_fond, width=1
                    )

        # 2) tracer les séparations entre deux pièces adjacentes de
        # couleurs différentes dans la même ligne
        for i in range(1, self.dim_plateau[0]):                 # par défaut 10
            for j in range(0, self.dim_plateau[1]):             # par défaut 16
                if self.plateau[i - 1][j] != self.plateau[i][j]:
                    self.plateau_affiche.create_rectangle(
                        (i) * self.cote_case, j * self.cote_case,
                        (i) * self.cote_case, (j + 1) * self.cote_case,
                        outline=couleur_fond, fill=couleur_fond, width=1
                    )

    def clicPlateau(self, event):
        """Récupère les coordonnées de la case sélectionnée, et joue le coup
        correspondant s'il est permis."""
        # remarque: le canevas de tkinter interprète (i, j) géométriquement
        # (au lieu de (ligne, colonne)), d'où l'inversion de coordonnées dans
        # la ligne ci-dessous
        (i, j) = (event.x // self.cote_case, event.y // self.cote_case)

        if self.plateau[i][j] is not None:
            piece = set()
            detecterPiece(self.plateau, i, j, piece, self.plateau[i][j])
            #print (piece)

            if len(piece) > 1:  # si la pièce est valide, on la retire
                # retirer la piece en mettant ses cases à None
                for (p, q) in piece:
                    self.plateau[p][q] = None

                # faire descendre les blocs situés au-dessus de la pièce
                mettreAJour(self.plateau, piece)

                # tasser le restant du plateau en supprimant les colonnes vides
                eliminerColonnesVides(self.plateau)

                # rafraîchir le plateau pour répercuter les modifications
                self.rafraichirPlateau()

                self.rafraichirNombreBlocs(piece)
                self.compteur_de_coups += 1
                self.compteCoups(self.compteur_de_coups)
                messagevictoire = partieFinie(self.plateau)
                if messagevictoire:
                    self.plateau_affiche.create_text(
                        int(self.plateau_affiche.cget("width")) // 2,
                        self.cote_case // 2,
                        text=messagevictoire,
                        font=tkinter.font.Font(
                            family="Courier", size=12, weight=tkinter.font.BOLD
                        ),
                        fill="red"
                    )

    def reinitialiserJeu(self):
        """Réinitialise le plateau de jeu et les scores."""
        self.reinitialiserPlateau()
        self.rafraichirNombreBlocs()

        # réinitialiser le nombre de coups
        self.compteur_de_coups = 0
        self.nb_coups_affiche.delete(ALL)
        self.nb_coups_affiche.create_text(self.largeur_plateau // 2, self.cote_case // 2, text="Coups effectués: " + str(self.compteur_de_coups), fill="black")

    def reinitialiserPlateau(self):
        """Réinitialise le plateau de jeu."""
        # réinitialiser la matrice
        self.plateau = initialiserPlateau(*self.dim_plateau)

        # réinitialiser l'affichage
        self.plateau_affiche.delete(ALL)

        if self.plateau:
            self.rafraichirPlateau()
Пример #40
0
class QuickHull(Tk):
	def __init__(self,points):
		Tk.__init__(self)
		board = Frame(self)
		self.title("Diagram") 

		width = 800 #setting height and width
		height = 600

		windowx = self.winfo_screenwidth()
		windowy = self.winfo_screenheight()
		x = (windowx - width)/2		#getting center
		y = (windowy - height)/2

		self.geometry("%dx%d+%d+%d" % (width,height,x,y)) #creates window of size _width by _height, and positions it at the center of the screen

		board.pack(fill=BOTH, expand=1)
	
		self.canvas = Canvas(board,height=600,width=800,background="white")
		self.canvas.place(x=0,y=0)
		
		self.drawPoints(points) #Draw points and the first line from the highest an lowest points
		

					

		
		def point(event):  #Add points by clicking on the screen
			self.canvas.create_text(event.x, event.y,text = "+")
			points.append([event.x,event.y])

		def start():
			if(points != []):
				startB.destroy()
				quickHullStart(points)
				self.nextButton()
	
		self.canvas.bind("<Button-1>", point)
		
		startB = Button(self, text = "Start QuickHull", command = start)
		startB.pack()
	
		
	
		self.mainloop()
	
				
	def nextButton(self):					#Button that steps forward one step in the QuickHull
		def callBack():
			self.animate()

		continueB = Button(self, text="-->",command=callBack)
		continueB.place(x=350,y=550)


	def animate(self):						#animation loop
		if(triList == []):
			self.onExit()
			return
		self.canvas.create_polygon(triList.pop(0),fill="red",outline="black")
			





	def onExit(self):  #Window popup signaling that the Quick Hull is complete
		alert = Tk()
		finish = Window(alert)
		finish.config(title="Complete",w = 200, h=50)
		finish.positionWindow()

		done = Label(alert,text="QuickHull Complete")
		done.pack()

		ok = Button(alert,text="OK",command=alert.destroy)
		ok.pack()
		alert.mainloop()
		return
		


	def drawPoints(self,points):			#Draw points Imported from a file
		for p in points:
			self.canvas.create_text(p[0],p[1],text="+")
Пример #41
0
class GraphView(View):
	WIN_PADDING_Y = 16
	POINT_MARGIN = 2

	def __init__(self, params):
		super(GraphView, self).__init__(params)

		self._ids = params["ids"] if "ids" in params else ""
		self._ids = [int(i) for i in self._ids.split(' ')]
		self._labels = params["labels"] if "labels" in params else ""
		self._labels = [l for l in self._labels.split(' ')]
		self._colors = [c for c in params["colors"].split(' ')] if "colors" in \
				params else None
		if not self._colors:
			self._colors = self._get_auto_colors(len(self._ids))
		if not len(self._ids) == len(self._labels) == len(self._colors):
			raise RuntimeError("ids, labels and colors must share the same size")

		self._min = float(params["min"]) if "min" in params else -1000
		self._max = float(params["max"]) if "max" in params else 1000
		if self._min > self._max:
			self._min, self._max = self._max, self._min
		self._diff = abs(self._max - self._min)

		self._data = [_GraphData() for _ in range(len(self._ids))]
		self._data_view = [_GraphDataView(self._colors[i]) for i in range(
				len(self._ids))]
		self._graph_x = 0

		self._tk = Tk()
		self._tk.title("Graph view %s" % str(self._labels))

		self._canvas = Canvas(self._tk, width = 640, height = 480)
		self._canvas.pack(fill = tkinter.BOTH, expand = 1)

		self._tk.update()
		self._win_size = self._tk.winfo_width(), self._tk.winfo_height()
		# graph_rect only works as providing the area but not coord
		self._graph_rect = self._win_size
		self._tk.minsize(320, 240)
		self._tk.protocol("WM_DELETE_WINDOW", self.on_press_close)

		self._tk.bind("<Configure>", self.on_config)
		self._canvas.config(background = config.COL_GREY_900)

		self._full_redraw()

		self._file = open("graph_%s_%i.csv" % (str(self._labels),
				int(time.time() * 1000)), "w")
		self._file.write(','.join(self._labels) + '\n')

		self._tk.after(16, self._refresh)

	def run(self):
		super(GraphView, self).run()
		self._tk.mainloop()

	def on_new_input(self):
		try:
			hex_data = binascii.unhexlify(self.get_input())
		except TypeError as e:
			logging.debug(str(e))
			return

		count = int(len(hex_data) / GraphView._MSG_SIZE)
		for i in (x * 6 for x in range(count)):
			if hex_data[i] in self._ids:
				value_type = hex_data[i + 1]
				value_bytes = hex_data[i + 2:i + 6]
				if value_type == GraphView._MSG_TYPE_INT:
					value = int.from_bytes(value_bytes, byteorder = "big",
							signed = True)
				elif value_type == GraphView._MSG_TYPE_FLOAT:
					value = struct.unpack(">f", value_bytes)[0]
				else:
					logging.error("Unknown type: " + str(value_type))
					continue
				self._tk.after_idle(self._put_value, hex_data[i], value)

	def on_dismiss(self):
		self._tk.after_idle(self.on_press_close)

	def on_press_close(self):
		self._tk.destroy()
		self.join_io_thread()

	def on_config(self, event):
		win_size = (event.width, event.height)
		if win_size != self._win_size:
			self._win_size = win_size
			self._full_redraw()

	def is_test_input(self):
		return False

	def gen_test_input(self):
		while True:
			for i in range(int(self._min), int(self._max)):
				sleep(0.1)
				yield "0000%08x" % (random.randrange(-100, 100) & 0xFFFFFFFF) \
						+ "0100%08x\n" % (i & 0xFFFFFFFF)

	def _put_value(self, id, value):
		pos = self._ids.index(id)
		if self._data[pos].size() == 0:
			for d in self._data:
				d.append()
		elif self._data[pos].get_value(-1) is not None:
			for d in self._data:
				d.append()
			if self._data[pos].size() > 1:
				self._write_prev_records()
		self._data[pos].put_value(value)

		graph_w = self._win_size[0] - self._graph_x;
		count = int(graph_w / GraphView.POINT_MARGIN + 1)

		for d in self._data:
			d.shrink(count)

	def _write_prev_records(self):
		write = ','.join((str(d.get_value(-2)) for d in self._data)) + '\n'
		self._file.write(write)
		self._file.flush()

	def _refresh(self):
		self._redraw_graph()
		self._tk.after(16, self._refresh)

	def _full_redraw(self):
		self._canvas.delete("all")
		bounding_box = self._redraw_data_labels()
		self._graph_rect = 0, 0, self._win_size[0], bounding_box[1]
		self._redraw_y_labels()
		for v in self._data_view:
			v.clear_lines();
		self._redraw_graph()

	def _redraw_data_labels(self):
		top = self._win_size[1]
		x = GraphView._DATA_LABEL_PADDING
		for l, c in zip(self._labels, self._colors):
			t = self._canvas.create_text(x,
					self._win_size[1] - GraphView._DATA_LABEL_PADDING,
					anchor = tkinter.SW, fill = c, font = config.FONT,
					text = '-' + l)
			bounding_box = self._canvas.bbox(t)
			top = min(top, bounding_box[1])
			x = bounding_box[2] + GraphView._DATA_LABEL_PADDING
		return 0, top, x, self._win_size[1]

	def _redraw_y_labels(self):
		height = self._graph_rect[3] - self._graph_rect[1] \
				- GraphView.WIN_PADDING_Y * 2
		count = max(int(height / 50), 2)

		labels = []
		max_label_size = 0
		longest_label = None
		longest_label_i = None
		for i in range(count):
			ratio = i / (count - 1)
			value = self._max - self._diff * ratio
			value_label = ("%.2f" % value) if value % 1 != 0 else str(value)
			labels.append(value_label)
			if len(value_label) > max_label_size:
				max_label_size = len(value_label)
				longest_label = value_label
				longest_label_i = i

		label_id = self._canvas.create_text(0, height * (longest_label_i \
						/ (count - 1)) + GraphView.WIN_PADDING_Y,
				anchor = tkinter.W, fill = config.COL_GREY_100,
				font = config.FONT, text = longest_label)
		bounding_box = self._canvas.bbox(label_id)
		width = bounding_box[2] - bounding_box[0]
		self._graph_x = width + GraphView.POINT_MARGIN

		for i in range(count):
			ratio = i / (count - 1)
			y = height * ratio + GraphView.WIN_PADDING_Y
			if i != longest_label_i:
				self._canvas.create_text(width, y, anchor = tkinter.E,
						fill = config.COL_GREY_100, font = config.FONT,
						text = labels[i])
			self._canvas.create_line(self._graph_x, y, self._graph_rect[2], y,
					fill = config.COL_GREY_700)

	def _redraw_graph(self):
		graph_h = self._graph_rect[3] - GraphView.WIN_PADDING_Y * 2
		for d, v in zip(self._data, self._data_view):
			v.populate(d.get_values(), self._max, self._diff, self._graph_x,
					graph_h)
			v.draw(self._canvas)

	def _get_auto_colors(self, size) -> list:
		product = GraphView._COLOR_REPO[:min(size, len(GraphView._COLOR_REPO))]
		while len(product) < size:
			product.append("#%06x" % random.randrange(0xFFFFFF))
		return product

	_LABEL_SIZE = 10
	_DATA_LABEL_PADDING = 8
	_MSG_SIZE = 6
	_MSG_TYPE_INT = 0
	_MSG_TYPE_FLOAT = 1
	_COLOR_REPO = ["#F44336", "#4CAF50", "#2196F3", "#FFEB3B", "#607D8B",
			"#9C27B0", "#009688", "#673AB7", "#795548"]
Пример #42
0
from tkinter import Canvas, Tk
from re import split

bgColor = 'white'
main = Tk()
c = Canvas(width=1000, height=200, bg=bgColor)
c.pack()

linka = 'linka3.txt'
with open(linka, 'r') as f:
    color = split('\n', f.readline())[0]
    x = 10
    for line in f:
        line = split('\n', line)[0]
        if x == 10:
            c.create_rectangle(x, 170, x + 10, 180, fill=color)
        elif line[0] != '*':
            c.create_oval(x, 170, x + 10, 180, fill=color)
        else:
            c.create_oval(x, 170, x + 10, 180, outline=color)
        c.create_line(x + 10, 175, x + 20, 175, fill=color)
        c.create_text(x + 10, 170, angle=45, anchor='sw', text=line, font=('Arial',8))
        x += 20
    c.create_rectangle(x - 20, 170, x - 10, 180, fill=color)
    c.create_line(x - 10, 175, x, 175, fill=bgColor)

main.mainloop()
Пример #43
0
def Classes(sbjBook, string):

    from tkinter import Tk
    from tkinter import Canvas
    import os

    master = Tk()

    w = 1240
    h = 1754
    m = 120

    c = Canvas(master, width=1240, height=1754)
    c.pack()

    c.create_rectangle(0, 0, w, h, fill="#fff", outline="#fff")

    c.create_rectangle(m, 60, w - m, 180, fill="#9bbb59", outline="#cadba6")
    c.create_text(m + 60,
                  90,
                  fill="#fff",
                  font=("Ubuntu", "12", "bold"),
                  text="SUBJECT")
    c.create_text(m + 170,
                  90,
                  fill="#fff",
                  font=("Ubuntu", "12", "bold"),
                  text="CLASS")
    c.create_text(m + 420,
                  90,
                  fill="#fff",
                  font=("Ubuntu", "12", "bold"),
                  text="SCHEDULE")
    c.create_text(m + 720,
                  90,
                  fill="#fff",
                  font=("Ubuntu", "12", "bold"),
                  text="PROFESSOR")
    c.create_text(m + 920,
                  90,
                  fill="#fff",
                  font=("Ubuntu", "12", "bold"),
                  text="OFFERED AS")

    for i in range(13):
        c.create_rectangle(m,
                           m + 120 * i,
                           w - m,
                           m + 120 * i + 60,
                           fill="#ebf1de",
                           outline="#cadba6")
        c.create_rectangle(m,
                           m + 120 * i + 60,
                           w - m,
                           m + 120 * i + 120,
                           fill="#fff",
                           outline="#cadba6")

    count = -1
    page = 0
    for i in sbjBook:
        if (i == -1):
            pass
        else:
            classroom = -1
            sameSche = [[], [], []]
            scheRecord = [[], [], []]
            for j in range(len(sbjBook[i])):
                classroom += 1
                count += 1
                period = sbjBook[i][j][1] - 1
                hpw = sbjBook[i][j][2]
                professor = sbjBook[i][j][3]
                group = sbjBook[i][j][4]
                if (group == None):
                    group = 'Elective'
                else:
                    course_id = int(group / 5)
                    b26 = ''
                    d = int(1)
                    while (d < course_id):
                        d = int(d * 26)
                    if (d >= 26): d = int(d / 26)
                    else: pass
                    while (d >= 1):
                        b26 = b26 + chr(int(course_id / d) + ord('A'))
                        course_id = course_id % d
                        d = d / 26
                    group = str(group + 1
                                ) + '-Year required subject\nfor course ' + b26
                sche = sbjBook[i][j][5:]

                if (sche in scheRecord[period]):
                    class_id = scheRecord[period].index(sche)
                    class_idBK = scheRecord[period].index(sche)
                    sameSche[period][class_id][0] += 1
                else:
                    scheRecord[period].append(sche)
                    sameSche[period].append([0])
                    class_id = scheRecord[period].index(sche)
                    class_idBK = scheRecord[period].index(sche)

                schedule = ""
                for k in sche:
                    if (schedule == ""): pass
                    else: schedule = schedule + "\n"

                    weekday = int((k + 1) / 2) + (k + 1) % 2
                    if (weekday == 1): weekday = 'Monday '
                    elif (weekday == 2): weekday = 'Tuesday '
                    elif (weekday == 3): weekday = 'Wednesday '
                    elif (weekday == 4): weekday = 'Thursday '
                    else: weekday = 'Friday '

                    if (k % 2 == 0 and period == 0):
                        hour = "from 8:00 am to 10:00 am"
                    elif (k % 2 == 0 and period == 1):
                        hour = "from 2:00 pm to 4:00 pm"
                    elif (k % 2 == 0 and period == 2):
                        hour = "from 7:00 pm to 9:00 pm"
                    elif (k % 2 == 1 and period == 0):
                        hour = "from 10:00 am to 12:00 pm"
                    elif (k % 2 == 1 and period == 1):
                        hour = "from 4:00 pm to 6:00 pm"
                    elif (k % 2 == 1 and period == 2):
                        hour = "from 9:00 pm to 11:00 pm"

                    schedule = schedule + weekday + hour

                b26 = ''
                div = int(1)
                while (div < class_id):
                    div = int(div * 26)
                if (div >= 26): div = int(div / 26)
                else: pass
                while (div >= 1):
                    b26 = b26 + chr(int(class_id / div) + ord('A'))
                    class_id = class_id % div
                    div = div / 26

                if (period == 0): periodTX = " - morning"
                elif (period == 1): periodTX = " - afternoon"
                else: periodTX = " - evening"

                if (count <= 25): pass
                else:
                    c.update()
                    c.postscript(file="classes-" + str(page) + ".ps",
                                 pageheight="29.70c",
                                 x="0",
                                 y="0",
                                 height="1754",
                                 width="1240")
                    c.delete("lines")
                    count = 0
                    page += 1

                c.create_text(m + 60,
                              150 + 60 * count,
                              fill="#000",
                              font=("Ubuntu", "10"),
                              text=i,
                              tags="lines")  # Subject
                c.create_text(m + 170,
                              150 + 60 * count,
                              fill="#000",
                              font=("Ubuntu", "10"),
                              text=b26 +
                              str(sameSche[period][class_idBK][0] + 1) +
                              periodTX,
                              tags="lines")  # Class
                c.create_text(m + 420,
                              150 + 60 * count,
                              fill="#000",
                              font=("Ubuntu", "10"),
                              text=schedule,
                              tags="lines")  # Schedule
                c.create_text(m + 720,
                              150 + 60 * count,
                              fill="#000",
                              font=("Ubuntu", "10"),
                              text=professor,
                              tags="lines")  # Professor
                c.create_text(m + 920,
                              150 + 60 * count,
                              fill="#000",
                              font=("Ubuntu", "10"),
                              justify='center',
                              text=group,
                              tags="lines")  # Group

    c.update()
    c.postscript(file=string + "-" + str(page) + ".ps",
                 pageheight="29.70c",
                 x="0",
                 y="0",
                 height="1754",
                 width="1240")

    #Concatenate PS files and output a single PDF, then clear PS files
    os.system("convert -density 300 *.ps  " + string + ".pdf")
    os.system("find . -name \*.ps -type f -delete")
Пример #44
0
class DrawingEngine(Screen):
    def __init__(self, window):
        super().__init__(window, "gameEngine")
        os.environ['SDL_WINDOWID'] = str(self.f.winfo_id())
        if platform.system() == "Windows":
            os.environ['SDL_VIDEODRIVER'] = 'windib'
            self.usePygame = True
            self.display = pygame.display.set_mode(
                (self.window.width, self.window.height))
            self.display.fill((255, 255, 255))
            pygame.display.init()
            pygame.font.init()
        else:
            self.usePygame = False
            self.canvas = Canvas(self.window.root,
                                 bg="white",
                                 width=self.window.width,
                                 height=self.window.height)
            self.canvas.pack(in_=self.f)
        self.tkImageList = [
        ]  #images must maintain a reference in order to appear on the canvas

        self.arenaSize = 1000
        self.mapSize = self.window.width * .2
        self.mapScale = .1
        self.mapX = self.window.width - self.mapSize / 2
        self.mapY = self.window.height - self.mapSize / 2
        self.wallWidth = 50
        self.circleDisplayList = []
        self.playerDisplayList = []
        self.player = PlayerDisplay(self.window, 0, 0, 10, 100, [], "name",
                                    "00.00.00")

        self.scale = self.window.width / 1280 / 1.5
        self.screenX = self.window.width / 2 / self.scale
        self.screenY = self.window.height / 2 / self.scale

    def render(self):
        largestDistance = 0
        for player in self.playerDisplayList:
            distance = math.sqrt((self.player.x - player.x)**2 +
                                 (self.player.y - player.y)**2)
            distance *= 16 / 9 * 2
            if distance > largestDistance:
                largestDistance = distance
        #if largestDistance >= 1280:
        #    self.scale = self.window.width / largestDistance
        #else:
        #    self.scale = self.window.width / 1280

        self.screenX = self.window.width / 2 / self.scale
        self.screenY = self.window.height / 2 / self.scale

        self.window.frameRate.startTimer("clear")
        if self.usePygame:
            self.display.fill((121, 202, 249))
        else:
            self.canvas.delete("all")
            self.canvas.create_rectangle(0,
                                         0,
                                         self.window.width,
                                         self.window.height,
                                         fill="#%02x%02x%02x" %
                                         (121, 202, 249))
            self.tkImageList.clear()
        self.window.frameRate.timeChange()

        self.showWalls()

        self.showCircles()

        self.showPlayer()

        self.showEnemies()

        self.showBullets()

        self.showGUI()

        self.window.frameRate.startTimer("update")
        if self.usePygame:
            pygame.display.update()
            self.window.root.update(
            )  #must update while in canvas in pygame but not in tkinter
        else:
            self.canvas.update()
        self.window.frameRate.timeChange()

    def showWalls(self):
        x1 = self.getScreenX(self.arenaSize + self.wallWidth / 2)
        y1 = self.getScreenY(self.arenaSize + self.wallWidth)
        x2 = self.getScreenX(self.arenaSize + self.wallWidth / 2)
        y2 = self.getScreenY(-self.arenaSize - self.wallWidth)
        self.showLine((x1, y1), (x2, y2), (0, 0, 0),
                      self.wallWidth * self.scale)

        x1 = self.getScreenX(self.arenaSize + self.wallWidth)
        y1 = self.getScreenY(-self.arenaSize - self.wallWidth / 2)
        x2 = self.getScreenX(-self.arenaSize - self.wallWidth)
        y2 = self.getScreenY(-self.arenaSize - self.wallWidth / 2)
        self.showLine((x1, y1), (x2, y2), (0, 0, 0),
                      self.wallWidth * self.scale)

        x1 = self.getScreenX(-self.arenaSize - self.wallWidth / 2)
        y1 = self.getScreenY(-self.arenaSize - self.wallWidth)
        x2 = self.getScreenX(-self.arenaSize - self.wallWidth / 2)
        y2 = self.getScreenY(self.arenaSize + self.wallWidth)
        self.showLine((x1, y1), (x2, y2), (0, 0, 0),
                      self.wallWidth * self.scale)

        x1 = self.getScreenX(-self.arenaSize - self.wallWidth)
        y1 = self.getScreenY(self.arenaSize + self.wallWidth / 2)
        x2 = self.getScreenX(self.arenaSize + self.wallWidth)
        y2 = self.getScreenY(self.arenaSize + self.wallWidth / 2)
        self.showLine((x1, y1), (x2, y2), (0, 0, 0),
                      self.wallWidth * self.scale)

    def showPlayer(self):
        self.showCircle(
            self.player.radius * self.scale,
            (self.getScreenX(self.player.x), self.getScreenY(self.player.y)),
            (0, 0, 255))
        healthWidth = 100
        healthHeight = 15
        healthOffset = self.player.radius + 15
        self.showRectangle(
            self.getScreenX(self.player.x - healthWidth / 2),
            self.getScreenY(self.player.y + healthOffset - healthHeight / 2),
            self.getScreenX(self.player.x + healthWidth / 2),
            self.getScreenY(self.player.y + healthOffset + healthHeight / 2),
            (0, 255, 0),
            width=1)
        healthPercent = 1 - self.player.health / self.player.maxHealth
        self.showRectangle(
            self.getScreenX(self.player.x + healthWidth / 2 -
                            healthPercent * healthWidth),
            self.getScreenY(self.player.y - healthHeight / 2 + healthOffset),
            self.getScreenX(self.player.x + healthWidth / 2),
            self.getScreenY(self.player.y + healthHeight / 2 + healthOffset),
            (255, 0, 0),
            width=1)

    def showBullets(self):
        for bullet in self.player.bulletDisplayList:
            self.showCircle(
                bullet.radius * self.scale,
                (self.getScreenX(bullet.x), self.getScreenY(bullet.y)),
                (0, 0, 255))
        for player in self.playerDisplayList:
            for bullet in player.bulletDisplayList:
                self.showCircle(
                    bullet.radius * self.scale,
                    (self.getScreenX(bullet.x), self.getScreenY(bullet.y)),
                    (255, 0, 0))

    def showEnemies(self):
        for player in self.playerDisplayList:
            self.showCircle(
                player.radius * self.scale,
                (self.getScreenX(player.x), self.getScreenY(player.y)),
                (255, 0, 0))
            healthWidth = 100
            healthHeight = 15
            healthOffset = player.radius + 15
            self.showRectangle(
                self.getScreenX(player.x - healthWidth / 2),
                self.getScreenY(player.y + healthOffset - healthHeight / 2),
                self.getScreenX(player.x + healthWidth / 2),
                self.getScreenY(player.y + healthOffset + healthHeight / 2),
                (0, 255, 0),
                width=1)
            healthPercent = 1 - player.health / player.maxHealth
            self.showRectangle(
                self.getScreenX(player.x + healthWidth / 2 -
                                healthPercent * healthWidth),
                self.getScreenY(player.y - healthHeight / 2 + healthOffset),
                self.getScreenX(player.x + healthWidth / 2),
                self.getScreenY(player.y + healthHeight / 2 + healthOffset),
                (255, 0, 0),
                width=1)
            self.showText(
                player.name,
                (self.getScreenX(player.x),
                 self.getScreenY(player.y + healthOffset + healthHeight +
                                 25 * self.scale / 2)), (255, 0, 0),
                fontSize=int(25 * self.scale),
                bold=True,
                anchorCenter=True,
                outlineWidth=2)

    def showGUI(self):
        self.showRectangle(self.window.width - self.mapSize,
                           self.window.height - self.mapSize,
                           self.window.width, self.window.height,
                           (121, 202, 249), 5)
        self.showCircle(
            self.player.radius * self.mapScale,
            (self.getMiniMapX(self.player.x), self.getMiniMapY(self.player.y)),
            (0, 0, 255))

        for circle in self.circleDisplayList:
            x = self.getMiniMapX(circle.x)
            y = self.getMiniMapY(circle.y)
            radius = circle.radius * self.mapScale
            if self.isInMiniMap(x, y, radius):
                self.showCircle(radius, (x, y), circle.color)

        for player in self.playerDisplayList:
            x = self.getMiniMapX(player.x)
            y = self.getMiniMapY(player.y)
            radius = player.radius * self.mapScale
            if self.isInMiniMap(x, y, radius):
                self.showCircle(radius, (x, y), (255, 0, 0))

        x1 = self.getMiniMapX(self.arenaSize + self.wallWidth / 2)
        y1 = self.getMiniMapY(self.arenaSize + self.wallWidth / 2)
        x2 = self.getMiniMapX(self.arenaSize + self.wallWidth / 2)
        y2 = self.getMiniMapY(-self.arenaSize - self.wallWidth / 2)
        if x1 < self.mapX - self.mapSize / 2:
            x1 += self.mapX - self.mapSize / 2 - x1
        if x1 > self.mapX + self.mapSize / 2:
            x1 += self.mapX + self.mapSize / 2 - x1
        if y1 < self.mapY - self.mapSize / 2:
            y1 += self.mapY - self.mapSize / 2 - y1
        if y1 > self.mapY + self.mapSize / 2:
            y1 += self.mapY + self.mapSize / 2 - y1
        if x2 < self.mapX - self.mapSize / 2:
            x2 += self.mapX - self.mapSize / 2 - x2
        if x2 > self.mapX + self.mapSize / 2:
            x2 += self.mapX + self.mapSize / 2 - x2
        if y2 < self.mapY - self.mapSize / 2:
            y2 += self.mapY - self.mapSize / 2 - y2
        if y2 > self.mapY + self.mapSize / 2:
            y2 += self.mapY + self.mapSize / 2 - y2
        self.showLine((x1, y1), (x2, y2), (0, 0, 0),
                      self.wallWidth * self.mapScale)

        x1 = self.getMiniMapX(self.arenaSize + self.wallWidth / 2)
        y1 = self.getMiniMapY(-self.arenaSize - self.wallWidth / 2)
        x2 = self.getMiniMapX(-self.arenaSize - self.wallWidth / 2)
        y2 = self.getMiniMapY(-self.arenaSize - self.wallWidth / 2)
        if x1 < self.mapX - self.mapSize / 2:
            x1 += self.mapX - self.mapSize / 2 - x1
        if x1 > self.mapX + self.mapSize / 2:
            x1 += self.mapX + self.mapSize / 2 - x1
        if y1 < self.mapY - self.mapSize / 2:
            y1 += self.mapY - self.mapSize / 2 - y1
        if y1 > self.mapY + self.mapSize / 2:
            y1 += self.mapY + self.mapSize / 2 - y1
        if x2 < self.mapX - self.mapSize / 2:
            x2 += self.mapX - self.mapSize / 2 - x2
        if x2 > self.mapX + self.mapSize / 2:
            x2 += self.mapX + self.mapSize / 2 - x2
        if y2 < self.mapY - self.mapSize / 2:
            y2 += self.mapY - self.mapSize / 2 - y2
        if y2 > self.mapY + self.mapSize / 2:
            y2 += self.mapY + self.mapSize / 2 - y2
        self.showLine((x1, y1), (x2, y2), (0, 0, 0),
                      self.wallWidth * self.mapScale)

        x1 = self.getMiniMapX(-self.arenaSize - self.wallWidth / 2)
        y1 = self.getMiniMapY(-self.arenaSize - self.wallWidth / 2)
        x2 = self.getMiniMapX(-self.arenaSize - self.wallWidth / 2)
        y2 = self.getMiniMapY(self.arenaSize + self.wallWidth / 2)
        if x1 < self.mapX - self.mapSize / 2:
            x1 += self.mapX - self.mapSize / 2 - x1
        if x1 > self.mapX + self.mapSize / 2:
            x1 += self.mapX + self.mapSize / 2 - x1
        if y1 < self.mapY - self.mapSize / 2:
            y1 += self.mapY - self.mapSize / 2 - y1
        if y1 > self.mapY + self.mapSize / 2:
            y1 += self.mapY + self.mapSize / 2 - y1
        if x2 < self.mapX - self.mapSize / 2:
            x2 += self.mapX - self.mapSize / 2 - x2
        if x2 > self.mapX + self.mapSize / 2:
            x2 += self.mapX + self.mapSize / 2 - x2
        if y2 < self.mapY - self.mapSize / 2:
            y2 += self.mapY - self.mapSize / 2 - y2
        if y2 > self.mapY + self.mapSize / 2:
            y2 += self.mapY + self.mapSize / 2 - y2
        self.showLine((x1, y1), (x2, y2), (0, 0, 0),
                      self.wallWidth * self.mapScale)

        x1 = self.getMiniMapX(-self.arenaSize - self.wallWidth / 2)
        y1 = self.getMiniMapY(self.arenaSize + self.wallWidth / 2)
        x2 = self.getMiniMapX(self.arenaSize + self.wallWidth / 2)
        y2 = self.getMiniMapY(self.arenaSize + self.wallWidth / 2)
        if x1 < self.mapX - self.mapSize / 2:
            x1 += self.mapX - self.mapSize / 2 - x1
        if x1 > self.mapX + self.mapSize / 2:
            x1 += self.mapX + self.mapSize / 2 - x1
        if y1 < self.mapY - self.mapSize / 2:
            y1 += self.mapY - self.mapSize / 2 - y1
        if y1 > self.mapY + self.mapSize / 2:
            y1 += self.mapY + self.mapSize / 2 - y1
        if x2 < self.mapX - self.mapSize / 2:
            x2 += self.mapX - self.mapSize / 2 - x2
        if x2 > self.mapX + self.mapSize / 2:
            x2 += self.mapX + self.mapSize / 2 - x2
        if y2 < self.mapY - self.mapSize / 2:
            y2 += self.mapY - self.mapSize / 2 - y2
        if y2 > self.mapY + self.mapSize / 2:
            y2 += self.mapY + self.mapSize / 2 - y2
        self.showLine((x1, y1), (x2, y2), (0, 0, 0),
                      self.wallWidth * self.mapScale)

    def showCircles(self):
        for circle in self.circleDisplayList:
            self.showCircle(
                circle.radius * self.scale,
                (self.getScreenX(circle.x), self.getScreenY(circle.y)),
                circle.color)

    def showRectangle(self, x1, y1, x2, y2, color, width=0):
        if self.usePygame:
            pygame.draw.rect(self.display, color,
                             ((x1, y1), (x2 - x1, y2 - y1)))
            if width != 0:
                pygame.draw.rect(self.display, (0, 0, 0),
                                 ((x1, y1), (x2 - x1, y2 - y1)), width)
        else:
            tk_rgb = "#%02x%02x%02x" % color
            self.canvas.create_rectangle(x1,
                                         y1,
                                         x2,
                                         y2,
                                         fill=tk_rgb,
                                         width=width)

    def showLine(self, position1, position2, color, width):
        if self.usePygame:
            pygame.draw.line(self.display, color,
                             (int(position1[0]), int(position1[1])),
                             (int(position2[0]), int(position2[1])),
                             int(width))
        else:
            tk_rgb = "#%02x%02x%02x" % color
            self.canvas.create_line(position1[0],
                                    position1[1],
                                    position2[0],
                                    position2[1],
                                    fill=tk_rgb,
                                    width=width)

    def showText(self,
                 text,
                 position,
                 color,
                 fontName="Times",
                 fontSize=12,
                 bold=False,
                 italic=False,
                 anchorCenter=False,
                 shadowWidth=0,
                 secondaryColor=(0, 0, 0),
                 outlineWidth=0):
        if self.usePygame:
            if outlineWidth != 0:
                font = pygame.font.SysFont(fontName, fontSize, bold, italic)
                screenText = font.render(text, 1, secondaryColor)
                if anchorCenter:
                    textW = screenText.get_width()
                    textH = screenText.get_height()
                else:
                    textW = 0
                    textH = 0

                for angle in range(0, 361,
                                   int(8 / math.sqrt(outlineWidth)) + 1):
                    x = outlineWidth * math.sin(angle)
                    y = outlineWidth * math.cos(angle)
                    self.display.blit(screenText,
                                      (int(position[0] - textW / 2) + x,
                                       int(position[1] - textH / 2) + y))
            elif shadowWidth != 0:
                font = pygame.font.SysFont(fontName, fontSize, bold, italic)
                screenText = font.render(text, 1, secondaryColor)
                if anchorCenter:
                    textW = screenText.get_width()
                    textH = screenText.get_height()
                else:
                    textW = 0
                    textH = 0
                for shift in range(shadowWidth):
                    self.display.blit(screenText,
                                      (int(position[0] - textW / 2) + shift,
                                       int(position[1] - textH / 2)))
            font = pygame.font.SysFont(fontName, fontSize, bold, italic)
            screenText = font.render(text, 1, color)
            if anchorCenter:
                textW = screenText.get_width()
                textH = screenText.get_height()
            else:
                textW = 0
                textH = 0
            self.display.blit(
                screenText,
                (int(position[0] - textW / 2), int(position[1] - textH / 2)))

        else:
            tk_rgb = "#%02x%02x%02x" % color
            fontString = fontName + " " + str(fontSize)
            if bold:
                fontString += " bold"
            if italic:
                fontString += " italic"
            if anchorCenter:
                if outlineWidth != 0:
                    secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor
                    for angle in range(0, 361,
                                       int(8 / math.sqrt(outlineWidth)) + 1):
                        x = outlineWidth * math.sin(angle)
                        y = outlineWidth * math.cos(angle)
                        self.canvas.create_text(position[0] + x,
                                                position[1] + y,
                                                fill=secondary_tk_rgb,
                                                font=fontString,
                                                text=text)
                elif shadowWidth != 0:
                    secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor
                    for shift in range(shadowWidth):
                        self.canvas.create_text(position[0] + shift,
                                                position[1],
                                                fill=secondary_tk_rgb,
                                                font=fontString,
                                                text=text)
                self.canvas.create_text(position[0],
                                        position[1],
                                        fill=tk_rgb,
                                        font=fontString,
                                        text=text)
            else:
                if outlineWidth != 0:
                    secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor
                    for angle in range(0, 361,
                                       int(8 / math.sqrt(outlineWidth)) + 1):
                        x = outlineWidth * math.sin(angle)
                        y = outlineWidth * math.cos(angle)
                        self.canvas.create_text(position[0] + x,
                                                position[1] + y,
                                                fill=secondary_tk_rgb,
                                                font=fontString,
                                                text=text,
                                                anchor=NW)
                elif shadowWidth != 0:
                    secondary_tk_rgb = "#%02x%02x%02x" % secondaryColor
                    for shift in range(shadowWidth):
                        self.canvas.create_text(position[0] + shift,
                                                position[1],
                                                fill=secondary_tk_rgb,
                                                font=fontString,
                                                text=text,
                                                anchor=NW)
                self.canvas.create_text(position[0],
                                        position[1],
                                        fill=tk_rgb,
                                        font=fontString,
                                        text=text,
                                        anchor=NW)

    def showImage(self, image, position, anchorCenter=False):
        if self.usePygame:
            if anchorCenter:
                imageW = image.get_width()
                imageH = image.get_height()
            else:
                imageW = 0
                imageH = 0
            self.display.blit(
                image,
                (int(position[0] - imageW / 2), int(position[1] - imageH / 2)))
        else:
            image = ImageTk.PhotoImage(image)
            self.tkImageList.append(image)
            if not anchorCenter:
                imageW = image.width()
                imageH = image.height()
            else:
                imageW = 0
                imageH = 0
            self.canvas.create_image(
                (position[0] + imageW / 2, position[1] + imageH / 2),
                image=image)

    def showPolygon(self, pointList, color, position=(0, 0)):
        points = []
        for index in range(len(pointList)):
            points.append((pointList[index][0] + position[0],
                           pointList[index][1] + position[1]))
        if self.usePygame:
            pygame.draw.polygon(self.display, color, points)
            pygame.draw.polygon(self.display, (0, 0, 0), points, 2)
        else:
            tk_rgb = "#%02x%02x%02x" % color
            self.canvas.create_polygon(points,
                                       outline='black',
                                       fill=tk_rgb,
                                       width=2)

    def showCircle(self, radius, position, color):
        try:
            if self.usePygame:
                pygame.draw.circle(self.display, color,
                                   (int(position[0]), int(position[1])),
                                   int(radius))
                pygame.draw.circle(self.display, (0, 0, 0),
                                   (int(position[0]), int(position[1])),
                                   int(radius), 2)
            else:
                tk_rgb = "#%02x%02x%02x" % color
                self.canvas.create_oval(position[0] - radius,
                                        position[1] - radius,
                                        position[0] + radius,
                                        position[1] + radius,
                                        fill=tk_rgb)
        except ValueError:
            pass

    def update(self):
        self.f.config(width=self.window.width, height=self.window.width)
        if self.usePygame:
            self.diplay = pygame.display.set_mode(
                (self.window.width, self.window.height))
        else:
            self.canvas.config(width=self.window.width,
                               height=self.window.height)

    def scaleImage(self, image, scale):
        newWidth = image.size[0] * scale
        wPercent = (newWidth / float(image.size[0]))
        hSize = int((float(image.size[1]) * float(wPercent)))
        scaledImage = image.resize((int(newWidth), int(hSize)),
                                   PIL.Image.ANTIALIAS)
        return scaledImage

    def rotate(self, image, angle):
        if self.usePygame:
            return pygame.transform.rotate(image, angle)
        else:
            return self.rotatePIL(image, angle)

    def rotatePIL(self, image, angle):
        startSize = image.size
        imageString = image.convert('RGBA')
        rotatedImage = imageString.rotate(angle, expand=0).resize(startSize)
        finalImage = Image.new("RGBA", startSize, (255, 255, 255, 0))
        finalImage.paste(rotatedImage, (0, 0), rotatedImage)
        return finalImage

    def convertToDisplayFormat(self, image):
        if self.usePygame:
            imageBytes = image.convert('RGBA').tobytes("raw", 'RGBA')
            convertedImage = pygame.image.fromstring(imageBytes, image.size,
                                                     'RGBA')
        else:
            convertedImage = image
        return convertedImage

    def manipulateImage(self, image, scale, angle):
        scaledImage = self.scaleImage(image, scale)
        rotatedImage = self.rotatePIL(scaledImage, angle)
        finalImage = self.convertToDisplayFormat(rotatedImage)
        return finalImage

    def getScreenX(self, x):
        return (-self.player.x + self.screenX + x) * self.scale

    def getScreenY(self, y):
        return (self.player.y + self.screenY - y) * self.scale

    def getMiniMapX(self, x):
        return (-self.player.x + x) * self.mapScale + self.mapX

    def getMiniMapY(self, y):
        return (self.player.y - y) * self.mapScale + self.mapY

    def isInMiniMap(self, x, y, radius):
        if x - radius > self.mapX - self.mapSize / 2 and x + radius < self.mapX + self.mapSize / 2:
            if y - radius > self.mapY - self.mapSize / 2 and y + radius < self.mapY + self.mapSize / 2:
                return True
        return False
Пример #45
0
class Visualize:
    def __init__(self, solution):
        self.solution = solution
        self.time = 0
        self.full = solution.full

        self.shiftRight = 20
        self.shiftDown = 20
        self.separation = 90
        self.scale = 60
        self.textVShift = 10

        self.root = Tk()
        self.canvas = Canvas(self.root)
        self.canvas.pack(fill=BOTH, expand=YES)
        self.root.bind("<KeyRelease>", self.key_released)
        self.timeLabel = Label(self.root, text='time_lavel')
        self.timeLabel.pack(side=RIGHT)

        self.setup()
        self.draw()

        if self.full:
            mainloop()

    def key_released(self, event):
        if event.char == 'j':
            if self.time < self.solution.maxt:
                self.time = self.time + 1
                self.draw()
        elif event.char == 'k':
            if self.time > 0:
                self.time = self.time - 1
                self.draw()
        elif event.char == 'q':
            self.root.quit()

    def getBBox(self, v):
        return (self.shiftRight + self.separation*v[0],
                self.shiftDown + self.separation*v[1],
                self.shiftRight + self.separation*v[0] + self.scale,
                self.shiftDown + self.separation*v[1] + self.scale)

    def getCenter(self, v):
        return (self.shiftRight + self.separation*v[0] + self.scale / 2,
                self.shiftDown + self.separation*v[1] + self.scale / 2)

    def getStatusPos(self, v):
        (x,y) = self.getCenter(v)
        return (x,y - self.textVShift)

    def getDecisionPos(self, v):
        (x,y) = self.getCenter(v)
        return (x,y + self.textVShift)

    def getEdgePos(self, e):
        v0 = self.getCenter(e[0])
        v1 = self.getCenter(e[1])
        if v0[0] == v1[0]:
            if v0[1] < v1[1]:
                return (v0[0], v0[1] + self.scale / 2), (v1[0], v1[1] - self.scale / 2)
            else:
                return (v0[0], v0[1] - self.scale / 2), (v1[0], v1[1] + self.scale / 2)
        elif v0[1] == v1[1]:
            if v0[0] < v1[0]:
                return (v0[0] + self.scale / 2, v0[1]), (v1[0] - self.scale / 2, v1[1])
            else:
                return (v0[0] - self.scale / 2, v0[1]), (v1[0] + self.scale / 2, v1[1])
        return v0, v1

    def setup(self):
        self.nodeStatus = {}
        self.nodeDecision = {}
        for v in self.solution.nodes:
            self.canvas.create_oval(self.getBBox(v))
            self.nodeStatus[v] = self.canvas.create_text(self.getStatusPos(v), text="asfs")
            self.nodeDecision[v] = self.canvas.create_text(self.getDecisionPos(v), text="fs")
        self.edges = {}
        for e in self.solution.edges:
            self.canvas.create_line(self.getEdgePos(e), fill='gray')
            self.edges[e] = self.canvas.create_line(self.getEdgePos(e), arrow='last',
                    state=HIDDEN)

    def draw(self):
        # quick reference
        nstat = self.solution.nstat
        command = self.solution.command

        self.timeLabel.config(text = '%r' % self.time)
        t = self.time
        for v in self.solution.nodes:
            self.canvas.itemconfig(self.nodeStatus[v], text=nstat[v,self.time])
            self.canvas.itemconfig(self.nodeDecision[v], text=command[v,self.time])

        if not self.full:
            return

        occu = self.solution.occu
        for e in self.solution.edges:
            state = HIDDEN
            if occu[e,t] == 1:
                state = NORMAL
            self.canvas.itemconfig(self.edges[e], state=state)
class World:
    def __init__(self, master, x=5, y=5):
        self.master = master
        master.title("Warehouse Grid")
        master.bind("<Up>", self.call_up)
        master.bind("<r>", self.reset_event)
        self.x, self.y = x, y
        self.width = 60
        self.board = Canvas(master,
                            width=self.x * self.width,
                            height=self.y * self.width)
        self.board.grid(row=0, column=0)
        self.render_grid()
        self.agents = []
        self.agents_pos = []
        self.agents_home_pos = []
        self.items = []
        self.items_pos = []
        self.items_qty = []
        self.bins = []
        self.bins_pos = []
        self.bins_qty = []

    def call_up(self, event):
        self.step(0, "up")

    def reset_event(self, event):
        self.reset()

    def set_size(self, m, n):
        self.x, self.y = m, n
        self.board = Canvas(self.master,
                            width=self.x * self.width,
                            height=self.y * self.width)

    def render_grid(self):
        for i in range(self.x):
            for j in range(self.y):
                self.board.create_rectangle(i * self.width,
                                            j * self.width,
                                            (i + 1) * self.width,
                                            (j + 1) * self.width,
                                            fill="white",
                                            width=1)

    def restart_episode(self):
        print('new episode started')

    def add_agent(self, tagid, pos=[0, 0], color='blue'):
        agent = self.board.create_rectangle(
            pos[0] * self.width + self.width * 2 / 10,
            pos[1] * self.width + self.width * 2 / 10,
            pos[0] * self.width + self.width * 8 / 10,
            pos[1] * self.width + self.width * 8 / 10,
            fill=color,
            width=1,
            tag=tagid)
        self.agents.append(agent)
        self.agents_pos.append(pos)
        self.agents_home_pos.append(list(pos))

    def add_items(self, tagid, pos=(0, 0), qty=1, color='green'):
        item_unit = self.board.create_rectangle(
            pos[0] * self.width + self.width * 2 / 10,
            pos[1] * self.width + self.width * 2 / 10,
            pos[0] * self.width + self.width * 8 / 10,
            pos[1] * self.width + self.width * 8 / 10,
            fill=color,
            width=1,
            tag=tagid)
        qty_label = self.board.create_text(
            (pos[0] * self.width + self.width / 2,
             pos[1] * self.width + self.width / 2),
            font=("Gothic", 16),
            text=str(qty))
        self.items.append(item_unit)
        self.items_pos.append(pos)
        self.items_qty.append(qty)

    def add_bins(self, tagid, pos=(0, 0), qty=0, color='yellow'):
        bin_unit = self.board.create_rectangle(
            pos[0] * self.width + self.width * 2 / 10,
            pos[1] * self.width + self.width * 2 / 10,
            pos[0] * self.width + self.width * 8 / 10,
            pos[1] * self.width + self.width * 8 / 10,
            fill=color,
            width=1,
            tag=tagid)
        qty_label = self.board.create_text(
            (pos[0] * self.width + self.width / 2,
             pos[1] * self.width + self.width / 2),
            font=("Gothic", 16),
            text=str(qty))
        self.bins.append(bin_unit)
        self.bins_pos.append(pos)
        self.bins_qty.append(qty)

    def initialize_world(self):
        self.add_items("itemA", (2, 2), 4)
        self.add_items("itemB", (7, 2), 7)
        self.add_items("itemC", (2, 7), 4)
        self.add_items("itemD", (7, 7), 7)

        self.add_bins("binA", (0, 0))
        self.add_bins("binB", (self.x - 1, 0))
        self.add_bins("binC", (0, self.y - 1))
        self.add_bins("binD", (self.x - 1, self.y - 1))

        self.add_agent("agent0", [4, 4], 'blue')
        self.add_agent("agent1", [5, 4])
        self.add_agent("agent1", [4, 5])
        self.add_agent("agent1", [5, 5])

        print("agent pos: ", self.agents_pos)
        print("items pos: ", self.items_pos, self.items_qty)
        print("bins pos: ", self.bins_pos, self.bins_qty)

    def reset(self):
        self.bins_qty = [0 for i in range(len(self.bins))]
        self.items_qty = [10 for i in range(len(self.bins))]
        self.agents_pos = copy.deepcopy(self.agents_home_pos)

        for i in range(len(self.agents)):
            self.board.coords(
                self.agents[i],
                self.agents_pos[i][0] * self.width + self.width * 2 / 10,
                self.agents_pos[i][1] * self.width + self.width * 2 / 10,
                self.agents_pos[i][0] * self.width + self.width * 8 / 10,
                self.agents_pos[i][1] * self.width + self.width * 8 / 10)

    def step(self, agent_id, action_cmd):
        dx, dy = self.map_action_commands(action_cmd)
        # print(self.agents_pos[agent_id][0])
        self.agents_pos[agent_id][0] += dx
        self.agents_pos[agent_id][1] += dy
        pos = self.agents_pos[agent_id]
        # print(self.agents_pos,self.agents_home_pos)
        self.board.coords(self.agents[agent_id],
                          pos[0] * self.width + self.width * 2 / 10,
                          pos[1] * self.width + self.width * 2 / 10,
                          pos[0] * self.width + self.width * 8 / 10,
                          pos[1] * self.width + self.width * 8 / 10)

    def map_action_commands(self, action_cmd):
        if action_cmd == "up":
            return 0, -1
        elif action_cmd == "down":
            return 0, 1
        elif action_cmd == "right":
            return 1, 0
        elif action_cmd == "left":
            return -1, 0
        else:
            return 0, 0
Пример #47
0
@ License: MIT
"""
from tkinter import Tk, Canvas, Frame, Button
from numpy import random

master = Tk()

frame_left = Frame(master, width=400, height=400, bg="#FFFFFF")
frame_right = Frame(master, width=100, height=400, bg="#676767")
frame_left.pack(side='left')
frame_right.pack(side='top')


count = 0  # 캔버스에 그려진 오브젝트의 숫자를 세는 변수
can = Canvas(frame_left, width=400, height=400, bg="#FFFFFF")
tx_counter = can.create_text(20, 10, text="0")  # 오브젝트의 갯수 표시
can.pack()


def add_obj():
    """
    랜덤한 x, y지점에 크기가 [5, 5]인 원을 그리는 버튼명령
    """
    global count, can, tx_counter
    count += 1
    can.delete(tx_counter)
    tx_counter = can.create_text(20, 10, text=str(count))
    x, y = (random.randint(395), random.randint(395))
    can.create_oval(x, y, x+5, y+5, fill="#000")

Пример #48
0
class rmap():
    _var = [1]
    _nc = 0
    _nr = 0
    _r = 0
    _c = 0
    _size = 0
    _w = 0
    _d = 0
    _NoneUpdate = False
    _Nonelabel = False
    _Nonegettext = False
    _field = []
    _endPoint = (0, 0)

    _robot = ''  # рисунок Робота (синее кольцо)
    _park = ''

    _canvas = ''
    sleep = 0.5
    _task = ''
    _solve = ''
    _test = ''
    _res = ''
    _bum = 0

    m = []
    m.append('task1')
    m.append('task2')
    m.append('task3')
    m.append('task4')
    m.append('task5')

    m.append('task6')
    m.append('task7')
    m.append('task8')
    m.append('task9')
    m.append('task10')
    m.append('task11')
    m.append('task12')
    m.append('task13')

    class _v:  # будет содержать изображение текста и квадратиков закраски и меток. Чтобы можно было "поднимать изображение"
        text = ''
        label = ''
        color = ''

    class _Tcell():
        color = ''
        text = ''
        label = ''  # color
        wUp = False
        wLeft = False
        v = ''

    def help(self):
        """ Вывести список команд Робота
Примеры использования по команде r.help_full()
"""
        print("""
Пояснение по каждой команде: print команда.__doc__
Например:
print r.color.__doc__
---=: Команды перемещения :=---
r.rt() # Вправо
r.lt() # Влево
r.dn() # Вниз
r.up() # Вверх
r.jumpTo(r,c) # Прыжок в точку. Без особых указаний в задачах не использовать
-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=
---=: Команды изменения среды :=---
r.pt([цвет]) # Закрасить указанным цветом. По умолчанию зеленым
r.sw(направление) # Установить стену с указанной стороны
r.settext(тест) # Вписать в клетку текст
-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=
---=: Команды обратной связи :=---
r.cl() # Каким цветом закрашена клетка? r.color()
r.label() # Какого цвета метка в клетке?
r.gettext() # Какой текст в клетке?
r.getCoords() # Где Робот?
r.getCoordR() # В какой строке Робот?
r.getCoordС() # В каком столбце Робот?
r.fu() # Сверху свободно?
r.fd() # Снизу свободно?
r.fr() # Справа свободно?
r.fl() # Слева свободно?
r.wu() # Сверху стена?
r.wd() # Снизу стена?
r.wr() # Справа стена?
r.wl() # Слева стена?
r.isPark # Робот на парковке?
-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=
---=: Дополнительно :=---
r.sleep = 0.4 # Установить размер задержки после каждого хода. Меньше значение - быстрее Робот.
r._NoneUpdate = False # Отключить прорисовку поля
r._NoneUpdate = True # Включить прорисовку поля
r.demo() # Показать, что нужно сделать в текущей задаче
r.demoAll() # Показать все задачи (с решениями, по очереди)
r.randcolor() # Генерировать случайный цвет
-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=
""")

    def help_full(self):
        """ Примеры. Для получения списка команд r.help()
Примеры использования по команде r.help_full()
Больше информации по каждой команде: print команда.__doc__
Например:
print r.color.__doc__
"""
        print("""
Не реализовано в данной версии. 
Если нужно - пишите на [email protected] или на сайте progras.ru
""")

    def demo(self):
        """Показать выполнение задачи
Пример использования:
#-------------------
r.demo()
#-------------------
Для уcкорения использовать r.sleep = 0.01
В задании 10-3(4/5) можно отключить обновление экрана
#-------------------
r._NoneUpdate = True
r.demo()
r._NoneUpdate = False
#-------------------
"""
        global r
        r = self
        exec(self._solve)

    def demoAll(self):
        """Показать выполнение всех заданий в автоматическом режиме
Пример использования:
#-------------------
r.demoAll()
#-------------------
Для того, чтобы Робот двигался быстрее, используйте
#-------------------
r.sleep = 0
r.demoAll()
#-------------------
"""
        global r
        r = self
        for x in r.m:
            r.lm(x)
            print(x)
            r.demo()
            r.pause()

    def __init__(self):
        self._w = 4  # толщина стен
        self._d = 4  # на столько меньше клетки закраска (с каждой стороны)
        self.sleep = 0.5  # замедление
        self._font_size = self._size // 2
        self._tk = Tk()
        self._tk.geometry('+0+0')
        x = (self._tk.winfo_screenwidth() - self._tk.winfo_reqwidth()) / 3
        y = (self._tk.winfo_screenheight() - self._tk.winfo_reqheight()) / 4
        self._tk.wm_geometry("+%d+%d" % (x, y))
        self._tk.title('Robot-hobot')
        self._canvas = Canvas(self._tk,
                              width=(self._size * (self._nc + 1)),
                              height=(self._size * (self._nr + 1)),
                              bg="gray")

        buttons = Frame(self._tk)

        self.task = Label(self._tk, justify='left')
        self.res = Label(self._tk, justify='left')

        self._but_start = Button(buttons, text='start', width=10, height=1)
        self._but_start.bind('<ButtonRelease-1>', self.but1)

        self._but_demo = Button(buttons, text='demo', width=10, height=1)
        self._but_demo.bind('<ButtonRelease-1>', self.but_demo)

        self._but_reload = Button(buttons, text='reload', width=10, height=1)
        self._but_reload.bind('<ButtonRelease-1>', self.but_reload)

        self._but_load_next = Button(buttons,
                                     text='load next',
                                     width=10,
                                     height=1)
        self._but_load_next.bind('<ButtonRelease-1>', self.but_load_next)

        buttons.grid(row=0, column=0, sticky="w")
        self._canvas.grid(row=1, column=0, sticky="e")
        self._but_start.pack(side="left")
        self._but_demo.pack(side="left")
        self._but_reload.pack(side="left")
        self._but_load_next.pack(side="left")
        self.task.grid(row=3, column=0, sticky="w")
        self.res.grid(row=4, column=0, sticky="w")

    ##        self.loadmap()
    def but_load_next(self, event):
        print("load next")
        index = self.m.index(self._cur_map)
        if index < len(self.m) - 1:
            self.lm(self.m[index + 1])
        else:
            self.lm(self.m[0])

    def but_demo(self, event):
        print("demo")
        self.demo()

    def but1(self, event):
        print('start')
        # self.lm(self._cur_map)
        self.solve_task()

    def but_reload(self, event):
        print("reload")
        self.lm(self._cur_map)

    def clear(self):
        "Очистка данных (без перерисовки)"
        self._canvas.delete('all')
        self._field = []
        self._park = []
        self._Nonelabel = False
        self._NoneisPark = False
        self._Nonesettext = False
        self._test = ''
        self._res = ''
        self._bum = 0

        for r in range(1, self._nr + 2):
            row = []
            for c in range(1, self._nc + 2):
                row.append(self._Tcell())
            self._field.append(row)

        for r in range(1, self._nr):
            for c in range(1, self._nc):
                self._field[r][c].text = ''
                self._field[r][c].color = ''
                self._field[r][c].label = ''
                self._field[r][c].wUp = False
                self._field[r][c].wLeft = False
                self._field[r][c].v = self._v()

        for c in range(1, self._nc):
            self._field[1][c].wUp = True
            self._field[self._nr][c].wUp = True

        for r in range(1, self._nr):
            self._field[r][1].wLeft = True
            self._field[r][self._nc].wLeft = True

        self._solve = ''
        self._r = 1
        self._c = 1

    def _paintMap(self):
        "Перерисовка  по имеющимся данным"
        remc = self._c
        remr = self._r
        size = self._size
        sleep = self.sleep
        self.sleep = 0

        self._bg = [
            self._canvas.create_rectangle(1,
                                          1, (size * (self._nc + 1)),
                                          (size * (self._nr + 1)),
                                          fill="gray")
        ]
        # создать поле

        for r in range(1, self._nr + 1):
            self._bg.append(
                self._canvas.create_line(size, r * size, self._nc * size,
                                         r * size))
            if r < self._nr:
                self._canvas.create_text(size / 2, r * size + size / 2, text=r)
        for c in range(1, self._nc + 1):
            self._bg.append(
                self._canvas.create_line(c * size, size, c * size,
                                         self._nr * size))
            if c < self._nc:
                self._bg.append(
                    self._canvas.create_text(c * size + size / 2,
                                             size / 2,
                                             text=c))
        # клетки и номера столбцов и строк

        for r in range(1, self._nr):
            for c in range(1, self._nc):
                self._r = r
                self._c = c
                if self._field[r][c].wUp:  # стена сверху
                    self.setWall('up')
                if self._field[r][c].wLeft:  # стена слева
                    self.setWall('left')
                if self._field[r][c].color != '':  # закраска
                    self.paint(self._field[r][c].color)
                if self._field[r][c].label != '':  # метка0000
                    d = self._d
                    x1 = self._size * (c)
                    x2 = self._size * (c + 1)
                    y1 = self._size * (r)
                    y2 = self._size * (r + 1)
                    self._canvas.delete(self._field[r][c].v.label)
                    self._field[r][c].v.label = self._canvas.create_rectangle(
                        x1 + d,
                        y1 + d,
                        x2 - d,
                        y2 - d,
                        width=d - 1,
                        outline=self._field[r][c].label)
                    self._canvas.lift(self._robot)
                self.settext(self._field[r][c].text)  # текст

        for self._c in range(1, self._nc):
            if self._field[self._nr][self._c].wUp:  # стена сверху
                self.setWall('down')

        for self._r in range(1, self._nr):
            if self._field[self._r][self._nc].wLeft:  # стена слева
                self.setWall('right')

        r = self._endPoint[0]
        c = self._endPoint[1]
        self._canvas.delete(self._park)
        if r > 0 and c > 0:
            self._park = self._canvas.create_oval(c * size + 6,
                                                  r * size + 6,
                                                  c * size + size - 6,
                                                  r * size + size - 6,
                                                  width=3,
                                                  outline='yellow')
        # конечная точка

        self.jumpTo((remr, remc))
        self._task = '\n' + self._task
        self.task.config(text=self._task)
        self.res.config()
        self._update()
        self.sleep = sleep
        # self.pause()

    def _update(self):
        "Обновить canvas"
        if not self._NoneUpdate:
            self._canvas.update()
            time.sleep(self.sleep)

    def start(self, fun):
        self.solve_task = fun
        self._tk.mainloop()

    ##Робот

    def pause(self, t=1):
        """Приостановка выполнения программы. Пауза в секундах.
#-------------------
r.pause() # пауза в одну секунду
#-------------------
r.pause(2) # пауза две секунды
#-------------------
"""
        time.sleep(t)

    def left(self, a=1):
        """Шаг влево
#-------------------
r.left()
#-------------------
r.lt()
#-------------------
r.lt(3)
#-------------------
"""
        if a == 1:
            if self.freeLeft():
                self._c -= 1
                self._canvas.move(self._robot, -self._size * a, 0)
                self._update()
            else:
                self._stop()
        else:
            for z in range(0, a):
                self.left()

    def right(self, a=1):
        """ Шаг вправо
#-------------------
r.right()
#-------------------
r.rt()
#-------------------
r.rt(5)
#-------------------
"""
        if a == 1:
            if self.freeRight():
                self._c += 1
                self._canvas.move(self._robot, self._size * a, 0)
                self._update()
            else:
                self._stop()

        else:
            for z in range(0, a):
                self.right()

    def up(self, a=1):
        """Шаг вверх
#-------------------
r.up()
#-------------------
r.up(3)
#-------------------
"""
        if a == 1:
            if self.freeUp():
                self._r -= 1
                self._canvas.move(self._robot, 0, -self._size * a)
                self._update()
            else:
                self._stop()
        else:
            for z in range(0, a):
                self.up()

    def down(self, a=1):
        """ Шаг вниз
#-------------------
r.down()
#-------------------
r.dn()
#-------------------
r.dn(4)
#-------------------
"""
        if a == 1:
            if self.freeDown():
                self._r += 1
                self._canvas.move(self._robot, 0, self._size * a)
                self._update()
            else:
                self._stop()
        else:
            for z in range(0, a):
                self.down()

    def jumpTo(self, coord=(1, 1)):
        """Прыжок в клетку с указанными координами. Через стены.
#-------------------
r.jumpTo((2,3)) # Робот окажется в третьем столбце второй строки
#-------------------
"""

        r = coord[0]
        c = coord[1]
        if (0 < r < self._nc) and (0 < c < self._nc):
            self._r = r
            self._c = c
            size = self._size
            self._canvas.coords(self._robot, c * size + 4, r * size + 4,
                                c * size + size - 4, r * size + size - 4)
            self._canvas.lift(self._robot)
            self._update()
        else:
            print("Попытка переместиться за пределы поля. Отказано.")

    def paint(self, color='green'):
        """ Закрасить текущую клетку выбранным цветом. Если цвет не указан, то зеленым
#-------------------
r.paint() # Закрасит текущую клетку зеленым цветом
#-------------------
r.pt() # Закрасит текущую клетку зеленым цветом
#-------------------
r.pt('red') # Закрасит текущую клетку красным цветом
#-------------------
r.pt(r.randcolor()) # Закрасит текущую клетку случайным цветом
#-------------------
r.pt(r.label()) # Закрасит текущую клетку цветом метки в этой клетке
#-------------------
"""
        d = self._d + 1
        self._field[self._r][self._c].color = color

        x1 = self._size * (self._c)
        x2 = self._size * (self._c + 1)
        y1 = self._size * (self._r)
        y2 = self._size * (self._r + 1)
        self._canvas.delete(self._field[self._r][self._c].v.color)
        self._field[self._r][self._c].v.color = self._canvas.create_rectangle(
            x1 + d, y1 + d, x2 - d, y2 - d, width=0, fill=color)
        self._canvas.lift(self._field[self._r][self._c].v.text)
        self._canvas.lift(self._robot)
        self._canvas.lift(self._park)
        self._update()

    def setWall(self, target):
        """ Установить стену с указанной стороны
#-------------------
r.sw('up') # Установить стену сверху
#-------------------
r.sw('left') # Установить стену слева
#-------------------
r.sw('down') # Установить стену снизу
#-------------------
r.sw('right') # Установить стену справа
#-------------------
"""
        size = self._size
        w = self._w
        if target == 'up':
            r = self._r
            c = self._c
            x1 = size * (c) - 1
            x2 = size * (c + 1) + 1
            y1 = size * (r)
            y2 = size * (r + 1)
            self._field[r][c].wUp = True
            self._canvas.create_line(x1, y1, x2, y1, width=w)
        elif target == 'left':
            r = self._r
            c = self._c
            x1 = size * (c)
            x2 = size * (c + 1)
            y1 = size * (r) - 1
            y2 = size * (r + 1) + 1
            self._field[r][c].wLeft = True
            self._canvas.create_line(x1, y1, x1, y2, width=w)
        elif target == 'down':
            r = self._r + 1
            c = self._c
            x1 = size * (c) - 1
            x2 = size * (c + 1) + 1
            y1 = size * (r)
            y2 = size * (r + 1)
            self._field[r][c].wDown = True
            self._canvas.create_line(x1, y1, x2, y1, width=w)
        elif target == 'right':
            r = self._r
            c = self._c + 1
            x1 = size * (c)
            x2 = size * (c + 1)
            y1 = size * (r) - 1
            y2 = size * (r + 1) + 1
            self._field[r][c].wRight = True
            self._canvas.create_line(x1, y1, x1, y2, width=4)
        self._update()

    def wallUp(self):
        """ Возвращает истину, если сверху есть стена
#-------------------
if r.wallUp(): r.pt() # Закрасить, если сверху стена
#-------------------
if r.wu(): r.pt() # Закрасить, если сверху стена
#-------------------
if r.wu():
    r.pt() # Закрасить, если сверху стена
    r.rt() # Перейти вправо
#-------------------
while r.wu(): # Идти вправо, пока сверху есть стена
    r.rt()
"""
        return self._field[self._r][self._c].wUp

    def wallDown(self):
        """ Возвращает истину, если снизу есть стена
#-------------------
if r.wallDown(): r.pt() # Закрасить, если снизу стена
#-------------------
if r.wd(): r.pt() # Закрасить, если снизу стена
#-------------------
if r.wd():
    r.pt() # Закрасить, если снизу стена
    r.rt() # Перейти вправо
#-------------------
while r.wd(): # Идти вправо, пока снизу есть стена
    r.rt()
"""
        return self._field[self._r + 1][self._c].wUp

    def wallLeft(self):
        """ Возвращает истину, если слева есть стена
#-------------------
if r.wallLeft(): r.pt() # Закрасить, если слева стена
#-------------------
if r.wl(): r.pt() # Закрасить, если слева стена
#-------------------
if r.wl():
    r.pt() # Закрасить, если слева стена
    r.dn() # Перейти вниз
#-------------------
while r.wl(): # Идти вниз, пока слева есть стена
    r.dn()
"""
        return self._field[self._r][self._c].wLeft

    def wallRight(self):
        """ Возвращает истину, если справа есть стена
#-------------------
if r.wallRight(): r.pt() # Закрасить, если справа стена
#-------------------
if r.wr(): r.pt() # Закрасить, если справа стена
#-------------------
if r.wr():
    r.pt() # Закрасить, если справа стена
    r.dn() # Перейти вниз
#-------------------
while r.wr(): # Идти вниз, пока справа есть стена
    r.dn()
"""
        return self._field[self._r][self._c + 1].wLeft

    def freeUp(self):
        """ Возвращает истину, если сверху свободно (нет стены)
#-------------------
if r.freeUp(): r.pt() # Закрасить, если сверху свободно
#-------------------
if r.fu(): r.up() # Шагнуть вверх, если сверху свободно
#-------------------
if r.fu():
    r.up() # Шагнуть вверх
    r.pt() # Закрасить
    r.dn() # Перейти вниз
#-------------------
while r.fu(): # Идти вверх, пока сверху свободно
    r.up()
"""
        return not self._field[self._r][self._c].wUp

    def freeDown(self):
        """ Возвращает истину, если снизу свободно (нет стены)
#-------------------
if r.freeDown(): r.pt() # Закрасить, если снизу свободно
#-------------------
if r.fd(): r.dn() # Шагнуть вверх, если снизу свободно
#-------------------
if r.fd():
    r.dn() # Шагнуть снизу
    r.pt() # Закрасить
    r.up() # Перейти вверх
#-------------------
while r.fd(): # Идти вниз, пока снизу свободно
    r.dn()
"""
        return not self._field[self._r + 1][self._c].wUp

    def freeLeft(self):
        """ Возвращает истину, если слева свободно (нет стены)
#-------------------
if r.freeLeft(): r.pt() # Закрасить, если слева свободно
#-------------------
if r.fl(): r.lt() # Шагнуть влево, если слева свободно
#-------------------
if r.fl():
    r.lt() # Шагнуть влево
    r.pt() # Закрасить
    r.rt() # Перейти вправо
#-------------------
while r.fl(): # Идти влево, пока слева свободно
    r.lt()
"""
        return not self._field[self._r][self._c].wLeft

    def freeRight(self):
        """ Возвращает истину, если снизу свободно (нет стены)
#-------------------
if r.freeDown(): r.pt() # Закрасить, если снизу свободно
#-------------------
if r.fd(): r.dn() # Шагнуть вверх, если снизу свободно
#-------------------
if r.fd():
    r.dn() # Шагнуть снизу
    r.pt() # Закрасить
    r.up() # Перейти вверх
#-------------------
while r.fd(): # Идти вниз, пока снизу свободно
    r.dn()
"""
        return not self._field[self._r][self._c + 1].wLeft

    def getCoords(self):
        " Возвращает координаты в виде (row,column)"
        return (self._r, self._c)

    def getCoordR(self):
        " Возвращает номер строки, в которой находиться Робот"
        return self._r

    def getCoordC(self):
        " Возвращает номер столбца, в которой находиться Робот"
        return self._c

    def isPark(self):
        " Возвращает истину, если Робот находиться на парковке"
        if self._NoneisPark:
            self.null()
        else:
            return self._endPoint == self.getCoords()

    def color(self):
        """ Возвращает цвет, которым закрашена клетка
Можно использовать для проверки, закрашена ли клетка:
#-------------------
# Закрасить, если сверху закрашено
r.up()
if r.color():
    r.dn()
    r.pt()
else:
    r.dn()
#-------------------
if r.color() == 'red': r.rt() # Вправо, если закрашено красным
#-------------------
"""
        return self._field[self._r][self._c].color

    def randcolor(self):
        """ Возвращает случайный цвет
#-------------------
r.pt(r.randcolor()) # Закрасить случайным цветом
#-------------------
# Закрасить соседнюю клетку тем же цветом, что и текущая
x = r.color()
r.rt()
r.pt(x)
#-------------------
"""
        cr = rnd(1, 255, 10)
        cg = rnd(1, 255, 10)
        cb = rnd(1, 255, 10)
        color = "#%02X%02X%02X" % (cr, cg, cb)
        return str(color)

    def label(self):
        """ Возвращает цвет метки текущей клетки
#-------------------
if r.label() == 'red': r.pt('red') # Закрасить клетку красным, если метка красная
#-------------------
"""
        if self._Nonelabel:
            self.null()
        else:
            return self._field[self._r][self._c].label

    def gettext(self):
        """ Возвращает текст, записанный в ячейке.
#-------------------
if r.gettext() != '': r.rt() # Перейти вправо, если в ячейке есть какой-нибудь текст
#-------------------
if r.gettext() == '3': r.rt() # Перейти вправо, если в ячейке записано 3
#-------------------
n = r.gettext()
if n: r.rt(n) # Перейти вправо на количество шагов, указанное в клетке
#-------------------
"""
        if self._Nonegettext:
            self.null()
        else:
            return self._field[self._r][self._c].text

    def settext(self, text):
        """ Записать текст в клетку
#-------------------
r.settext(3)
#-------------------
"""
        self._field[self._r][self._c].text = text
        d = 1
        x1 = self._size * (self._c)
        x2 = self._size * (self._c + 1)
        y1 = self._size * (self._r)
        y2 = self._size * (self._r + 1)
        self._canvas.delete(self._field[self._r][self._c].v.text)
        self._field[self._r][self._c].v.text = self._canvas.create_text(
            self._c * self._size + self._size / 2,
            self._r * self._size + self._size / 2,
            text=self._field[self._r][self._c].text,
            font=('Helvetica', self._font_size, 'bold'))
        self._update()

    def _stop(self):
        print("Bum!")
        self._bum = 1
        self._canvas.delete(self._robot)
        x = self._c
        y = self._r

        self._robot = self._canvas.create_oval(
            x * self._size + 2 * self._d,
            y * self._size + 2 * self._d,
            x * self._size + self._size - 2 * self._d,
            y * self._size + self._size - 2 * self._d,
            fill='#FF0000')

    def null(self, *args):
        print(
            'Эта команда запрещена к использованию в данной задаче. Ищите другой способ'
        )
        return ''

    def loadmap(self, mn=m[0], variant=0):
        """ Загрузить карту (задачу)
#-------------------
r.loadmap('task10-5')
#-------------------
r.lm('task10-5') # Загрузить задачу по названию
#-------------------
r.lm(r.m[5]) # Загрузить задачу по номеру
#-------------------
# Вывести полный список названий и номеров заданий
for x in r.m:
    print r.m.index(x),x
#-------------------
"""
        self._tk.title(mn)
        self._cur_map = mn
        self._NoneUpdate = False
        self._endPoint = (0, 0)
        #        self._NoneUpdate = True

        if mn == 'task1':
            self._nc = 7
            self._nr = 5
            self._size = 30

            self.clear()
            self._r = 3
            self._c = 2

            self._solve = ''
            self._endPoint = (3, 5)
            self._task = 'Необходимо перевести Робота по лабиринту\n' \
                         ' из начального положения в конечное.\n'

            self._field[2][2].wUp = True
            self._field[2][3].wUp = True
            self._field[2][4].wUp = True
            self._field[2][5].wUp = True

            self._field[4][2].wUp = True
            self._field[4][3].wUp = True
            self._field[4][4].wUp = True
            self._field[4][5].wUp = True

            self._field[2][4].wLeft = True
            self._field[3][3].wLeft = True
            self._field[3][5].wLeft = True

        ##--------------------------------------------------------------------------------------------
        elif mn == 'task2':
            self._nc = 16
            self._nr = 4
            self._size = 30

            self.clear()
            self._r = 3
            self._c = 1

            self._solve = ''

            self._task = 'Составьте программу рисования узора.\n'

        ##--------------------------------------------------------------------------------------------
        elif mn == 'task3':
            self._nc = 10
            self._nr = 5
            self._size = 30
            self.clear()
            self._r = 2
            self._c = 1

            self._endPoint = (2, 9)
            self._solve = ''
            self._task = 'Необходимо провести Робота вдоль коридора\n' \
                         ' из начального положения в конечное,\n' \
                         ' заглядывая в каждый боковой коридор.'

            for i in range(2, 9):
                self._field[2][i].wUp = True
                if i % 2 == 0:
                    self._field[3][i].wUp = True
                else:
                    self._field[4][i].wUp = True

                if i < 8:
                    self._field[3][i + 1].wLeft = True

        ##--------------------------------------------------------------------------------------------
        elif mn == 'task4':
            self._nc = 8
            self._nr = 12
            self._size = 30
            self.clear()
            self._r = rnd(1, self._nr)
            self._c = rnd(1, self._nc)

            for i in range(0, 5):
                for j in range(0, 3):
                    self._field[6 + 2 * j - i][2 + i].label = 'red'

            self._solve = ''
            self._task = 'Составьте программу закрашивания\n' \
                         ' клеток поля, отмеченных звездочкой.\n'

        ##--------------------------------------------------------------------------------------------
        elif mn == 'task5':
            self._nc = 16
            self._nr = 11
            self._r = 1
            self._c = 1
            self._size = 30

            self.clear()
            self._solve = ''
            self._task = 'Составьте программу рисования узора.'

        ##--------------------------------------------------------------------------------------------
        ##--------------------------------------------------------------------------------------------
        elif mn == 'task6':
            self._nc = 25
            self._nr = 25
            self._r = 1
            self._c = 1
            self._size = 20
            self.clear()
            self._solve = ''
            self._task = 'Составьте программу рисования фигуры в виде буквы "Т".\n' \
                         ' Вертикальные и горизонтальные размеры пользователь вводит\n' \
                         ' с клавиатуры. Ввод данных можно осуществлять любым способом.\n'

        ##-------------------------------------------------------------------------------------------------------
        elif mn == 'task7':
            self._nc = 16
            self._nr = 11
            self._size = 25

            self.clear()

            self._r = rnd(1, self._nr)
            self._c = rnd(1, self._nc)

            self._field[3][2].wUp = True
            self._field[2][9].wUp = True
            self._field[3][12].wUp = True
            self._field[6][12].wUp = True
            self._field[7][3].wUp = True
            self._field[7][9].wUp = True
            self._field[8][6].wUp = True
            self._field[9][2].wUp = True
            self._field[9][11].wUp = True

            for i in range(0, 4):
                self._field[4][5 + i].wUp = True
                self._field[5][5 + i].wUp = True

            self._solve = ''

            self._task = 'Где-то в поле Робота находится горизонтальный коридор шириной в одну клетку\n' \
                         ' неизвестной длины. Робот из верхнего левого угла поля должен дойти до\n' \
                         ' коридора и закрасить клетки внутри него, как указано в задании. По полю\n' \
                         ' Робота в произвольном порядке располагаются стены, но расстояние \n' \
                         'между ними больше одной клетки.\n'
        ##--------------------------------------------------------------------------------------------
        elif mn == 'task8':
            self._nc = 16
            self._nr = 11
            self._size = 25

            self.clear()

            self._r = rnd(1, self._nr)
            self._c = rnd(1, self._nc)

            self._field[2][6].wLeft = True
            self._field[3][6].wLeft = True
            self._field[5][6].wLeft = True
            self._field[6][6].wLeft = True
            self._field[7][6].wLeft = True
            self._field[8][6].wLeft = True

            self._solve = ''
            self._task = 'Где-то в поле Робота находится вертикальная стена с отверстием в одну клетку,\n' \
                         ' размеры которой неизвестны. Робот из произвольной клетки должен дойти до\n' \
                         ' стены и закрасить клетки как показано в задании.\n'

        ##--------------------------------------------------------------------------------------------
        elif mn == 'task9':
            self._nc = 20
            self._nr = 20
            self._size = 25

            self.clear()

            self._r = rnd(1, self._nr)
            self._c = rnd(1, self._nc)

            c = rnd(2, 16)
            r = rnd(2, 16)
            w = rnd(3, 8)
            h = rnd(3, 8)
            if c + w >= self._nc: w = self._nc - c
            if r + h >= self._nc: h = self._nr - r

            for rcount in range(0, h):
                for ccount in range(0, w):
                    self._field[r + rcount][c + ccount].color = 'green'

            self._solve = ''

            self._task = 'На поле находится квадрат из закрашенных клеток. Вычислить и вывести на экран площадь квадрата.\n'

        ##--------------------------------------------------------------------------------------------
        elif mn == 'task10':
            self._nc = 15
            self._nr = 11
            self._size = 30
            self.clear()
            self._r = 2
            self._c = 1

            self._field[2][1].wUp = True
            self._field[2][2].wUp = True
            self._field[2][4].wUp = True
            self._field[2][5].wUp = True
            self._field[2][6].wUp = True
            self._field[2][8].wUp = True
            self._field[2][9].wUp = True
            self._field[2][11].wUp = True
            self._field[2][12].wUp = True
            self._field[2][13].wLeft = True

            self._field[3][1].wUp = True
            self._field[3][2].wUp = True
            self._field[3][3].wUp = True
            self._field[3][4].wUp = True
            self._field[3][6].wUp = True
            self._field[3][7].wUp = True
            self._field[3][8].wUp = True
            self._field[3][10].wUp = True
            self._field[3][11].wUp = True
            self._field[3][12].wLeft = True

            self._field[4][3].wLeft = True
            self._field[4][3].wUp = True
            self._field[4][4].wUp = True
            self._field[4][5].wUp = True
            self._field[4][6].wUp = True
            self._field[4][8].wUp = True
            self._field[4][9].wUp = True
            self._field[4][10].wUp = True
            self._field[4][11].wUp = True
            self._field[4][13].wLeft = True

            self._field[5][3].wLeft = True
            self._field[5][4].wLeft = True
            self._field[5][4].wUp = True
            self._field[5][6].wUp = True
            self._field[5][7].wUp = True
            self._field[5][8].wUp = True
            self._field[5][10].wUp = True
            self._field[5][11].wUp = True
            self._field[5][12].wUp = True

            self._field[6][3].wLeft = True
            self._field[6][4].wUp = True
            self._field[6][5].wLeft = True

            self._field[7][3].wUp = True
            self._field[7][4].wLeft = True
            self._field[7][6].wUp = True
            self._field[7][7].wLeft = True

            self._field[8][4].wUp = True
            self._field[8][5].wUp = True
            self._field[8][6].wLeft = True
            self._field[8][7].wUp = True
            self._field[8][8].wLeft = True

            self._field[9][6].wUp = True
            self._field[9][7].wLeft = True
            self._field[9][8].wUp = True
            self._field[9][9].wUp = True
            self._field[9][10].wLeft = True

            self._field[10][7].wUp = True
            self._field[10][9].wLeft = True
            self._field[10][10].wLeft = True

            self._endPoint = (10, 1)
            self._solve = """
"""

            self._task = 'Необходимо провести Робота по коридору шириной в одну клетку из начального положения до конца коридора, \n' \
                         'закрашивая при этом все клетки коридора, которые имеют выход. Выходы размером в одну клетку располагаются \n' \
                         'произвольно по всей длине коридора. Коридор заканчивается тупиком. Коридор имеет два горизонтальных и \n' \
                         'диагональный участки. Пример коридора показан на рисунке.\n'

        elif mn == 'task11':
            self._nc = 15
            self._nr = 11
            self._size = 30
            self.clear()

            self._r = rnd(1, self._nr)
            self._c = rnd(1, self._nc)

            for i in range(1, self._nr):
                for j in range(1, self._nc):
                    self._field[i][j].text = str(rnd(0, 10))

            self._task = 'На поле 10х15 каждой в каждой клетке записана цифра (от 0 до 9).\n Закрасить квадрат 2х2 с наименьшей суммой значений клеток.'

        elif mn == 'task12':
            self._nc = 15
            self._nr = 6
            self._size = 30
            self.clear()

            self._r = 2
            self._c = 13

            self._field[2][2].wUp = True
            self._field[2][3].wLeft = True
            self._field[3][3].wLeft = True
            self._field[4][3].wLeft = True
            self._field[5][3].wUp = True
            self._field[5][4].wUp = True
            self._field[4][5].wLeft = True
            self._field[3][5].wLeft = True
            self._field[2][5].wLeft = True
            self._field[2][5].wUp = True
            self._field[2][6].wLeft = True
            self._field[3][6].wLeft = True
            self._field[4][6].wLeft = True
            self._field[5][6].wUp = True
            self._field[5][7].wUp = True
            self._field[5][8].wUp = True
            self._field[4][9].wLeft = True
            self._field[3][9].wLeft = True
            self._field[2][9].wLeft = True
            self._field[2][9].wUp = True
            self._field[2][10].wUp = True
            self._field[2][11].wLeft = True
            self._field[3][11].wLeft = True
            self._field[4][11].wLeft = True
            self._field[5][11].wUp = True
            self._field[4][12].wLeft = True
            self._field[3][12].wLeft = True
            self._field[2][12].wLeft = True
            self._field[2][12].wUp = True
            self._field[2][13].wUp = True

            self._task = 'Робот движется вдоль стены, профиль которой показан на рисунке,\n' \
                         ' от начального положения до конца стены. Необходимо закрасить\n' \
                         ' все внутренние углы стены, как показано на примере. Размеры стены\n могут быть произвольны.'

        elif mn == 'task13':
            self._nc = 20
            self._nr = 20
            self._size = 25

            self.clear()

            self._r = rnd(self._nr / 2, self._nr)
            self._c = rnd(self._nc / 2, self._nc)

            col = rnd(2, self._nc / 2)
            row = rnd(4, self._nr / 2)
            height = rnd(4, self._nr - 4)

            if row + height >= self._nr:
                height = self._nr - row - 1

            for i in range(row, row + height):
                self._field[i][col].wLeft = True

        ##--------------------------------------------------------------------------------------------

        ##--------------------------------------------------------------------------------------------
        # сделать прямое управление с демонстрацией датчиков и возможностей
        # при запуске робота создавать task.py и справочник :)
        # сделать робота без клеток !!!
        ##--------------------------------------------------------------------------------------------
        ##--------------------------------------------------------------------------------------------
        else:
            print(mn)
            self._task = "Нет задачи с таким номером"
            self._test = '-'

        self._canvas.config(width=(self._size * (self._nc + 1)),
                            height=(self._size * (self._nr + 1)))
        x = y = 1
        d = self._d
        d = 6
        self._robot = self._canvas.create_oval(x * self._size + d,
                                               y * self._size + d,
                                               x * self._size + self._size - d,
                                               y * self._size + self._size - d,
                                               outline='#4400FF',
                                               width=3)

        self._paintMap()

    lm = loadmap
    lt = left
    rt = right
    dn = down
    pt = paint
    sw = setWall
    wu = wallUp
    wd = wallDown
    wl = wallLeft
    wr = wallRight
    fu = freeUp
    fd = freeDown
    fl = freeLeft
    fr = freeRight
    cl = color
Пример #49
0
    global dn
    global times
    global correct
    global direcs
    global totalresp
    global top
    global curd
    correct = []
    times = []
    direcs = []
    totalresp = 0
    top = tkinter.Tk()
    
    gameboard = Canvas(top, bg = "black", width = 1000, height = 750)
    downI = PhotoImage(file = "Down.PNG")
    upI = PhotoImage(file = "Up.PNG")
    leftI = PhotoImage(file = "Left.PNG")
    rightI = PhotoImage(file = "Right.PNG")
    
    cur = 1
    curd = 1
    dn = 0
    
    arrow = gameboard.create_image(650, 200, anchor= "ne", image = downI)
    tdisp = gameboard.create_text(0, 0, anchor = "ne", text = '', fill = 'red') 
    
    gameboard.pack()
    gameboard.bind_all('<KeyRelease>', kp) 
    start = time.time()
    top.mainloop()
Пример #50
0
    ]
    return Snake(segments)


# Setting up window
root = Tk()

root.title("The Snake")
root.iconbitmap(r"icon.ico")
c = Canvas(root, width=WIDTH, height=HEIGHT, bg="#fff")
c.grid()
# catch keypressing
c.focus_set()
game_over_text = c.create_text(WIDTH / 2,
                               HEIGHT / 2,
                               text="Игра окончена!",
                               font='Roboto 20',
                               fill='black',
                               state='hidden')
restart_text = c.create_text(WIDTH / 2,
                             HEIGHT - HEIGHT / 3,
                             font='Roboto 30',
                             fill='black',
                             text="Кликните для перезапуска",
                             state='hidden')
exit_game = c.create_text(WIDTH / 2,
                          HEIGHT / 4,
                          text='НАЖМИТЕ ESC ДЛЯ ВЫХОДА',
                          fill='black',
                          font='Impact 10',
                          state='hidden')
Пример #51
0
                controlBar("文件生成中", 100)
            time.sleep(0.1)
        controlBar("完成", 100)
        resetStatus()

def runthread():
    global rectlist
    limit = list(map(lambda x: bool(x) and int(x) or 1, [limitXEntry.get(), limitYEntry.get()]))
    rectlist = trimList(analyse(pngPath), limit)
    print(rectlist)
    writeFile(rectlist, outDictory, outNameEntry.get())

items = {}
bar = Canvas(top, width = 300, height = 20, bg = "white")
items['bar'] = bar.create_rectangle(2, 1, 1, 20, fill = "blue")
items['text'] = bar.create_text(140, 13, text = "未开始", fill = "black")

def controlBar(text = "未开始", rate = 0):
    global items
    global bar
    bar.coords(items['bar'], 2, 1, rate * 3, 20)
    bar.itemconfig(items['text'], text = text)


# label = Label(top, text = 'hello ,python')
# label.pack(fill=BOTH)

top.pack()
advancedFrame.pack(anchor = "nw", pady = 20)

getBtn = Button(top, text = "打开", command = getfilepath, width = 10)
            list_events.append(current_event)
    return list_events


def days_between_dates(date1, date2):
    time_between = str(date2 - date1)
    number_of_days = time_between.split(' ')
    return number_of_days[0]


root = Tk()
c = Canvas(root, width=800, height=800, bg='lightblue')
c.pack()
c.create_text(100,
              50,
              anchor='w',
              fill='darkorange',
              font='Arial 28 bold underline',
              text='Countdown Calendar')
events = get_events()
today = date.today()
vertical = 100
for event in events:
    event_name = event[0]
    days_until = days_between_dates(today, event[1])
    if int(days_until) <= 7:
        text_col = 'red'
    else:
        text_col = 'green'
    display = 'It is %s days until %s' % (days_until, event_name)
    c.create_text(100,
                  vertical,
Пример #53
0
def Classes(sbjBook, string):

	from tkinter import Tk
	from tkinter import Canvas
	import os

	master = Tk()

	w=1240
	h=1754
	m=120

	c = Canvas(master, width=1240, height=1754)
	c.pack()

	c.create_rectangle(0, 0, w, h, fill="#fff", outline="#fff")

	c.create_rectangle(m, 60, w-m, 180, fill="#9bbb59", outline="#cadba6")
	c.create_text(m+60, 90, fill="#fff", font=("Ubuntu","12", "bold") , text="SUBJECT")
	c.create_text(m+170, 90, fill="#fff", font=("Ubuntu","12", "bold") , text="CLASS")
	c.create_text(m+420, 90, fill="#fff", font=("Ubuntu","12", "bold") , text="SCHEDULE")
	c.create_text(m+720, 90, fill="#fff", font=("Ubuntu","12", "bold") , text="PROFESSOR")
	c.create_text(m+920, 90, fill="#fff", font=("Ubuntu","12", "bold") , text="OFFERED AS")	

	for i in range(13):
		c.create_rectangle(m, m+120*i, w-m, m+120*i+60, fill="#ebf1de", outline="#cadba6")
		c.create_rectangle(m, m+120*i+60, w-m, m+120*i+120, fill="#fff", outline="#cadba6")

	count = -1
	page = 0
	for i in sbjBook:
		if(i == -1):
			pass
		else:
			classroom = -1
			sameSche = [[],[],[]]
			scheRecord = [[],[],[]]
			for j in range(len(sbjBook[i])):
				classroom += 1
				count += 1
				period = sbjBook[i][j][1]
				hpw = sbjBook[i][j][2]
				professor = sbjBook[i][j][3]
				group = sbjBook[i][j][4]
				if(group==None):
					group = 'Elective'
				else:
					course_id = int(group/5)
					b26 = ''
					d = int(1)
					while(d<course_id):
						d = int(d*26)
					if(d>=26):d = int(d/26)
					else: pass
					while(d>=1):
						b26 = b26+chr(int(course_id/d) + ord('A'))
						course_id = course_id % d
						d = d/26
					group = str(group+1)+'-Year required subject\nfor course '+b26
				sche = sbjBook[i][j][5:]
		
				if(sche in scheRecord[period]):
					class_id = scheRecord[period].index(sche)
					class_idBK = scheRecord[period].index(sche)
					sameSche[period][class_id][0] += 1
				else:
					scheRecord[period].append(sche)
					sameSche[period].append([0])
					class_id = scheRecord[period].index(sche)
					class_idBK = scheRecord[period].index(sche)
			
				schedule = ""
				for k in sche:
					if(schedule==""):pass
					else: schedule = schedule + "\n"
				
					weekday = int((k+1)/2) + (k+1)%2
					if(weekday==1): weekday = 'Monday '
					elif(weekday==2): weekday = 'Tuesday '
					elif(weekday==3): weekday = 'Wednesday '
					elif(weekday==4): weekday = 'Thursday '
					else: weekday = 'Friday '
				
					if(k%2==0 and period==0): hour = "from 8:00 am to 10:00 am"
					elif(k%2==0 and period==1): hour = "from 2:00 pm to 4:00 pm"
					elif(k%2==0 and period==2): hour = "from 7:00 pm to 9:00 pm"
					elif(k%2==1 and period==0): hour = "from 10:00 am to 12:00 pm"
					elif(k%2==1 and period==1): hour = "from 4:00 pm to 6:00 pm"
					elif(k%2==1 and period==2): hour = "from 9:00 pm to 11:00 pm"
					
					try: schedule = schedule + weekday + hour
					except: print(k,period); raise
			
				b26 = ''
				div = int(1)
				while(div<class_id):
					div = int(div*26)
				if(div>=26):div = int(div/26)
				else: pass
				while(div>=1):
					b26 = b26+chr(int(class_id/div) + ord('A'))
					class_id = class_id % div
					div = div/26
		
				if(period==0): periodTX = " - morning"
				elif(period==1): periodTX = " - afternoon"
				else: periodTX = " - evening"
		
				if(count<=25): pass
				else:
					c.update()
					c.postscript(file = "classes-"+str(page)+".ps", pageheight="29.70c",x="0",y="0",height="1754",width="1240") 
					c.delete("lines")
					count = 0
					page += 1
				
				c.create_text(m+60, 150+60*count, fill="#000", font=("Ubuntu","10") , text=i, tags="lines") # Subject
				c.create_text(m+170, 150+60*count, fill="#000", font=("Ubuntu","10") , text=b26+str(sameSche[period][class_idBK][0]+1)+periodTX, tags="lines") # Class
				c.create_text(m+420, 150+60*count, fill="#000", font=("Ubuntu","10") , text=schedule, tags="lines") # Schedule
				c.create_text(m+720, 150+60*count, fill="#000", font=("Ubuntu","10") , text=professor, tags="lines") # Professor
				c.create_text(m+920, 150+60*count, fill="#000", font=("Ubuntu","10") , justify='center', text=group, tags="lines") # Group

	c.update()
	c.postscript(file = string+"-"+str(page)+".ps", pageheight="29.70c",x="0",y="0",height="1754",width="1240") 

	#Concatenate PS files and output a single PDF, then clear PS files
	os.system("convert -density 300 *.ps  "+string+".pdf")
	os.system("find . -name \*.ps -type f -delete")
class Graphics:
    def __init__(self, env):
        self.running = True
        self.environment = env
        self.cv_width = 600
        self.cv_height = 600
        self.padding = 100
        self.floor_margin = ((self.cv_height - self.padding) /
                             self.environment.number_of_floors)
        self.floor_pos = []

    def start(self):
        self.master = Tk()
        self.master.title("AI elevator simulation")

        self.c = Canvas(self.master,
                        width=self.cv_width,
                        height=self.cv_height)
        self.c.pack()

        self.generate_floors()
        self.floor_pos.reverse()
        self.master.bind('<Escape>', lambda e: self.master.destroy())
        self.master.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.master.mainloop()

    def on_closing(self):
        self.master.destroy()

    def tick(self):
        if not self.running:
            return
        self.c.delete("all")
        self.draw_environment()

    def generate_floors(self):
        """This will create the coordinates of the floor lines and add them
        to the floor_pos array in the form of x1, y1, x2, y2 where y1 and y2
        are the same values"""
        for i in range(self.environment.number_of_floors):
            self.floor_pos.append([
                self.cv_width / 2, self.padding + self.floor_margin * i,
                self.cv_width, self.padding + self.floor_margin * i
            ])

    def draw_environment(self):
        # Draw Floors
        for i in range(len(self.floor_pos)):
            self.c.create_line(self.floor_pos[i][0],
                               self.floor_pos[i][1],
                               self.floor_pos[i][2],
                               self.floor_pos[i][3],
                               fill="white")
            self.c.create_text(self.floor_pos[i][0] - 20,
                               self.floor_pos[i][1],
                               fill="black",
                               font="Times 16 italic bold",
                               text=str(i))  # Floor Number Text
            self.c.create_text(
                self.floor_pos[i][0] - 180,
                self.floor_pos[i][1] - 50,
                fill="black",
                font="Times 15 italic bold",
                text="Waiting persons: " +
                str(len(self.environment.floors[i].waiting_queue)))

        # Draw Elevators
        for i, elevator in enumerate(self.environment.elevators):
            x1 = self.floor_pos[elevator.current_floor][0] + i * 60 + 10
            x2 = x1 + 50
            y2 = self.floor_pos[elevator.current_floor][1]
            y1 = y2 - (self.floor_margin / 2)

            my = y2 - 25
            mx = x2 - 25

            self.c.create_rectangle(x1, y1, x2, y2, fill="red")
            self.c.create_text(mx,
                               my,
                               fill="white",
                               font="Times 10 italic bold",
                               text="{}/{}".format(
                                   len(elevator.passenger_in_elevator),
                                   elevator.capacity))
Пример #55
0
class Visual(object):
    def __init__(self, width=800, height=600):
        root = Tk()
        self.root = root
        self.margin = 0.12*height
        self.width, self.height = width, height - self.margin
        self.cx, self.cy = width/2, (height - self.margin)/2
        self.toolbar = \
            Canvas(self.root, width=self.width, height=self.margin)
        self.toolbar.pack()
        self.canvas = Canvas(root, width=width, height=height - self.margin)
        self.canvas.pack()
        self.init_animation()
        root.bind("<Button-1>", lambda e: self.mouse_event(e))
        root.bind("<Key>", lambda e: self.key_event(e))
        root.mainloop()

    def draw_users(self):
        """Draw all users"""
        for user in self.users:
            user.draw()

    def draw_connections(self):
        """Draw all of user's connections"""
        for user in self.users:
            user.draw_students()

    def draw_start_screen(self):
        """Start screen text"""
        self.canvas.delete(ALL)
        cx, cy = self.width/2, self.height/2
        font = ("Impact", "128")
        self.canvas.create_text(cx, 0.8*cy, text="INFECTION", font=font)
        font = ("Impact", 32)
        self.canvas.create_text(cx, 1.5*cy, text="Press s to Begin", font=font)

    def draw_setup_screen(self):
        """User setup screen"""
        self.canvas.delete(ALL)
        cx, cy = self.width/2, self.height/2
        text = "Number of Users (1-{})".format(self.max_users)
        font = ("Impact", 24)
        self.canvas.create_text(cx, 0.4*cy, text=text, font=font)
        self.num_users_entry = Entry(self.canvas, justify=CENTER)
        self.canvas.create_window(cx, 0.5*cy, window=self.num_users_entry)
        self.num_users_entry.insert(0, str(self.default_users))

        text = "Number of Coaches"
        self.canvas.create_text(cx, 0.6*cy, text=text, font=font)
        self.num_coaches_entry = Entry(self.canvas, justify=CENTER)
        self.canvas.create_window(cx, 0.7*cy, window=self.num_coaches_entry)
        self.num_coaches_entry.insert(0, str(self.default_coaches))

        text = "Max Number of Students"
        self.canvas.create_text(cx, 0.8*cy, text=text, font=font)
        self.num_students_entry = Entry(self.canvas, justify=CENTER)
        self.canvas.create_window(cx, 0.9*cy, window=self.num_students_entry)
        self.num_students_entry.insert(0, str(self.default_students))

        self.button = Button(cx, 1.5*cy, 0.3*cx, 0.2*cy, "Begin")
        self.button.draw(self.canvas)

    def draw_toolbar(self):
        """Toolbar for main animation"""
        self.toolbar.create_text(self.cx, 0.1*self.cy, text="INFECTION",
                                 font=("Impact", 32))
        self.toolbar.create_text(self.cx*0.05, 0.1*self.cy,
                                 text="Total Infection: Click User",
                                 font=("Impact", 20), anchor="w")
        self.toolbar.create_text(self.cx*1.8, 0.1*self.cy,
                                 text="Limited Infection",
                                 font=("Impact", 20), anchor="e")
        self.limited_entry = Entry(self.toolbar, justify=CENTER, width=3)
        self.toolbar.create_window(self.cx*1.85, 0.1*self.cy,
                                   window=self.limited_entry)
        self.limited_entry.insert(0, str(self.default_users//2))
        cx, cy = self.cx*1.95, self.margin*0.35
        r = self.margin/5
        self.limited_button = (cx, cy, r)
        self.toolbar.create_oval((cx-r, cy-r, cx+r, cy+r), width=2, fill="RED")
        self.toolbar.create_text(cx, cy, text="X", font=("Courier Bold", 30))
        side = self.width/self.versions
        self.side = side
        y = 50
        self.gradient = (y, y+side)
        for col in range(int(self.versions)):
            fill = self.get_fill(col)
            width = 2 if col == self.version else 0
            self.toolbar.create_rectangle(col*side, y, (col+1)*side, y+side,
                                          fill=fill, width=width)
        self.select_version()

    def redraw_all(self):
        """Refresh frame for infection animation"""
        self.canvas.delete(ALL)
        # Draw connections first so circles get drawn on top of lines
        self.draw_connections()
        self.draw_users()

    def init_users(self):
        """Initializes list of VisualUser objects from users"""
        for user in self.raw_users:
            self.users.append(VisualUser(user, self))

    def update_locations(self):
        """Update locations of all users"""
        for user in self.users:
            user.update_location()

    def get_fill(self, v):
        """
        Convert version number into RGB hex value

        Creates gradient covering range of colors
        """
        if v is None:
            return "white"
        b = 0
        quarter = self.versions/4
        if v < quarter:  # Red -> Yellow
            r = 255
            g = int(255*min((v/quarter), 1))
        elif quarter <= v < 2*quarter:  # Yellow -> Green
            r = int(255*max(0, (1-(v-quarter)/quarter)))
            g = 255
        elif 2*quarter <= v < 3*quarter:  # Green -> Blue
            r = 0
            g = int(255*max(0, (1-(v-2*quarter)/quarter)))
            b = int(255*min(((v-2*quarter)/quarter), 1))
        else:  # Blue -> Purple
            g = 0
            r = int(255*min(((v-3*quarter)/quarter), 1))
            b = 255
        return "#{:02x}{:02x}{:02x}".format(r, g, b)

    def draw_random_point(self):
        """Draw randomly colored point on screen"""
        fill = self.get_fill(self.start_counter % 100)
        self.start_counter += 1
        x = random.randint(0, self.width)
        y = random.randint(0, self.height)
        self.canvas.create_rectangle(x, y, x+2, y+2, width=0, fill=fill)

    def timer_fired(self):
        """Called every frame refresh"""
        if self.mode == Mode.START:
            for _ in range(10):
                self.draw_random_point()
        if self.mode == Mode.MAIN and not self.paused:
            self.update_locations()
            self.redraw_all()

    def timer(self):
        """Setup timer loop"""
        self.timer_fired()
        self.canvas.after(self.timer_delay, self.timer)

    def init_animation(self):
        """Initialize or reset animation"""
        self.users = []
        self.timer_delay = 100
        self.start_counter = 0
        self.versions = 40
        self.default_users = 20
        self.default_coaches = 5
        self.default_students = 5
        self.max_users = 100
        self.version = None
        self.paused = False
        self.mode = Mode.START
        self.draw_start_screen()
        self.error_text = None
        self.error_font_size = 20
        self.version_select = None
        self.timer()

    def start_infection(self):
        """Initialize users and start infections"""
        num_users_text = self.num_users_entry.get()
        num_coaches_text = self.num_coaches_entry.get()
        num_students_text = self.num_students_entry.get()
        try:
            error = "Invalid Number of Users"
            num_users = int(num_users_text)
            if not (1 <= num_users <= self.max_users):
                raise ValueError
            num_coaches = int(num_coaches_text)
            error = "Invalid Number of Coaches"
            if not (1 <= num_coaches <= num_users):
                raise ValueError
            error = "Invalid Number of Students"
            num_students = int(num_students_text)
            if not (1 <= num_students <= num_users):
                raise ValueError
        except ValueError:
            if self.error_text:
                self.canvas.delete(self.error_text)
            self.error_text = \
                self.canvas.create_text(self.cx, 0.2*self.cy,
                                        text=error,
                                        font=("Impact", self.error_font_size))
            self.error_font_size += 2
            return
        self.infection = Infection(num_users=num_users, num_coaches=num_coaches,
                                   students=(1, num_students))
        self.num_users = num_users
        self.num_coaches = num_coaches
        self.num_students = num_students
        self.raw_users = self.infection.network.users
        self.init_users()
        self.draw_toolbar()
        self.mode = Mode.MAIN

    def limited_infection(self):
        size_text = self.limited_entry.get()
        try:
            size = int(size_text)
            if not (1 <= size <= self.num_users):
                raise ValueError
        except ValueError:
            print("Bad input")  # TODO: display to user
            return
        self.infection.limited_infection(size, self.version)
        print("Limited infection of size", size, self.num_users)

    def select_version(self):
        if self.version_select:  # Erase old selection
            self.toolbar.delete(self.version_select)
        if self.version is None:
            return
        y0, y1 = self.gradient
        x0, x1 = self.version*self.side, (self.version + 1)*self.side
        self.version_select = \
            self.toolbar.create_rectangle(x0, y0, x1, y1, width="2")

    def mouse_event(self, e):
        """Process click event"""
        x, y = e.x, e.y
        if self.mode == Mode.SETUP:
            if self.button.clicked(x, y):
                self.start_infection()
        if self.mode == Mode.MAIN:
            cx, cy, r = self.limited_button
            if distance(cx, cy, x, y) < r:
                self.limited_infection()
            elif self.gradient[0] <= y <= self.gradient[1]:
                print("gradient bar", x)
                self.version = int(x / self.side)
                print(self.versions, self.version)
                self.select_version()
            else:
                for user in self.users:
                    if user.clicked(x, y):
                        print("user clicked", user)
                        user.infect()
                        break

    def key_event(self, e):
        """Process keyboard event"""
        if e.keysym == 'r':
            self.init_animation()
            self.paused = False
        elif e.keysym == 'p':
            self.paused = not self.paused
        elif e.keysym == 's' and self.mode == Mode.START:
            self.mode = Mode.SETUP
            self.draw_setup_screen()
        elif e.keysym == 'b' and self.mode == Mode.SETUP:
            self.start_infection()
        elif e.keysym == 'q':
            self.root.destroy()
Пример #56
0
            for index in range(len(s.segments) - 1):
                if head_coords == c.coords(s.segments[index].instance):
                    IN_GAME = False
        root.after(100, main)

    # Если не в игре выводим сообщение о проигрыше
    else:
        set_state(game_over_text, 'normal')


def start_game():
    global s
    create_block()
    s = create_snake()

    c.bind("<KeyPress>", s.change_direction)
    main()


game_over_text = c.create_text(WIDTH / 2,
                               HEIGHT / 2,
                               text="GAME OVER!",
                               font='Arial 20',
                               fill='red',
                               state='hidden')

start_game()

# Запускаем окно
root.mainloop()
Пример #57
0
class Plot:

    def __init__(self, root, grid, title='', boxsize=[], width=800, height=800):
        
        if boxsize:
            self.xmin, self.ymin, self.xmax, self.ymax = boxsize
        else:
            self.xmin, self.ymin, self.xmax, self.ymax = grid.boxsize()
        self.width = width
        self.height = height
        self.title = title
        self.grid = grid
    
        self.frame = Frame(root)
        self.frame.pack()
        self.canvas = Canvas(bg="white", width=width, height=height)
        self.canvas.pack()

    def draw(self, rho, the, xyPath=[]):
        
        border_x, border_y = 0.2, 0.2
        scale = min((1.-border_x)*self.width/(self.xmax-self.xmin), \
                    (1.-border_y)*self.height/(self.ymax-self.ymin))
        a = max(border_x * self.width/2., (self.width-scale*(self.xmax-self.xmin))/2.)
        b = max(border_y * self.height/2.,(self.height-scale*(self.ymax-self.ymin))/2.)
    
        box_pix = (a, self.height-scale*(self.ymax-self.ymin) - b,
                   scale*(self.xmax-self.xmin) + a, self.height - b)
        # draw the box
        self.addBox((self.xmin, self.ymin, self.xmax, self.ymax), box_pix)
    
        # color plot
        cells = cell.cell(self.grid)
        for index in range(len(cells.data)):
                ia, ib, ic = cells.data[index]
                xa, ya = scale*(self.grid.x(ia)-self.xmin) + a, \
                         self.height -scale*(self.grid.y(ia)-self.ymin) - b
                xb, yb = scale*(self.grid.x(ib)-self.xmin) + a, \
                         self.height -scale*(self.grid.y(ib)-self.ymin) - b
                xc, yc = scale*(self.grid.x(ic)-self.xmin) + a, \
                         self.height -scale*(self.grid.y(ic)-self.ymin) - b

                rhoAbc = (rho[ia] + rho[ib] + rho[ic])/3.0
                theAbc = (the[ia] + the[ib] + the[ic])/3.0
                color = colormap(rhoAbc, theAbc)
                self.canvas.create_polygon(xa, ya, xb, yb, xc, yc, fill=color)
        
        # add path if present
        index = 0
        for (x, y) in xyPath:
            xa, ya = scale*(x - self.xmin) + a, \
                self.height -scale*(y - self.ymin) - b
            self.canvas.create_oval(xa-5, ya-5,
                                    xa+5, ya+5)
            #self.canvas.create_text(xa+2, ya+1, text=str(index))
            index += 1
    
        # add title
        x, y = self.width/3., self.height/15.0
        self.canvas.create_text(x, y, text=str(self.title),
                                font =("Helvetica", 24),
                                fill='black')


    def addBox(self, xxx_todo_changeme, xxx_todo_changeme1):
        """
        Add Box. Min/Max coordinates are in pixels.
        """
        (self.xmin,self.ymin,self.xmax,self.ymax) = xxx_todo_changeme
        (self.xmin_pix, self.ymin_pix, self.xmax_pix, self.ymax_pix) = xxx_todo_changeme1
        self.canvas.create_line(self.xmin_pix, self.ymax_pix, self.xmax_pix, self.ymax_pix)
        self.canvas.create_text(self.xmin_pix   ,self.ymax_pix+ 8, text=('%4.1f' % self.xmin))
        self.canvas.create_text(self.xmin_pix-12,self.ymax_pix   , text=('%4.1f' % self.ymin))
        self.canvas.create_line(self.xmax_pix, self.ymax_pix, self.xmax_pix, self.ymin_pix)
        self.canvas.create_text(self.xmax_pix   ,self.ymax_pix+ 8, text=('%4.1f' % self.xmax))
        self.canvas.create_line(self.xmax_pix, self.ymin_pix, self.xmin_pix, self.ymin_pix)
        self.canvas.create_text(self.xmin_pix-12,self.ymin_pix   , text=('%4.1f' % self.ymax))
        self.canvas.create_line(self.xmin_pix, self.ymin_pix, self.xmin_pix, self.ymax_pix)
Пример #58
0
    return (x, y)


root = Tk()
root.title("Polar Plot Demo")
c = Canvas(width=width, height=height, bg='white')
c.pack()

# draw radial lines at interval of 15 degrees
for theta in range(0, 360, 15):
    r = 180
    x, y = x_center + math.cos(math.radians(theta))*r, \
           y_center - math.sin(math.radians(theta)) *r
    c.create_line(x_center, y_center, x, y, fill='green', dash=(2, 4),\
                  activedash=(6, 5, 2, 4) )
    c.create_text(x, y, anchor=W, font="Purisa 8", text=str(theta) + '°')

# draw concentric_circles
for radius in range(1, 4):
    x_max = x_center + radius * scaling_factor
    x_min = x_center - radius * scaling_factor
    y_max = y_center + radius * scaling_factor
    y_min = y_center - radius * scaling_factor
    c.create_oval(x_max, y_max, x_min, y_min, width=1, outline='grey', \
                  dash=(2, 4), activedash=(6, 5, 2, 4))

for theta in range(0, 3000):
    r = 2 * math.sin(2 * theta)
    # a few equations that look good on polar plot -
    # uncomment one line at a time to see the individual plots
    # also change parameters of equations to see their effect on the plots
Пример #59
0
class Visual(Frame):
    '''Class that takes a world as argument and present it graphically
    on a tkinter canvas.'''

    def __init__(self):
        '''
        Sets up a simulation GUI in tkinter.
        '''
        Frame.__init__(self)
        self.master.title("The Schelling Segregation Model in Python")
        self.master.wm_resizable(0, 0)
        self.grid()
        self.movement_possible = True

        # --------------------------------------- #
        # --------- FRAMES FOR GUI -------------- #
        # --------------------------------------- #

        # The pane for user values
        self._entryPane = Frame(self,
                                borderwidth=5,
                                relief='sunken')
        self._entryPane.grid(row=0, column=0, sticky='n')

        # The buttons pane
        self._buttonPane = Frame(self, borderwidth=5)
        self._buttonPane.grid(row=1, column=0, sticky='n')

        # A temp pane where graph is located, just for cosmetic reasons
        width, height = 425, 350
        self._graph = Canvas(self,
                             width=width,
                             height=height,
                             background="black")
        self._graph.configure(relief='sunken', border=2)
        self._graph.grid(row=3, column=0)

        # The pane where the canvas is located
        self._animationPane = Frame(self,
                                    borderwidth=5,
                                    relief='sunken')
        self._animationPane.grid(row=0, column=1,
                                 rowspan=4, pady=10,
                                 sticky="n")

        # --------------------------------------- #
        # --------- FILLING THE FRAMES ---------- #
        # --------------------------------------- #

        self._canvas()      # Create graphics canvas
        self._entry()       # Create entry widgets
        self._buttons()     # Create button widgets

    def _plot_setup(self, time):
        '''Method for crudely annotating the graph window.'''
        time = time

        # Main plot
        width, height = 425, 350
        y0 = -time/10
        self._graph = Canvas(self, width=width,
                             height=height,
                             background="black",
                             borderwidth=5)
        self._graph.grid(row=3, column=0)
        self.trans = Plotcoords(width, height, y0, -0.2, time, 1.3)

        x, y = self.trans.screen(time // 2, 1.2)
        x1, y1 = self.trans.screen(time // 2, 1.13)
        self._graph.create_text(x, y,
                                text="% Happy",
                                fill="green",
                                font="bold 12")
        
        self._graph.create_text(x1, y1,
                                text="% Unhappy",
                                fill="red",
                                font="bold 12")
 
        # Line x-axis
        x, y = self.trans.screen((-5 * (time / 100)), -0.05)
        x1, y = self.trans.screen(time, -0.05)
        self._graph.create_line(x, y, x1, y, fill="white", width=1.5)
         
        # Text x-axis
        x_text, y_text = self.trans.screen(time / 2, -0.15)
        self._graph.create_text(x_text, y_text,
                                text="Time",
                                fill="white",
                                font="bold 12")

        # Line y-axis
        x, y = self.trans.screen((-0.5 * (time / 100)), -0.05)
        x, y1 = self.trans.screen((-5 * (time / 100)), 1)
        self._graph.create_line(x, y, x, y1, fill="white", width=1.5)
 
    def _entry(self):
        '''Method for creating widgets for collecting user input.'''
         
        # N (no of turtles)
        dim = 30*30

        self.fill_label = Label(self._entryPane,
                                anchor='w',
                                justify='left',
                                text='Fill',
                                relief='raised',
                                width=12,
                                height=1,
                                font='italic 20')
        
        self.fill_label.grid(row=0, column=1, ipady=14)

        self.fill = Scale(self._entryPane,
                          from_=0,
                          to=1,
                          resolution=0.01,
                          bd=3,
                          relief='sunken',
                          orient='horizontal',
                          length=235,
                          tickinterval=20)
        self.fill.grid(row=0, column=2)
        self.fill.set(0.8)
                           
        self._N_label = Label(self._entryPane,
                              anchor='w',
                              justify='left',
                              text="N:",
                              relief='raised',
                              width=12,
                              height=1,
                              font="italic 20")
        self._N_label.grid(row=1, column=1, ipady=14)

        self._N = Scale(self._entryPane,
                        from_=0,
                        to=100,
                        resolution=1,
                        bd=3,
                        relief='sunken',
                        orient='horizontal',
                        length=235,
                        tickinterval=20)
        self._N.set(30)
        self._N.grid(row=1, column=2)

        # Ticks (length of simulation)
        self._Ticks_label = Label(self._entryPane,
                                  anchor='w',
                                  justify='left',
                                  text="Time:",
                                  relief='raised',
                                  width=12,
                                  height=1,
                                  font="bold 20")
        self._Ticks_label.grid(row=2, column=1, ipady=14)
 
        self._Ticks = Scale(self._entryPane,
                            from_=10,
                            to=1000,
                            resolution=1,
                            bd=3,
                            relief='sunken',
                            orient='horizontal',
                            length=235,
                            tickinterval=990)
        self._Ticks.set(500)
        self._Ticks.grid(row=2, column=2)
 
        # % similar wanted
        self._Similar_label = Label(self._entryPane,
                                    anchor='w',
                                    justify='left',
                                    text="Similar wanted:",
                                    relief='raised',
                                    width=12,
                                    height=1,
                                    font="bold 20")
         
        self._Similar_label.grid(row=3, column=1, ipady=14)
 
        self._Similar = Scale(self._entryPane,
                              from_=0.0,
                              to=1.0,
                              resolution=0.01,
                              bd=3,
                              relief='sunken',
                              orient='horizontal',
                              length=235,
                              tickinterval=0.5)
        self._Similar.set(0.76)
        self._Similar.grid(row=3, column=2)

        # Delay between steps
        self._delay_label = Label(self._entryPane,
                                  anchor='w',
                                  justify='left',
                                  text="Delay (s):",
                                  relief='raised',
                                  width=12,
                                  height=1,
                                  font="bold 20")
         
        self._delay_label.grid(row=4, column=1, ipady=14)
 
        self._delay = Scale(self._entryPane,
                            from_=0.0,
                            to=1.0,
                            resolution=0.01,
                            bd=3,
                            relief='sunken',
                            orient='horizontal',
                            length=235,
                            tickinterval=0.5)
        self._delay.set(0.15)
        self._delay.grid(row=4, column=2)

    def _buttons(self):
        '''Method for creating button widgets for setting up,
        running and plotting results from simulation.'''
        width = 7
        height = 1

        # The 'Setup' button
        self._setupButton = Button(self._buttonPane,
                                   text="Setup",
                                   command=self._setup,
                                   width=width,
                                   height=height,
                                   font="bold 30",
                                   relief='raised',
                                   borderwidth=5)
        self._setupButton.grid(row=0, column=0)

        # The 'Go' button
        self._goButton = Button(self._buttonPane,
                                text="Go",
                                command=self._go,
                                width=width,
                                height=height,
                                font="bold 30",
                                relief='raised',
                                borderwidth=5)
        self._goButton.grid(row=0, column=1)

        # The 'Quit' button
        self._quitButton = Button(self._buttonPane,
                                  text="Quit",
                                  command=self._quit,
                                  width=width,
                                  height=height,
                                  font="bold 30",
                                  relief='raised',
                                  borderwidth=5)
        self._quitButton.grid(row=1, column=0, columnspan=2)

    def _canvas(self):
        '''Creates the canvas on which everything happens.'''
        # The tick counter information
        self._Tick_counter = Label(self._animationPane,
                                   anchor='w',
                                   justify='left',
                                   text="Time:",
                                   width=5,
                                   font="bold 20")
        self._Tick_counter.grid(row=0, column=0, sticky="e")
        self._Tick_counter1 = Label(self._animationPane,
                                    justify='center',
                                    text="",
                                    relief='raised',
                                    width=5,
                                    font="bold 20")
        self._Tick_counter1.grid(row=0, column=1, sticky='w')
        self.canvas_w, self.canvas_h = 750, 750
        self.canvas = Canvas(self._animationPane,
                             width=self.canvas_w,
                             height=self.canvas_h,
                             background="black")

        self.canvas.grid(row=1, column=0, columnspan=2)

    def _setup(self):
        '''Method for 'Setup' button.'''
        # Clearing the canvas and reset the go button
        self.canvas.delete('all')
        self._goButton['relief'] = 'raised'
        self.N = int(self._N.get())
        self.Ticks = int(self._Ticks.get())
        self.similar = float(self._Similar.get())
        self.data = []
        self.tick_counter = 0
        self._Tick_counter1['text'] = str(self.tick_counter)
        self._plot_setup(self.Ticks)
        self.grid_size = self.N
        self.world = World(750, 750, self.grid_size)
        self.create_turtles()
        self.neighbouring_turtles()
        self.draw_turtles()

    def _go(self):
        '''Method for the 'Go' button, i.e. running the simulation.'''
        self._goButton['relief'] = 'sunken'
        if self.tick_counter <= self.Ticks:
            self._Tick_counter1['text'] = str(self.tick_counter)
            self.canvas.update()

            self._graph.update()
            self._graph.after(0)

            # Data collection
            turtles_unhappy = self.check_satisfaction()
            prop_happy, prop_unhappy = self.calc_prop_happy(self.tick_counter)

            self.data_collection(self.tick_counter, prop_happy, prop_unhappy)

            if self.tick_counter >= 1:

                # HAPPY values (%)
                x0 = self.tick_counter-1
                x1 = self.tick_counter

                # Collecting values from stored data
                y0 = self.data[self.tick_counter-1][1]
                y1 = self.data[self.tick_counter][1]

                # Transforming to tkinter
                x1, y1 = self.trans.screen(x1, y1)
                x0, y0 = self.trans.screen(x0, y0)
                self._graph.create_line(x0, y0, x1, y1,
                                        fill="green", width=1.3,
                                        tag="happy")  # Draw "happy lines

                # UNHAPPY values (%)
                x0 = self.tick_counter-1
                x1 = self.tick_counter

                # Collecting values from stored data
                y0 = self.data[self.tick_counter-1][2]
                y1 = self.data[self.tick_counter][2]

                # Transforming to tkinter
                x1, y1 = self.trans.screen(x1, y1)
                x0, y0 = self.trans.screen(x0, y0)
                self._graph.create_line(x0, y0, x1, y1,
                                        fill="red", width=1.1,
                                        tag="unhappy")  # Draw unhappy lines
             
            if prop_happy < 1:
                self.turtle_move(turtles_unhappy)
                time.sleep(self._delay.get())
                self.update_neighbours()
                self.tick_counter += 1
                self.canvas.after(0, self._go())

        self._goButton['relief'] = 'raised'

    def _quit(self):
        '''Method for the 'Quit' button.'''
        self.master.destroy()

    # ------------------------------------------------------ #
    # ---------- FUNCTIONS CALLED AT EACH TICK ------------- #
    # ------------------------------------------------------ #

    def turtle_move(self, unhappy_turtles):
        '''Moves all the unhappy turtles (randomly).'''
         
        while unhappy_turtles:
            i = random.randint(0, len(unhappy_turtles)-1)
            turtle = unhappy_turtles.pop(i)
            turtle.move(self)

    def update_neighbours(self):
        '''Updates the turtles neigbour attributes. Called
        after all turtles have moved.'''
        for turtle in self.turtles:
            turtle.update_neighbours()

    def check_satisfaction(self):
        '''Checks to see if turtles are happy or not.
        Returns a list of unhappy turtles, i.e. turtles
        that should move.

        Called before the move method.'''

        for turtle in self.turtles:
            turtle.is_happy()

        unhappy_turtles = []
        for element in self.turtles:
            if not element.happy:
                unhappy_turtles.append(element)

        return unhappy_turtles

    def calc_prop_happy(self, i):
        '''Calculates the proportion of happy turtles.'''
        happy = 0
        unhappy = 0

        for turtle in self.turtles:
            if turtle.happy:
                happy += 1
            else:
                unhappy += 1
        prop_happy = happy/len(self.turtles)
        prop_unhappy = unhappy/len(self.turtles)

        return prop_happy, prop_unhappy

    def data_collection(self, i, prop_happy, prop_unhappy):
        '''Method for collecting data at each tick.'''
        self.data.append((i, prop_happy, prop_unhappy))


# ------------------------------------------------------ #
# ---------- INITIALISATION FUNCTIONS ------------------ #
# ------------------------------------------------------ #

    def create_turtles(self):
        '''Method for creating a new list of turtles.

        Upon creation they are registered in the World object.'''
        if self.N*self.N <= self.grid_size*self.grid_size:
            counter = 0
            self.turtles = []
            while counter < self.N * self.N * self.fill.get():
                             
                s = "S"+str(counter)
                if counter <= int(self.N * self.N * self.fill.get() / 2):
                    color = "green"
                else:
                    color = "red"

                x = random.randint(0, self.grid_size-1)
                y = random.randint(0, self.grid_size-1)

                if not self.world.patch_list[x][y]:
                    new_turtle = Schelling(world=self.world,
                                           x=x,
                                           y=y,
                                           s=s,
                                           color=color,
                                           similar_wanted=self.similar)

                    self.world.register(new_turtle)
                    counter += 1
                    self.turtles.append(new_turtle)
        else:
            print("Number of turtles exceeds world!")

    def draw_turtles(self):
        '''Method for drawing turtles on canvas.

           Calls each turtle's own method for drawing.'''
        for turtle in self.turtles:
            turtle.draw(self.canvas)
 
    def neighbouring_turtles(self):
        '''Method for updating turtles' neighbours.

           Calls on each turtle's own method for updating neighbours.'''
        for turtle in self.turtles:
            turtle.get_neighbouring_patches()
Пример #60
0
class SudokuGUI(Frame):
    def __init__(self, parent, game):
        self.game = game
        self.parent = parent
        Frame.__init__(self, parent)

        self.row, self.col = 0, 0

        self.__initUI()

    def __initUI(self):
        self.parent.title("Sudoku")
        self.pack(fill=BOTH, expand=1)
        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)
        solve_button = Button(self, text="Solve", command=self.__solve)
        solve_button.pack(fill=BOTH, side=BOTTOM)

        self.__draw_grid()
        self.__draw_puzzle()
        self.updater()

        #self.canvas.bind("<Button-1>", self.__cell_clicked)
        #self.canvas.bind("<Key>", self.__key_pressed)

    def __draw_grid(self):
        """
        Draws grid divided with blue lines into 3x3 squares
        """
        for i in range(10):
            color = "blue" if i % 3 == 0 else "gray"

            x0 = MARGIN + i * SIDE
            y0 = MARGIN
            x1 = MARGIN + i * SIDE
            y1 = HEIGHT - MARGIN
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

            x0 = MARGIN
            y0 = MARGIN + i * SIDE
            x1 = WIDTH - MARGIN
            y1 = MARGIN + i * SIDE
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

    def __draw_puzzle(self):
        self.canvas.delete("numbers")
        for i in range(9):
            for j in range(9):
                answer = self.game[i][j]
                if answer != 0:
                    x = MARGIN + j * SIDE + SIDE / 2
                    y = MARGIN + i * SIDE + SIDE / 2
                    #original = self.game.start_puzzle[i][j]
                    #color = "black" if answer == original else "sea green"
                    self.canvas.create_text(
                        #x, y, text=answer, tags="numbers", fill=color
                        x,
                        y,
                        text=answer,
                        tags=f"numbers{x}{y}",
                        fill="green")

    def __solve(self):
        _thread.start_new_thread(SudokuGame.solve, (0, 0))
        print("Startet Thread")

    def update_puzzle(self):
        for i in range(9):
            for j in range(9):
                answer = board[i][j]
                if answer != 0:
                    x = MARGIN + j * SIDE + SIDE / 2
                    y = MARGIN + i * SIDE + SIDE / 2
                    #original = self.game.start_puzzle[i][j]
                    #color = "black" if answer == original else "sea green"
                    if (not given[i][j]):
                        self.canvas.delete(f"numbers{x}{y}")
                        self.canvas.create_text(
                            #x, y, text=answer, tags="numbers", fill=color
                            x,
                            y,
                            text=answer,
                            tags=f"numbers{x}{y}",
                            fill="black")

    def updater(self):
        self.update_puzzle()
        self.after(1, self.updater)