Beispiel #1
0
 def draw(self, win):
     if(self.wall):
         self.square.setFill(color_rgb(55, 55, 55))
     else:
         self.square.setFill(color_rgb(230,230,230))
     self.square.undraw()
     self.square.draw(win)
Beispiel #2
0
def main():

    # create the application window
    win = GraphWin("Dice Roller")
    win.setCoords(0,0,10,10)
    win.setBackground("gray")

    # draw the interface widgets
    die1 = DieView(win, Point(3,7), 2)
    die2 = DieView(win, Point(7,7), 2)
    rollButton = Button(win, Point(5,4.5), 6, 1, "Roll Dice")
    rollButton.activate()
    quitButton = Button(win, Point(5,1), 2, 1, "Quit")

    # event loop
    pt = win.getMouse()
    while not quitButton.clicked(pt):
        if rollButton.clicked(pt):
            # re-rolling value and pip color of die1
            value1 = randrange(1, 7)
            color = color_rgb(randrange(0,256), randrange(0,256), randrange(0,256))
            die1.setValue(value1)
            die1.setColor(color)
            # re-rolling value and pip color of die2
            value2 = randrange(1, 7)
            color = color_rgb(randrange(0,256), randrange(0,256), randrange(0,256))
            die2.setValue(value2)
            die2.setColor(color)
            quitButton.activate()
        pt = win.getMouse()

    # close up shop
    win.close()
Beispiel #3
0
 def draw_neuron_help(self,
                      neuron_layer,
                      lay,
                      markersize=7,
                      colscale=1,
                      first=False):
     x = Game.x0 + (lay + 1) * Game.space
     ys = np.linspace(Game.y0, Game.ymax, Game.num_nodes[lay] + 2)[1:-1]
     if not first:
         mx = max(np.max(neuron_layer), 0.01)
         cmap = self.neuron_col
     else:
         mx = 250
         cmap = self.neuron_col_r
         neuron_layer[0] += 125
     for i in range(len(neuron_layer)):
         disc = 100
         val = int(disc * neuron_layer[i] * colscale /
                   mx)  #you can choose to only update
         if True:  #val != self.neur_vals_disc[lay][i]: #neurons when they look different than before
             try:  #to advance frames faster
                 self.neur_circs[lay][i].undraw()
             except:
                 pass
             col = (255 * np.asarray(cmap(val / disc)[0:3])).astype(int)
             self.neur_circs[lay][i] = g.Circle(g.Point(x, ys[i]),
                                                radius=15)
             self.neur_circs[lay][i].setOutline(g.color_rgb(*col))
             self.neur_circs[lay][i].setFill(g.color_rgb(*col))
             self.neur_circs[lay][i].draw(self.win)
             self.neur_vals_disc[lay][i] = val
Beispiel #4
0
    def __init__(self,
                 pos,
                 width,
                 height,
                 type=None,
                 bc=color_rgb(255, 255, 255),
                 text="",
                 size=18,
                 txtc=color_rgb(0, 0, 0),
                 style="normal",
                 font="arial"):

        oWidth = width / 2  #offset width
        oHeight = height / 2  #offset height

        pos1 = Point(pos.getX() - oWidth, pos.getY() - oHeight)
        pos2 = Point(pos.getX() + oWidth, pos.getY() + oHeight)

        self.object = Rectangle(pos1, pos2)
        self.object.setFill(bc)
        self.object.setOutline(color_rgb(255, 255, 255))
        self.pos = pos
        self.pos1 = pos1  #Left-Up Corner
        self.pos2 = pos2  #Right-Down Corner
        self.type = type
        self.width = width
        self.height = height

        self.text = Text(self.object.getCenter(), text, size, txtc, style,
                         font)
Beispiel #5
0
def draw_house():
    house_body = gr.Rectangle(gr.Point(200, 220), gr.Point(400, 420))
    house_body.setFill(gr.color_rgb(200, 180, 140))
    house_body.setOutline(gr.color_rgb(160, 140, 100))
    house_body.setWidth(5)
    house_body.draw(window)

    house_roof = gr.Polygon(gr.Point(190, 220), gr.Point(300, 110),
                            gr.Point(410, 220))
    house_roof.setFill(gr.color_rgb(140, 25, 30))
    house_roof.setOutline(gr.color_rgb(100, 5, 10))
    house_roof.setWidth(5)
    house_roof.draw(window)

    house_window = gr.Rectangle(gr.Point(250, 260), gr.Point(350, 360))
    house_window.setFill(gr.color_rgb(132, 205, 255))
    house_window.setWidth(5)
    house_window.draw(window)

    line1 = gr.Line(gr.Point(300, 260), gr.Point(300, 360))
    line2 = gr.Line(gr.Point(250, 310), gr.Point(350, 310))

    line1.setWidth(5)
    line2.setWidth(5)

    line1.draw(window)
    line2.draw(window)
def bird_init(x, y, scale):
    """ Create the list of objects needed to draw a bird
		at position (x,y) with the given scale """

    bird = []
    '''separate rectangles triangle and circle for the 
		body of the bird, beak, and legs'''

    body = gr.Rectangle(gr.Point(x, y), gr.Point(x + scale * 75,
                                                 y + scale * 25))
    body.setFill(gr.color_rgb(107, 142, 35))
    bird.append(body)

    leg1 = gr.Rectangle(gr.Point(x, y + 25 * scale),
                        gr.Point(x + scale * 10, y + 40 * scale))
    leg1.setFill(gr.color_rgb(95, 158, 160))
    bird.append(leg1)

    leg2 = gr.Rectangle(gr.Point(x + 30, y + 25 * scale),
                        gr.Point(x + scale * 40, y + 40 * scale))
    leg2.setFill(gr.color_rgb(95, 158, 160))
    bird.append(leg2)

    head = gr.Circle(gr.Point(x + 75 * scale, y - 5 * scale), 15)
    head.setFill(gr.color_rgb(127, 255, 215))
    bird.append(head)

    beak = gr.Polygon(gr.Point(x + 85 * scale, y * scale),
                      gr.Point(x + scale * 105, y - scale * 10),
                      gr.Point(x + scale * 85, y - scale * 20))
    beak.setFill(gr.color_rgb(255, 215, 0))
    bird.append(beak)

    return bird
def landscape_init(x, y, scale):
    """ Create the list of objects needed to draw a landscape
		at position (x,y) with the given scale """

    shapes = []
    '''3 rectangle and 1 circle for different parts of 
		landscape like sky, sun, grass, and water'''

    sky = gr.Rectangle(gr.Point(x, y - 500 * scale),
                       gr.Point(x + scale * 1000, y + scale * 500))
    sky.setFill(gr.color_rgb(135, 206, 235))
    shapes.append(sky)

    sun = gr.Circle(gr.Point(x + 200 * scale, y - 250 * scale), 70)
    sun.setFill(gr.color_rgb(255, 69, 0))
    shapes.append(sun)

    grass = gr.Rectangle(gr.Point(x, y),
                         gr.Point(x + scale * 450, y + scale * 350))
    grass.setFill(gr.color_rgb(0, 128, 0))
    shapes.append(grass)

    water = gr.Rectangle(gr.Point(x + scale * 450, y),
                         gr.Point(x + scale * 1000, y + scale * 700))
    water.setFill(gr.color_rgb(70, 130, 180))
    shapes.append(water)

    return shapes
Beispiel #8
0
def draw_background(palette: GraphWin):
    _height = palette.getHeight()
    _width = palette.getWidth()

    sky_percentage = 0.7

    sky = get_rectangle(gr.Point(0, _height * sky_percentage), _width, _height * sky_percentage)
    land = get_rectangle(gr.Point(0, _height), _width, _height * (1 - sky_percentage))
    sun = gr.Circle(gr.Point(_width * 0.85, _height * 0.15), _height * 0.1)

    sky.setFill(gr.color_rgb(0, 0, 200))
    land.setFill(gr.color_rgb(80, 240, 20))
    sun.setFill(gr.color_rgb(255, 255, 0))

    sky.draw(palette)
    land.draw(palette)
    sun.draw(palette)

    sky_shift = _height * 0.15
    for i in range(5):
        cloud = gr.Circle(gr.Point(0 + sky_shift, _height * 0.15), _height * 0.05)
        cloud.setFill(gr.color_rgb(255, 255, 255))
        cloud.draw(palette)
        sky_shift += _height * 0.1 / 2
    sky_shift = _height * 0.175
    for i in range(4):
        cloud = gr.Circle(gr.Point(0 + sky_shift, _height * 0.10), _height * 0.05)
        cloud.setFill(gr.color_rgb(255, 255, 255))
        cloud.draw(palette)
        sky_shift += _height * 0.1 / 2
Beispiel #9
0
    def display_inspection(self):
        subprocess.check_output([
            "dconf", "write",
            "/org/compiz/profiles/unity/plugins/unityshell/launcher-hide-mode",
            "1"
        ])
        time.sleep(1)
        monitor = get_monitors()[0]

        window = gx.GraphWin("Window Test", monitor.width, monitor.height)
        window.setBackground(gx.color_rgb(0, 0, 0))

        window.getMouse()
        window.setBackground(gx.color_rgb(255, 0, 0))

        window.getMouse()
        window.setBackground(gx.color_rgb(0, 0, 255))

        window.getMouse()
        window.setBackground(gx.color_rgb(255, 255, 255))

        window.getMouse()
        window.close()
        subprocess.check_output([
            "dconf", "write",
            "/org/compiz/profiles/unity/plugins/unityshell/launcher-hide-mode",
            "0"
        ])
Beispiel #10
0
def landscape_init( x, y, scale):
	""" Create the list of objects needed to draw a landscape
		at position (x,y) with the given scale """

	shapes = []
	
	'''3 rectangle and 1 circle for different parts of 
		landscape like sky, sun, grass, and water'''
	
	sky = gr.Rectangle( gr.Point(x,y-500*scale), gr.Point(x+scale*1000, y+scale*500) )
	sky.setFill(gr.color_rgb( 135, 206, 235))
	shapes.append( sky )
	
	sun = gr.Circle( gr.Point(x+200*scale,y-250*scale), 70)
	sun.setFill( gr.color_rgb(255, 69, 0))
	shapes.append( sun )
	
	grass = gr.Rectangle( gr.Point(x,y), gr.Point(x+scale*450, y+scale*350) )
	grass.setFill(gr.color_rgb( 0, 128, 0))
	shapes.append( grass )
	
	water= gr.Rectangle( gr.Point(x+scale*450, y), gr.Point(x+scale*1000, y+scale*700) )
	water.setFill(gr.color_rgb( 70, 130, 180))
	shapes.append( water )
	
	return shapes
def get_image_path():
    width, height = 300, 150
    win = GraphWin("Image Path", width, height)
    win.setBackground(color_rgb(0, 0, 0))

    path_entry = Entry(Point(width // 2, height // 2 - 50), 30)
    path_entry.draw(win)

    ok_button = Rectangle(Point(width - 50, height - 50),
                          Point(width - 5, height - 5))
    ok_button.setFill(color_rgb(255, 255, 255))
    ok_button.draw(win)
    ok_button_text = Text(ok_button.getCenter(), "OK")
    ok_button_text.setSize(15)
    ok_button_text.draw(win)

    while True:
        click = win.getMouse()
        clickx = click.getX()
        clicky = click.getY()

        if ok_button.getP1().getX() <= clickx <= ok_button.getP2().getX(
        ) and ok_button.getP1().getY() <= clicky <= ok_button.getP2().getY():
            win.close()
            return str(path_entry.getText())
Beispiel #12
0
def main():
    #create the application window
    win = GraphWin("Dice Roller")
    win.setCoords(0, 0, 10, 10)
    win.setBackground("green2")

    #Draw the interface widgets
    die1 = DieView(win, Point(3, 7), 2)
    die2 = DieView(win, Point(7, 7), 2)
    rollButton = Button(win, Point(5, 4.5), 5, 1, "Roll Dice")
    rollButton.activate()
    quitButton = Button(win, Point(5, 1), 2, 1, "Quit")

    #Event loop
    pt = win.getMouse()
    while not quitButton.clicked(pt):
        r, g, b = int(random() * 255), int(random() * 255), int(random() * 255)
        if rollButton.clicked(pt):
            value1 = randrange(1, 7)
            die1.setColor(color_rgb(r, g, b))
            die2.setColor(color_rgb(r, g, b))
            die1.setValue(value1)
            value2 = randrange(1, 7)
            die2.setValue(value2)
            quitButton.activate()
        pt = win.getMouse()

    #close up shop
    win.close()
def test_scene():
    """ Create a window and plot a scene with a 
	of a steam plant in it. """
    win = gr.GraphWin('title', 1000, 700, False)

    # the four separate functions for objects
    landscape = landscape_init(0, 385, 1.0)
    cannon = cannon_init(50, 300, 1.0)
    ship = ship_init(700, 330, 1.0)
    bird = bird_init(300, 100, 1.0)

    #drawing the four separate object functions
    draw(landscape, win)
    draw(bird, win)
    draw(cannon, win)
    draw(ship, win)

    win.update()

    # ANIMATION for loop to shoot "big shot' and cannonballs, and BIRD
    for frame_num in range(60):
        time.sleep(0.15)
        print frame_num
        cannonball_animation_frame(cannon, frame_num, win)
        bird_animation_frame(bird, frame_num, win)
        win.update()
        if win.checkMouse():
            break
    for frame_num in range(65, 300):
        time.sleep(0.05)
        bird_animation_frame(bird, frame_num, win)
        '''make bird go faster here to avoid boat on fire'''
        fire = []
        c = gr.Circle(gr.Point(800, 300), 10)
        c.draw(win)
        fire.append(c)
        for item in fire:
            dx = random.randint(-80, 80)
            dy = random.randint(-115, 100)
            item.move(dx, dy)
            hot = [
                gr.color_rgb(255, 255, 0),
                gr.color_rgb(255, 0, 0),
                gr.color_rgb(255, 69, 0),
                gr.color_rgb(255, 165, 0)
            ]
            item.setFill(random.choice(hot))
        if random.random() < 0.2:
            oldshape = random.choice(fire)
            newshape = oldshape.clone()
            newshape.draw(win)
            fire.append(newshape)

        win.update()

        if win.checkMouse() != None:
            break

    win.getMouse()
    win.close()
Beispiel #14
0
Datei: tg.py Projekt: VP1147/tg
def grid(m):  # m - Def the distance between 2 lines
    e = 0
    for i in range(0, int((Sx) / (m / Factor)) + 1):
        l = gfx.Line(gfx.Point((e / Factor) + (Sx / 2), 0),
                     gfx.Point((e / Factor) + (Sx / 2), Sy))
        l.setFill(gfx.color_rgb(Color3[0], Color3[1], Color3[2]))
        l.draw(Win)

        l = gfx.Line(gfx.Point((Sx / 2) - (e / Factor), 0),
                     gfx.Point(Sx / 2 - (e / Factor), Sy))
        l.setFill(gfx.color_rgb(Color3[0], Color3[1], Color3[2]))
        l.draw(Win)
        e += m / 2
    e = 0
    for i in range(0, int((Sy) / (m / Factor)) + 1):
        l = gfx.Line(gfx.Point(0, (e / Factor) + (Sy / 2)),
                     gfx.Point(Sx, (e / Factor) + (Sy / 2)))
        l.setFill(gfx.color_rgb(Color3[0], Color3[1], Color3[2]))
        l.draw(Win)

        l = gfx.Line(gfx.Point(0, (Sy / 2) - (e / Factor)),
                     gfx.Point(Sx, (Sy / 2) - (e / Factor)))
        l.setFill(gfx.color_rgb(Color3[0], Color3[1], Color3[2]))
        l.draw(Win)
        e += m / 2
Beispiel #15
0
def main(window_width, window_height, square_dim, filename):

    window = GraphWin("Karnaugh Map", window_width, window_height)

    window.setBackground(color_rgb(255, 255, 255))

    for line in get_k_map_lines(window_width, window_height, square_dim):
        line.setWidth(1)
        line.setFill(color_rgb(0, 0, 0))
        line.draw(window)

    variables = [(chr(i), chr(i) + "'") for i in range(65, 91)]
    shuffle(variables)
    for label in get_k_map_variable_labels(window_width, window_height, square_dim, variables):
        label.setTextColor('black')
        label.setSize(30)
        label.draw(window)

    k_map_values = get_k_map_values()
    for text in get_k_map_text_values(window_width, window_height, square_dim, k_map_values):
        text.setTextColor('black')
        text.setSize(30)
        text.draw(window)
    # print(k_map_values)
    ps = window.postscript(colormode='color')
    img = Image.open(io.BytesIO(ps.encode('utf-8')))
    img.save(filename)

    window.close()
def bird_init(x,y,scale):
	""" Create the list of objects needed to draw a bird
		at position (x,y) with the given scale """

	bird = []
	'''separate rectangles triangle and circle for the 
		body of the bird, beak, and legs'''
	
	body = gr.Rectangle( gr.Point(x,y), gr.Point(x+scale*75, y+scale*25) )
	body.setFill(gr.color_rgb( 107, 142, 35))
	bird.append( body )
	
	leg1 = gr.Rectangle( gr.Point(x, y+25*scale), gr.Point(x+scale*10, y+40*scale) )
	leg1.setFill(gr.color_rgb( 95, 158, 160))
	bird.append( leg1 )
	
	leg2 = gr.Rectangle( gr.Point(x+30, y+25*scale), gr.Point(x+scale*40, y+40*scale) )
	leg2.setFill(gr.color_rgb( 95, 158, 160))
	bird.append( leg2 )
	
	head = gr.Circle( gr.Point(x+75*scale, y-5*scale), 15)
	head.setFill( gr.color_rgb(127, 255, 215))
	bird.append( head )
	
	beak = gr.Polygon( gr.Point(x+85*scale, y*scale), gr.Point(x+scale*105, y-scale*10),
	gr.Point(x+scale*85, y-scale*20 ))
	beak.setFill(gr.color_rgb( 255, 215, 0))
	bird.append( beak )
	
	return bird
Beispiel #17
0
def update_board(second_per_update):
    # A*
    current = min(openSet, key=lambda o: o.f)
    # BFS
    # current = openSet[0]
    # DIJKSTRA
    # current = min(openSet, key=lambda o: o.g)
    for i in openSet:
        if i not in open_update:
            rect = i.rectangle(i.i, i.j)
            rect.setFill(color_rgb(167, 239, 180))
            rect.draw(win)
            open_update.append(i)
            text = i.hScoreText(i.i, i.j)
            text.setOutline(color_rgb(19, 10, 200))
            text.setStyle("bold")
            text.draw(win)
        dot = Circle(
            Point(current.j * square_size + square_size / 2,
                  current.i * square_size + square_size / 2), 10)
        dot.setOutline(color_rgb(19, 10, 200))
        dot.draw(win)
    for i in closeSet:
        if i not in closed_update:
            rect = i.rectangle(i.i, i.j)
            rect.setFill(color_rgb(239, 167, 167))
            rect.draw(win)
            closed_update.append(i)
            text = i.hScoreText(i.i, i.j)
            text.setOutline(color_rgb(19, 10, 200))
            text.setStyle("bold")
            text.draw(win)
    openSet_score.setText(openSet.__len__())
    closedSet_score.setText(closeSet.__len__())
    time.sleep(second_per_update)
Beispiel #18
0
def draw_christmas_tree(center_point: Point, width: int, height: int, palette: GraphWin):
    trunk = get_rectangle(Point(center_point.getX() - width * 0.05, center_point.getY()), int(width * 0.1),
                          int(height * 0.1))
    trunk.setFill(gr.color_rgb(128, 64, 0))
    trunk.draw(palette)

    tier_diff = height / 5
    tier_falloff = 0.8

    tier_a = get_isosceles_triangle(Point(center_point.getX() - width / 2, center_point.getY() - int(height * 0.1)),
                                    width, int(height * 0.5))
    tier_b = get_isosceles_triangle(
        Point(center_point.getX() - (width / 2) * tier_falloff, center_point.getY() - int(height * 0.1) - tier_diff),
        int(width * tier_falloff), int(height * 0.5 * tier_falloff))
    tier_c = get_isosceles_triangle(
        Point(center_point.getX() - width / 2 * tier_falloff ** 2,
              center_point.getY() - int(height * 0.1) - tier_diff * 2),
        int(width * tier_falloff ** 2), int(height * 0.5 * tier_falloff ** 2))
    tier_a.setFill(gr.color_rgb(0, 80, 0))
    tier_b.setFill(gr.color_rgb(0, 80, 0))
    tier_c.setFill(gr.color_rgb(0, 80, 0))

    tier_a.draw(palette)
    tier_b.draw(palette)
    tier_c.draw(palette)
Beispiel #19
0
 def draw(self, win):
     self.circle.setFill(color_rgb(0, 0, 0))
     self.face.setFill(color_rgb(0, 0, 0))
     self.circle.undraw()
     self.face.undraw()
     self.circle.draw(win)
     self.face.draw(win)
Beispiel #20
0
def main():
    global WIN            # Window for graphics
    global CUR_COLOR      # Current color. (Is there a better way to do this?)
    CUR_COLOR = graphics.color_rgb(0, 128, 0) # dull green? 
    
    sample = Rect(5, 5, 20, 20)
    other_rect = Rect(10, 10, 20, 25)
    non_overlap_rect = Rect(25, 25, 30, 30)

    first_rectlist = Rectlist()
    first_rectlist.addrect(sample)
    first_rectlist.addrect(other_rect)
    first_rectlist.addrect(non_overlap_rect)

    second_rectlist = Rectlist()
    second_rectlist.addrect(Rect(27, 27, 30, 30))
    second_rectlist.addrect(Rect(0, 6, 19, 10))
    
    if sample.overlap(other_rect):
        print('Overlap (expected)')
    else:
        print('No overlap (somethings wrong)')
        
    if sample.overlap(non_overlap_rect):
        print('Overlap (expected)')
    else:
        print('No overlap (somethings wrong)')

    CUR_COLOR = graphics.color_rgb(128, 0, 0)

    sample.intersection(other_rect)

    input("Press enter to close")
Beispiel #21
0
def showField():  #Generates window and basic objects
    """Generates window and basic objects, returns window and object list."""
    if settings[3]:  #Hardcore setting
        lw = gr.GraphWin("Pysweeper | HARDCORE Game", settings[0] * 40,
                         (settings[1] * 40) + 40, False)
    else:
        lw = gr.GraphWin("Pysweeper | Game", settings[0] * 40,
                         (settings[1] * 40) + 40, False)
    lw.setBackground(gr.color_rgb(33, 33, 33))
    li = []
    # 0: Top bar background
    # 1: Remaining flags
    # 2: Timer
    # 3: Reset icon

    li.append(gr.Rectangle(gr.Point(0, 0), gr.Point(lw.width, 40)))
    li[0].setWidth(0)
    li[0].setFill(gr.color_rgb(66, 66, 66))

    li.append(gr.Text(gr.Point(30, 20), "000"))
    li[1].setSize(20)
    li[1].setFill(gr.color_rgb(250, 250, 250))

    li.append(gr.Text(gr.Point(lw.width - 30, 20), "000"))
    li[2].setSize(20)
    li[2].setFill(gr.color_rgb(250, 250, 250))

    li.append(gr.Image(gr.Point(lw.width / 2, 20), "img/Reset.png"))
    li[1].setText((3 - len(str(rflags))) * "0" + str(rflags))

    for i in li:
        i.draw(lw)

    lw.flush()
    return lw, li
Beispiel #22
0
    def drawPlanGraphics(self):

        # First iterate over all the cells and mark them up
        cellExtent = self.searchGrid.getExtentInCells()
        for i in range(cellExtent[0]):
            if rospy.is_shutdown():
                return
            for j in range(cellExtent[1]):
                cellLabel = self.searchGrid.getCellFromCoords((i, j)).label
                terrain = self.searchGrid.getCellFromCoords((i, j)).terrainCost
                if cellLabel == CellLabel.OBSTRUCTED:
                    colour = 'purple'
                elif cellLabel == CellLabel.START:
                    colour = 'green'
                elif cellLabel == CellLabel.GOAL:
                    colour = 'blue'
                elif cellLabel == CellLabel.UNVISITED:
                    colour = 'gray'
                    v = int(min(400 * (terrain - 1), 255))
                    colour = graphics.color_rgb(100 + int(v * .5), 100,
                                                min(100 + v, 255))
                elif cellLabel == CellLabel.DEAD:
                    # colour = 'black'
                    v = int(min(300 * (terrain - 1), 255))
                    colour = graphics.color_rgb(v, 0, int(v * .5))
                else:
                    colour = 'white'
                self.rectangles[i][j].setFill(colour)
Beispiel #23
0
Datei: tg.py Projekt: VP1147/tg
def axis(x, y):
    l1 = gfx.Line(gfx.Point(x / 2, 0), gfx.Point(x / 2, x))
    l1.setFill(gfx.color_rgb(Color2[0], Color2[1], Color2[2]))
    l1.draw(Win)

    l2 = gfx.Line(gfx.Point(x, y / 2), gfx.Point(1, y / 2))
    l2.setFill(gfx.color_rgb(Color2[0], Color2[1], Color2[2]))
    l2.draw(Win)
Beispiel #24
0
 def draw(self, win):
     if (self.pressed or self.locked):
         self.rect.setFill(color_rgb(100, 100, 100))
     else:
         self.rect.setFill(color_rgb(170, 170, 170))
     self.rect.undraw()
     self.rect.draw(win)
     self.text.undraw()
     self.text.draw(win)
Beispiel #25
0
def drawGrid(win):
    for i in range(0, WIDTH, 20):
        ln = g.Line(g.Point(i, 0), g.Point(i, HEIGHT))
        ln.setOutline(g.color_rgb(200, 200, 255))
        ln.draw(win)
    for i in range(0, HEIGHT, 20):
        ln = g.Line(g.Point(0, i), g.Point(WIDTH, i))
        ln.setOutline(g.color_rgb(200, 200, 255))
        ln.draw(win)
Beispiel #26
0
    def createHud(self):
        score = self.getScores()
        self.scoreText = Text(Point(730, 20 + len(self.racket) * 10), score)
        self.scoreText.setTextColor(color_rgb(255, 255, 255))
        self.scoreText.draw(self)

        self.gameSpeedText = Text(Point(50, 20),
                                  'Speed: ' + str(self.gameSpeed))
        self.gameSpeedText.setTextColor(color_rgb(255, 255, 255))
        self.gameSpeedText.draw(self)
Beispiel #27
0
def draw_book(window, x, y, widtg, height):
    book = gr.Rectangle(gr.Point(x, y), gr.Point(x + widtg, y - height))
    book.setFill(
        gr.color_rgb(random.randint(0, 255), random.randint(0, 255),
                     random.randint(0, 255)))
    book.draw(window)
    book_name = gr.Rectangle(gr.Point(x + 4, y - 2),
                             gr.Point(x + widtg - 4, y - height + 12))
    book_name.setFill(gr.color_rgb(0, 0, 0))
    book_name.draw(window)
Beispiel #28
0
def buildRectangle(tlx, brx, index):
#Check Index to ensure final block meets the edge
    if index == numBars - 1:
        bottomRight = g.Point(400, 200)
    else:
        bottomRight = g.Point(brx, 200)
    topLeft = g.Point(tlx, 0)
    rectangle = g.Rectangle(topLeft, bottomRight)
    rectangle.setFill(g.color_rgb(colorInterval, 0, 0))
    rectangle.setOutline(g.color_rgb(colorInterval, 0, 0))
    rectangle.draw(win)
Beispiel #29
0
def populateImageFromArea(img, area, cellSize, areaSize):
    for i in range(0, areaSize):
        for j in range(0, areaSize):
            status = area[i][j]
            for py in range(cellSize * i, cellSize * i + cellSize):
                for px in range(cellSize * j, cellSize * j + cellSize):
                    if int(status) == 1:
                        color = gp.color_rgb(0, 255, 0)
                    else:
                        color = gp.color_rgb(255, 0, 0)
                    img.setPixel(px, py, color)
Beispiel #30
0
    def __init__(self, name="Twixt"):
        self.bottom = self.CELL*(2+self.SIZE)
	self.win = gr.GraphWin(name, self.CELL*(2+self.SIZE), self.bottom+self.CELL, autoflush=False)
	self.history = []
	self.known_moves = set()

	# Regular background
	self.win.setBackground(gr.color_rgb(244, 255,240))

        # bottom
        for i in range(20):
            peg = gr.Circle(self.center(i,25), self.PEG_RADIUS)
            peg.setWidth(0)
            peg.setFill(self._colors(i))
            peg.draw(self.win)
        
	# black/white end zones
	for i in range(4):
	    a = self.twopoints(i)
	    b = self.twopoints(i+1)
	    color = [gr.color_rgb(255,255,200), gr.color_rgb(200,200,200)][i&1]
	    poly = gr.Polygon(a[0], a[1], b[1], b[0])
	    poly.setOutline(color)
	    poly.setFill(color)
	    poly.draw(self.win)

	# peg holes
	for x in range(self.SIZE):
	    for y in range(self.SIZE):
		if x in (0, self.SIZE-1) and y in (0, self.SIZE-1):
		    continue

		c = gr.Circle(self.center(x, y), self.HOLE_RADIUS)
		c.setFill("black")
		c.draw(self.win)

	# labels
	for i in range(self.SIZE):
	    ctr = self.center(i, i)
	    row_label = "%d" % (i+1)
	    txt = gr.Text(gr.Point(self.CELL/2, ctr.y), row_label)
	    txt.draw(self.win)
	    txt = txt.clone()
	    txt.move(self.CELL*(self.SIZE+1), 0)
	    txt.draw(self.win)

	    col_label = chr(ord('A')+i)
	    txt = gr.Text(gr.Point(ctr.x, self.CELL/2), col_label)
	    txt.draw(self.win)
	    txt = txt.clone()
	    txt.move(0, self.CELL*(self.SIZE+1))
	    txt.draw(self.win)

	gr.update()
Beispiel #31
0
    def __init__(self, win, online):
        self.player = Player(Point(win.getWidth() / 2,
                                   win.getHeight() / 2), 25, 450,
                             color_rgb(255, 120, 90))
        self.online = online  #For peer-to-peer gameplay
        self.asteroidCounter = 0

        self.scoreui = Text(Point(100, 100), str(self.player.getScore()), 25,
                            color_rgb(255, 145, 164), "bold")

        if not online:
            self.asteroids = []
Beispiel #32
0
def draw_rectangle(x, y, length, height, r, g, b):
    """
        Рисует прямоугольник:
        x,y - координаты правой нижней точки прямоугольника;
        length - длина прямоугольника ;
        height - высота;
        r,g,b - параметры его цвета
    """
    rectangle = gr.Rectangle(gr.Point(x, y), gr.Point(x + length, y + height))
    rectangle.setFill(gr.color_rgb(r, g, b))
    rectangle.setOutline(gr.color_rgb(r, g, b))
    rectangle.draw(window)
Beispiel #33
0
def earth():
    """
    Draws earth - fills area with Light Gray color

    Returns
    -------
    None.

    """
    earth = gr.Rectangle(gr.Point(0, 400), gr.Point(800, 600))
    earth.setFill(gr.color_rgb(187, 187, 187))
    earth.setOutline(gr.color_rgb(187, 187, 187))
    earth.draw(window)
Beispiel #34
0
def cannonball_animation_frame(shapes, frame_num, win):
	"""Cannonball animation. The animation will
		involve one big cannonball shooting out of the cannon.
		shapes is a list containing the graphics objects needed to draw
		the cannonball scene.
		frame_num is a number indicating which frame of the animation
		it is. win is the GraphWin object containing the scene.
		This animates by creating up to 20 little cannonball circles too. 
		Each circle creeps across the screen until it gets to the edge"""
	p1 = shapes[2].getP1()
	p2 = shapes[2].getP2()
	
	dy = p2.getY() - p1.getY()
	newy = (p1.getY() + p2.getY())*0.5
	newx = p2.getX() - dy*0.5
	
	if frame_num %2 == 0 and len(shapes) < 22:
		c = gr.Circle(gr.Point( newx, newy), 0.4*dy)
		c.setFill(gr.color_rgb(150, 150, 150))
		c.draw(win)
		shapes.append(c)
		
	for shape in shapes[5:]:
		shape.move( 25, 0)
		center = shape.getCenter()
		
		if center.y < 0:
			mx = newx - center.getX()
			my = newy - center.getY()
			shape.move( mx, my )
 def colorscheme2(self, color1, color2, num):
     '''
     :param color1: a color in hexdecimal string
     :param color2: another color in hexdecimal string
     :param num: the number of colors desired to make the transition between those two colors inputed
     :return: a list of colors
     '''
     r1 = int(color1[1:3], 16)
     g1 = int(color1[3:5], 16)
     b1 = int(color1[5:7], 16)
     r2 = int(color2[1:3], 16)
     g2 = int(color2[3:5], 16)
     b2 = int(color2[5:7], 16)
     rlist = []
     glist = []
     blist = []
     colors = []
     for i in range(min(r1, r2), max(r1, r2), (max(r1, r2) - min(r1, r2))/num):
         rlist.append(i)
     for i in range(min(g1, g2), max(g1, g2), (max(g1, g2) - min(g1, g2))/num):
         glist.append(i)
     for i in range(min(b1, b2), max(b1, b2), (max(b1, b2) - min(b1, b2))/num):
         blist.append(i)
     for i in range(num):
         color = graphics.color_rgb(rlist[i], glist[i], blist[i])
         colors.append(color)
     return colors
Beispiel #36
0
def colors(numSites):
    r = np.arange(0,255, (255/numSites))
    g = np.arange(0,255, (255/numSites))
    b = np.arange(0,255, (255/numSites))
    np.random.shuffle(r)
    np.random.shuffle(g)
    np.random.shuffle(b)
    colorBook = {}
    for i in range(numSites):
        color =  gp.color_rgb(r[i], g[i], b[i])
        colorBook[i] = color
    return colorBook
Beispiel #37
0
def cannon_init(x, y, scale):
	""" Create the list of objects needed to draw a cannon
	at position (x,y) with the given scale """
	
	shapes = []
	
	'''the separate rectangle are parts of the cannon
		the cannonball is the large "first shot" cannonball'''
	
	r1 = gr.Rectangle( gr.Point(x,y), gr.Point(x+scale*100, y+scale*50) )
	r1.setFill(gr.color_rgb(185, 185, 185))
	shapes.append( r1 )
	
	r2 = gr.Rectangle( gr.Point(x+scale*100, y+scale*10), gr.Point(x+scale*200, y+scale*40) )
	r2.setFill(gr.color_rgb(185, 185, 185))
	shapes.append( r2 )
	
	r3 = gr.Rectangle( gr.Point(x+scale*200, y+scale*20) , gr.Point(x+scale*250, y+scale*30) )
	r3.setFill(gr.color_rgb(185, 185, 185))
	shapes.append( r3 )
	
	r4 = gr.Rectangle( gr.Point(x+scale*15, y+scale*50) , gr.Point(x+scale*40, y+scale*85) )
	r4.setFill(gr.color_rgb(176, 133, 85 ))
	shapes.append( r4 )
	
	r5 = gr.Rectangle( gr.Point(x+scale*115, y+scale*40) , gr.Point(x+scale*140, y+scale*85) )
	r5.setFill(gr.color_rgb(176, 133, 85 ))
	shapes.append( r5 )
	
	cannonball = gr.Circle( gr.Point(x+250*scale,y+25*scale), 20)
	cannonball.setFill( gr.color_rgb(230, 230, 250))
	shapes.append( cannonball )
	
	return shapes
def createTable(maxDoors):
    """creates the table of probabilities
    of success by switching"""
    table = graphics.GraphWin("table", (cellSize+1)*maxDoors, (cellSize+1)*maxDoors)
    if maxDoors < 3:
        return
    for n in range (3, maxDoors+1):
        for i in range(n-1):
            value = float(n-1)/(n**2 - n*i - n)
            p1 = graphics.Point(n*cellSize, i*cellSize)
            p2 = graphics.Point((n+1)*cellSize, (i+1)*cellSize)
            sqr = graphics.Rectangle(p1, p2)
            sqr.setFill(graphics.color_rgb(0,0,value*255))
            sqr.draw(table)
    return table
Beispiel #39
0
def ship_init( x, y, scale ):
	""" Create the list of objects needed to draw a ship
		at position (x,y) with the given scale """

	shapes = []
	
	'''separate rectangles triangles for the 
		body of the ship, mast, and flag and
		circle for the windows'''
	
	body = gr.Rectangle( gr.Point(x,y), gr.Point(x+scale*200, y+scale*100) )
	body.setFill(gr.color_rgb( 218, 165, 32))
	shapes.append( body )
	
	mast = gr.Rectangle( gr.Point(x+scale*100, y-250*scale), gr.Point(x+scale*110, y) )
	mast.setFill(gr.color_rgb( 222, 184, 135))
	shapes.append( mast )
	
	t1 = gr.Polygon( gr.Point(x, y), gr.Point(x-scale*50, y+scale*50), gr.Point(x, y+scale*100 ))
	t1.setFill(gr.color_rgb( 218, 165, 32))
	shapes.append( t1 )
	
	t2 = gr.Polygon( gr.Point(x+scale*200, y), gr.Point(x+scale*250, y+scale*50), gr.Point(x+scale*200, y+scale*100 ))
	t2.setFill(gr.color_rgb(218, 165, 32))
	shapes.append( t2 )
	
	flag = gr.Polygon( gr.Point(x+scale*110, y-150*scale), gr.Point(x+scale*160, y-200*scale), gr.Point(x+scale*110, y-250*scale) )
	flag.setFill(gr.color_rgb( 255, 0, 255))
	shapes.append( flag )
	
	window1 = gr.Circle( gr.Point(x+40*scale, y+50*scale), 10)
	window1.setFill( gr.color_rgb(230, 230, 250))
	shapes.append( window1 )
	
	window2 = gr.Circle( gr.Point(x+100*scale, y+50*scale), 10)
	window2.setFill( gr.color_rgb(230, 230, 250))
	shapes.append( window2 )

	window3 = gr.Circle( gr.Point(x+160*scale, y+50*scale), 10)
	window3.setFill( gr.color_rgb(230, 230, 250))
	shapes.append( window3 )

	return shapes
def test_scene():
	""" Create a window and plot a scene with a 
	of a steam plant in it. """
	win = gr.GraphWin( 'title', 1000, 700, False )

	# the four separate functions for objects
	landscape = landscape_init(0, 385, 1.0)
	cannon = cannon_init( 50, 300, 1.0 )
	ship = ship_init( 700, 330, 1.0)
	bird = bird_init( 300, 100, 1.0)
	
	#drawing the four separate object functions
	draw(landscape, win)
	draw(bird, win)
	draw(cannon, win)
	draw( ship, win)
		
	win.update()

	# ANIMATION for loop to shoot "big shot' and cannonballs, and BIRD
	for frame_num in range(60):
		time.sleep( 0.15 )
		print frame_num
		cannonball_animation_frame( cannon, frame_num, win )
		bird_animation_frame( bird, frame_num, win)
		win.update()
		if win.checkMouse():
			break
	for frame_num in range(65,300):
		time.sleep( 0.05 )
		bird_animation_frame( bird, frame_num, win)
		'''make bird go faster here to avoid boat on fire'''
		fire = []
		c = gr.Circle( gr.Point(800, 300), 10)
		c.draw( win )
		fire.append( c )
		for item in fire:
			dx = random.randint( -80, 80 )
			dy = random.randint( -115, 100 )
			item.move( dx, dy )	
			hot = [ gr.color_rgb( 255, 255, 0 ), gr.color_rgb( 255, 0, 0 ),
			gr.color_rgb( 255, 69, 0 ), gr.color_rgb(255,165,0)]
			item.setFill( random.choice(hot) )
		if random.random() < 0.2:
			oldshape = random.choice( fire )
			newshape = oldshape.clone()
			newshape.draw( win )
			fire.append( newshape )
			
		win.update()
		
		if win.checkMouse() != None:
			break 
	
	
	
	
	
	
	
	

	win.getMouse()
	win.close() 
Beispiel #41
0
if __name__ == "__main__":
    results_dir = 'results'
    for f in (f for f in os.listdir(results_dir) if f.endswith('.log')):
        hist = json.load(open(os.path.join(results_dir, f)))
        colors = None
        for i, game in enumerate(hist):
            score = [0, 0]
            images = []
            names = game['players']
            size = int(game['size'])

            dim = 600
            left_marg = 50
            top_marg = 200
            win = GraphWin(game, dim + 2*left_marg, dim + top_marg + 50)
            win.setBackground(color_rgb(255, 255, 255))

            if not colors:
                colors = {names[0]: 'blue', names[1]: 'red'}
                p1 = Text(Point(left_marg + dim//2, 30), names[0])
                p1.setFill(colors[names[0]])
                p1.setSize(20)
                score1 = Text(Point(left_marg + dim//6, 70), '0:0')
                score1.setFill(colors[names[0]])
                score1.setSize(30)

                vs = Text(Point(left_marg + dim//2, 70), 'vs')
                vs.setFill('black')
                vs.setSize(20)

                p2 = Text(Point(left_marg + dim//2, 110), names[1])
Beispiel #42
0
import graphics  # Because what fun are rectangles without drawing

#
# Very simple graphical depiction.  Virtual coordinates to 50,50
#

global WIN, CUR_COLOR  # Sloppy but expedient.  How should we handle these? 

WIN = graphics.GraphWin("Rectangles", 800, 800)
WIN.setCoords(0,0,50,50)
background = graphics.Rectangle( graphics.Point(0,0), graphics.Point(1024,768))
background.setFill( graphics.color_rgb(255,255,255) ) # white

CUR_COLOR = graphics.color_rgb(0,0,0) # black

def draw_rect(llx, lly, urx, ury, color=""):
    """Display a rectangle in the graphics window.
    Arguments:
       llx, lly:  Coordinates of lower left corner
       urx, ury:  Coordinates of upper right corner
       color: fill color of rectangle drawn on screen
    Returns:
       nothing
    Effects:
       rectangle is drawn on screen
    """
    view = graphics.Rectangle( graphics.Point(llx,lly), graphics.Point(urx,ury))
    view.setFill( CUR_COLOR )
    view.draw(WIN)
    return
Beispiel #43
0
def cursor_func(
        freq_sampling,
        num_signal_channels,
        num_event_types,
        window_size_in_samples):

    logging.debug('%s cursor_func(.) entered.', TAG)

    len_padding = 5 * freq_sampling

    cursor_radius = 26
    w = 2 * math.pi / 10

    # Initialize the time-domain filter
    #numer, denom = get_time_domain_filters(8.0, 12.0, 0.5)

    # Init the NN
    if is_control_mode:
        filename_base = '../models/MIBBCI_NN_medium_bestsofar'
        filename_nn = filename_base + '.npz'
        nnet = nnutils.load_nn(nnutils.create_nn_medium, filename_nn)

    # Init the preproc stuff
    if is_control_mode:
        filename_p = filename_base + '.p'
        scaler = cPickle.load(open(filename_p, 'rb'))
        print 'Loaded scaler.mean_, scaler.var_:', scaler.mean_, scaler.var_

    # Init graphics
    win = graphics.GraphWin('Cursor', params.IMAGE_W, params.IMAGE_H)
    cursor = graphics.Circle(graphics.Point(params.IMAGE_W/2, params.IMAGE_H/2), cursor_radius)
    cursor.setFill(graphics.color_rgb(params.CURSOR_COLOR_REST[0], params.CURSOR_COLOR_REST[1], params.CURSOR_COLOR_REST[2]))
    cursor.setOutline(graphics.color_rgb(params.CURSOR_COLOR_REST[0], params.CURSOR_COLOR_REST[1], params.CURSOR_COLOR_REST[2]))
    cursor.draw(win)
    cursor_pos_prev = np.array([params.IMAGE_W/2, params.IMAGE_H/2])
    cursor_pos = cursor_pos_prev

    # Init event labels
    event_arr_right = np.zeros((params.LEN_DATA_CHUNK_READ, num_event_types))
    event_arr_right[:, params.EVENT_ID_RH] = np.ones(params.LEN_DATA_CHUNK_READ)
    event_arr_left = np.zeros((params.LEN_DATA_CHUNK_READ, num_event_types))
    event_arr_left[:, params.EVENT_ID_LH] = np.ones(params.LEN_DATA_CHUNK_READ)
    event_arr_idle = np.zeros((params.LEN_DATA_CHUNK_READ, num_event_types))
    event_arr_idle[:, params.EVENT_ID_IDLE] = np.ones(params.LEN_DATA_CHUNK_READ)
    #event_arr_calib = np.zeros((params.LEN_DATA_CHUNK_READ, num_event_types))
    #event_arr_calib[:, 3] = np.ones(params.LEN_DATA_CHUNK_READ)
    cursor_event_list = []
    cursor_color_arr_raw = np.zeros((int(params.LEN_PERIOD_SEC * freq_sampling / params.LEN_DATA_CHUNK_READ), 3))
    color_counter = 0
    for i in range(int(params.LEN_IDLE_SEC * freq_sampling / params.LEN_DATA_CHUNK_READ)):
        cursor_color_arr_raw[color_counter, :] = params.CURSOR_COLOR_IDLE
        cursor_event_list.append(event_arr_idle)      # r, l, idle, calib
        color_counter += 1
    for i in range(int(params.LEN_RIGHT_SEC * freq_sampling / params.LEN_DATA_CHUNK_READ)):
        cursor_color_arr_raw[color_counter, :] = params.CURSOR_COLOR_RIGHT
        cursor_event_list.append(event_arr_right)
        color_counter += 1
    for i in range(int(params.LEN_IDLE_SEC * freq_sampling / params.LEN_DATA_CHUNK_READ)):
        cursor_color_arr_raw[color_counter, :] = params.CURSOR_COLOR_IDLE
        cursor_event_list.append(event_arr_idle)
        color_counter += 1
    for i in range(int(params.LEN_LEFT_SEC * freq_sampling / params.LEN_DATA_CHUNK_READ)):
        cursor_color_arr_raw[color_counter, :] = params.CURSOR_COLOR_LEFT
        cursor_event_list.append(event_arr_left)
        color_counter += 1
    conv_window = np.ones((params.LEN_COLOR_CONV_SEC * freq_sampling / params.LEN_DATA_CHUNK_READ, 1))\
                  / (1 * int(params.LEN_COLOR_CONV_SEC * freq_sampling / params.LEN_DATA_CHUNK_READ))
    cursor_color_arr_ud = np.flipud(cursor_color_arr_raw)
    cursor_color_arr_ud_convd = signal.convolve(cursor_color_arr_ud.T, conv_window.T).T
    cursor_color_arr_final = np.flipud(cursor_color_arr_ud_convd[0:cursor_color_arr_raw.shape[0], :])
    if False:
        plt.figure()
        plt.plot(cursor_color_arr_raw)
        #plt.plot(cursor_color_arr_ud[:, 0])
        #plt.plot(cursor_color_arr_ud_convd[:, 0])
        plt.plot(cursor_color_arr_final)
        #plt.legend(['raw', 'ud', 'ud_convd', 'final'])
        plt.show()

    # Initialize the amplifier
    if not is_simulation_mode:
        print 'Initializing the amp...'
        recorder = Recorder('lslamp', freq_sampling, params.LEN_REC_BUF_SEC, num_signal_channels)
        thread_rec = threading.Thread(target=recorder.record)
        thread_rec.start()

    # Cursor control loop
    X_raw_buf_live = np.zeros((int(freq_sampling*params.LEN_REC_BUF_SEC), num_signal_channels))
    label_buf_live = np.zeros((int(freq_sampling*params.LEN_REC_BUF_SEC), num_event_types))
    counter = 0
    #while True:
    while counter < (params.LEN_REC_SEC * freq_sampling / params.LEN_DATA_CHUNK_READ):
        print 'counter: ', counter

        # Clear the canvas
        win.delete('all')

        if not is_simulation_mode:
            # Wait for new data and get it
            data_last_chunk = recorder.get_new_data(params.LEN_DATA_CHUNK_READ, params.AMP_WAIT_SEC)
            recorder.acknowledge_new_data()
            print 'recorder.new_data_counter:', recorder.new_data_counter
        else:
            time.sleep(1.0 / (freq_sampling/params.LEN_DATA_CHUNK_READ))
            data_last_chunk = 1000.0 * np.random.rand(int(params.LEN_DATA_CHUNK_READ), num_signal_channels)
            #print 'Random data_last_chunk size:', data_last_chunk

        # Insert the new sample into our time series
        i_row_lb = int((counter+len_padding)*params.LEN_DATA_CHUNK_READ)
        i_row_ub = int((counter+len_padding+1)*params.LEN_DATA_CHUNK_READ)
        X_raw_buf_live[i_row_lb:i_row_ub, :] = data_last_chunk
        #print 'data_last_chunk:', data_last_chunk
        label_buf_live[i_row_lb:i_row_ub, :]\
                = cursor_event_list[counter % int(params.LEN_PERIOD_SEC * freq_sampling / params.LEN_DATA_CHUNK_READ)]

        # Calculating cursor step
        i_row_ub = int((counter+len_padding+1)*params.LEN_DATA_CHUNK_READ)
        i_row_lb = i_row_ub - int(window_size_in_samples)
        if i_row_lb >= 0:
            #print 'i_row_lb, i_row_ub:', i_row_lb, i_row_ub
            #print 'X_raw_buf_live[i_row_lb:i_row_ub, :].shape:', X_raw_buf_live[i_row_lb:i_row_ub, :].shape
            if is_control_mode:
                X_window = utils.preprocess(X_raw_buf_live[i_row_lb:i_row_ub, :], scaler)
                X_in = TimeSeriesBatchIterator.create_X_instance(X_window, conv_dim=1)
                X_in = X_in.reshape(1, X_in.shape[0], X_in.shape[1])
                #print 'X_window.shape:', X_window.shape
                #print 'X_in.shape:', X_in.shape
                cursor_step = calc_cursor_step(nnet, X_in.astype(np.float32))
            else:
                #X_window = X_raw_buf_live[i_row_lb:i_row_ub, :]
                cursor_step = 0

            cursor_pos = cursor_pos_prev + np.array([cursor_step, 0])
            #print 'cursor_pos: ', cursor_pos

        else:
            cursor_pos = cursor_pos_prev

        cursor_pos_point = graphics.Point(cursor_pos[0], cursor_pos[1])
        cursor_pos_prev = cursor_pos
        cursor = graphics.Circle(cursor_pos_point, cursor_radius)
        color_temp = cursor_color_arr_final[counter % int(params.LEN_PERIOD_SEC * freq_sampling / params.LEN_DATA_CHUNK_READ)]
        cursor.setFill(graphics.color_rgb(color_temp[0], color_temp[1], color_temp[2]))
        cursor.setOutline(graphics.color_rgb(color_temp[0], color_temp[1], color_temp[2]))
        cursor.draw(win)

        counter += 1

        # End of if
    # End of while

    # Stop recording
    recorder.stop_recording()

    # Close the window
    win.close()

    # Cut the padding from the data
    i_row_lb = int(len_padding * params.LEN_DATA_CHUNK_READ)
    i_row_ub = int((counter+len_padding)*params.LEN_DATA_CHUNK_READ)
    X_raw_buf_cut = X_raw_buf_live[i_row_lb:i_row_ub, :]
    label_buf_cut = label_buf_live[i_row_lb:i_row_ub, :]

    # Save data to file
    time_axis = np.arange(X_raw_buf_cut.shape[0]).reshape((X_raw_buf_cut.shape[0], 1))
    print 'time_axis.shape:', time_axis.shape
    data_merged = np.concatenate((time_axis, X_raw_buf_cut, label_buf_cut), axis=1)
    print 'data_merged.shape: ', data_merged.shape
    time_save = datetime.now()
    np.savetxt('../data/MIBBCI_REC_{0}Hz_{1}{2:02}{3:02}_{4:02}h{5:02}m{6:02}s_RAW.csv'.format(
            int(freq_sampling),
            time_save.year, time_save.month, time_save.day,
            time_save.hour, time_save.minute, time_save.second),
            X=data_merged, fmt='%.8f', delimiter=",",
            header='time, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, red, blue, idle',
            comments='')


    print 'cursor_func(.) terminates.'
                pkl_file_write.close()

                HIGHSCORE_CONGRATS.draw(window)
                pygame.mixer.music.stop()
                highScoreEntering = True
                TEXT_ENTRY.setText('')
                highScoreSound.play()
                TEXT_ENTRY.draw(window)
                playing = False

            # Player has not beaten the high score this run.
            if HIGHSCORETHISRUN == False:

                # Flags control loop False to stop game repeating             
                playing = False
                player.undraw()
                pygame.mixer.music.stop()
                gameOverSound.play()
                highScore()

window = graphics.GraphWin('Scrolling Game', Win_Width, Win_Height)
window.setBackground(graphics.color_rgb(255,117,117))
START_MESSAGE.draw(window)

# Wait for keyboard input events
window.bind_all('<Key>', handleKeys)

# Wait for events - main loop
window.mainloop()

def hitAnimation():

    window.setBackground('yellow')
    time.sleep(0.05)
    window.setBackground(graphics.color_rgb(255,117,117))
Beispiel #46
0
def cursor_func():

    print 'cursor_func(.) entered.'
    cursor_radius = 26
    w = 2 * math.pi / 10


    # Initialize the time-domain filter
    freq_Nyq = mi_params.FREQ_S/2.
    freq_trans = 0.5
    freqs_FIR_Hz = np.array([8.-freq_trans, 12.+freq_trans])
    #numer = signal.firwin(M_FIR, freqs_FIR, nyq=FREQ_S/2., pass_zero=False, window="hamming", scale=False)
    numer = signal.firwin(mi_params.M_FIR, freqs_FIR_Hz, nyq=freq_Nyq, pass_zero=False, window="hamming", scale=False)
    denom = 1.
    '''w, h = signal.freqz(numer)
    plt.plot(freq_Nyq*w/math.pi, 20 * np.log10(abs(h)), 'b')
    plt.ylabel('Amplitude [dB]', color='b')
    plt.xlabel('Frequency [rad/sample]')
    plt.show()'''


    # Set up graphics
    win = graphics.GraphWin('Cursor', mi_params.IMAGE_W, mi_params.IMAGE_H)
    cursor = graphics.Circle(graphics.Point(mi_params.IMAGE_W/2, mi_params.IMAGE_H/2), cursor_radius)
    #cursor.setFill(CURSOR_COLOR_REST)
    #cursor.setOutline(CURSOR_COLOR_REST)
    cursor.setFill(graphics.color_rgb(mi_params.CURSOR_COLOR_REST[0], mi_params.CURSOR_COLOR_REST[1], mi_params.CURSOR_COLOR_REST[2]))
    cursor.setOutline(graphics.color_rgb(mi_params.CURSOR_COLOR_REST[0], mi_params.CURSOR_COLOR_REST[1], mi_params.CURSOR_COLOR_REST[2]))
    cursor.draw(win)
    cursor_pos_prev = np.array([mi_params.IMAGE_W/2, mi_params.IMAGE_H/2])
    cursor_pos = cursor_pos_prev
    #my_canvas.delete('all')
    #event_arr = np.zeros(((LEN_IDLE_SEC+LEN_RIGHT_SEC+LEN_IDLE_SEC+LEN_LEFT_SEC), 3))
    event_arr_right = np.zeros((mi_params.LEN_DATA_CHUNK_READ, mi_params.NUM_EVENT_TYPES));
    event_arr_right[:, 0] = np.ones(mi_params.LEN_DATA_CHUNK_READ);        # TODO event ids
    event_arr_left = np.zeros((mi_params.LEN_DATA_CHUNK_READ, mi_params.NUM_EVENT_TYPES));
    event_arr_left[:, 1] = np.ones(mi_params.LEN_DATA_CHUNK_READ);        # TODO event ids
    event_arr_idle = np.zeros((mi_params.LEN_DATA_CHUNK_READ, mi_params.NUM_EVENT_TYPES));
    event_arr_idle[:, 2] = np.ones(mi_params.LEN_DATA_CHUNK_READ);        # TODO event ids
    event_arr_calib = np.zeros((mi_params.LEN_DATA_CHUNK_READ, mi_params.NUM_EVENT_TYPES));
    event_arr_calib[:, 3] = np.ones(mi_params.LEN_DATA_CHUNK_READ);        # TODO event ids
    #cursor_color_list = []
    cursor_event_list = []
    cursor_color_arr_raw = np.zeros((int(mi_params.LEN_PERIOD_SEC * mi_params.FREQ_S / mi_params.LEN_DATA_CHUNK_READ), 3))
    color_counter = 0
    for i in range(int(mi_params.LEN_IDLE_SEC * mi_params.FREQ_S / mi_params.LEN_DATA_CHUNK_READ)):
        #cursor_color_list.append(CURSOR_COLOR_IDLE)
        cursor_color_arr_raw[color_counter, :] = mi_params.CURSOR_COLOR_IDLE
        cursor_event_list.append(event_arr_idle)      # r, l, idle, calib
        color_counter += 1
    for i in range(int(mi_params.LEN_RIGHT_SEC * mi_params.FREQ_S / mi_params.LEN_DATA_CHUNK_READ)):
        #cursor_color_list.append(CURSOR_COLOR_RIGHT)
        cursor_color_arr_raw[color_counter, :] = mi_params.CURSOR_COLOR_RIGHT
        cursor_event_list.append(event_arr_right)
        color_counter += 1
    for i in range(int(mi_params.LEN_IDLE_SEC * mi_params.FREQ_S / mi_params.LEN_DATA_CHUNK_READ)):
        #cursor_color_list.append(CURSOR_COLOR_IDLE)
        cursor_color_arr_raw[color_counter, :] = mi_params.CURSOR_COLOR_IDLE
        cursor_event_list.append(event_arr_idle)
        color_counter += 1
    for i in range(int(mi_params.LEN_LEFT_SEC * mi_params.FREQ_S / mi_params.LEN_DATA_CHUNK_READ)):
        #cursor_color_list.append(CURSOR_COLOR_LEFT)
        cursor_color_arr_raw[color_counter, :] = mi_params.CURSOR_COLOR_LEFT
        cursor_event_list.append(event_arr_left)
        color_counter += 1
    conv_window = np.ones((mi_params.LEN_COLOR_CONV_SEC * mi_params.FREQ_S / mi_params.LEN_DATA_CHUNK_READ, 1))\
                  / (int(mi_params.LEN_COLOR_CONV_SEC * mi_params.FREQ_S / mi_params.LEN_DATA_CHUNK_READ))
    cursor_color_arr_ud = np.flipud(cursor_color_arr_raw)
    cursor_color_arr_ud_convd = signal.convolve(cursor_color_arr_ud.T, conv_window.T).T
    cursor_color_arr_final = np.flipud(cursor_color_arr_ud_convd[0:cursor_color_arr_raw.shape[0], :])
    if False:
        plt.figure()
        plt.plot(cursor_color_arr_raw)
        #plt.plot(cursor_color_arr_ud[:, 0])
        #plt.plot(cursor_color_arr_ud_convd[:, 0])
        plt.plot(cursor_color_arr_final)
        #plt.legend(['raw', 'ud', 'ud_convd', 'final'])
        plt.show()


    # Initialize the amplifier
    if not is_simulation_mode:
        print 'Initializing the amp...'
        recorder = Recorder('lslamp', mi_params.FREQ_S, mi_params.LEN_REC_BUF_SEC, mi_params.NUM_CHANNELS)
        thread_rec = threading.Thread(target=recorder.record)
        thread_rec.start()


    # Wait a little until the recorder gets some data
    #time.sleep(2.0)    The obj does this at init
    #if not is_simulation_mode:
    #    while recorder.new_data_counter < mi_params.LEN_DATA_CHUNK_READ:
    #        print 'Waiting for some initial data...'
    #        time.sleep(0.1)


    # Rest-state offset estimation loop
    #X_buf_rest_est = np.zeros((1.2*REST_EST_LEN_SAMPLES, 2))    # 2 relevant channels
    X_buf_raw_live = np.zeros((mi_params.FREQ_S*mi_params.LEN_REC_BUF_SEC, mi_params.NUM_CHANNELS))
    X_events_live = np.zeros((mi_params.FREQ_S*mi_params.LEN_REC_BUF_SEC, mi_params.NUM_EVENT_TYPES))
    X_buf_live = np.zeros((mi_params.FREQ_S*mi_params.LEN_REC_BUF_SEC, 2))
    X_buf_feat_live = np.zeros((mi_params.FREQ_S*mi_params.LEN_REC_BUF_SEC, 1))
    X_feat_log = np.zeros((mi_params.FREQ_S*mi_params.LEN_REC_BUF_SEC/mi_params.LEN_DATA_CHUNK_READ, 1))
    counter = 0
    while counter < (mi_params.LEN_REST_ESTIM_SEC * mi_params.FREQ_S / mi_params.LEN_DATA_CHUNK_READ):
        print 'counter: ', counter

        # Clear the canvas
        win.delete('all')

        #if recorder.is_new_data_available:

        if not is_simulation_mode:
            # Wait for new data and get it
            data_last_chunk = recorder.get_new_data(mi_params.LEN_DATA_CHUNK_READ, mi_params.AMP_WAIT_SEC)
            recorder.acknowledge_new_data()
            print 'recorder.new_data_counter:', recorder.new_data_counter
        else:
            time.sleep(1.0 / (mi_params.FREQ_S/mi_params.LEN_DATA_CHUNK_READ))
            data_last_chunk = 1000.0 * np.random.rand(mi_params.LEN_DATA_CHUNK_READ, mi_params.NUM_CHANNELS)
            #print 'Random data_last_chunk size:', data_last_chunk

        if True:
            # Insert the new sample to our time series
            X_buf_raw_live[((counter+mi_params.LEN_PADDING)*mi_params.LEN_DATA_CHUNK_READ):((counter+mi_params.LEN_PADDING+1)*mi_params.LEN_DATA_CHUNK_READ), :]\
                            = data_last_chunk
            #print 'data_last_chunk:', data_last_chunk
            #data_last_chunk = np.random.rand(LEN_DATA_CHUNK_READ, NUM_CHANNELS)
            #print 'data_last_chunk.shape:', data_last_chunk.shape
            #print '(data_last_chunk[:, 7]-data_last_chunk[:, 3]).shape:', (data_last_chunk[:, 7]-data_last_chunk[:, 3]).shape
            #data_last_reref = data_last_chunk[:, (7, 10)]
            #print 'data_last_reref.shape:', data_last_reref.shape
            data_last_reref = np.array([ (data_last_chunk[:, 7]-data_last_chunk[:, 4]), (data_last_chunk[:, 10]-data_last_chunk[:, 4])]).T  # Re-reference
            #print 'data_last_reref.shape:', data_last_reref.shape
            #print 'data_last_reref:', data_last_reref
            X_buf_live[((counter+mi_params.LEN_PADDING)*mi_params.LEN_DATA_CHUNK_READ):((counter+mi_params.LEN_PADDING+1)*mi_params.LEN_DATA_CHUNK_READ), :] = data_last_reref   # TODO which channel ids
            #print 'X_buf_live[((counter+LEN_PADDING)*LEN_DATA_CHUNK_READ):((counter+LEN_PADDING+1)*LEN_DATA_CHUNK_READ), :]:', X_buf_live[((counter+LEN_PADDING)*LEN_DATA_CHUNK_READ):((counter+LEN_PADDING+1)*LEN_DATA_CHUNK_READ), :]
            X_events_live[((counter+mi_params.LEN_PADDING)*mi_params.LEN_DATA_CHUNK_READ):((counter+mi_params.LEN_PADDING+1)*mi_params.LEN_DATA_CHUNK_READ), :] = event_arr_calib

            # Process the data
            i_2 = (counter+mi_params.LEN_PADDING+1)*mi_params.LEN_DATA_CHUNK_READ
            #print 'numer, denom:', numer, denom
            #print 'X_buf_live[(i_2-M_FIR):i_2, :]', X_buf_live[(i_2-M_FIR):i_2, :]
            X_filt = signal.lfilter(numer, denom, X_buf_live[(i_2-mi_params.M_FIR):i_2, :].T).T
            #X_to_filt = X_buf_live[(i_2-M_FIR):i_2, :]
            #print 'X_to_filt.shape:', X_to_filt.shape
            #X_filt = np.array(Parallel(n_jobs=4)(delayed(signal.lfilter)
            #        (numer, denom, X_to_filt[:, ch]) for ch in range(X_to_filt.shape[1]))).T
            #print 'X_filt:', X_filt
            #print 'X_filt.shape:', X_filt.shape
            X_pow = X_filt ** 2
            #print 'X_pow:', X_pow
            X_pow_mean = np.mean(X_pow, axis=0)
            #print 'X_pow mean:', X_pow_mean
            X_pow_diff = X_pow_mean[0] - X_pow_mean[1]

            #cursor_pos = graphics.Point(IMAGE_W/2 + 100*math.cos(w*counter), IMAGE_H/2)
            #diff_mult = 4000.0  # Ok for simulation
            X_feat = FEAT_MULT_1 * X_pow_diff
            print 'X_feat (rest): ', X_feat
            X_feat_log[counter] = X_feat
            X_buf_feat_live[((counter+mi_params.LEN_PADDING)*mi_params.LEN_DATA_CHUNK_READ):((counter+mi_params.LEN_PADDING+1)*mi_params.LEN_DATA_CHUNK_READ), :]\
                            = X_feat * np.ones((mi_params.LEN_DATA_CHUNK_READ, 1))
            if counter > mi_params.IMP_RESP_LEN:
                cursor_pos = cursor_pos_prev + np.array([X_feat, 0])
                print 'cursor_pos: ', cursor_pos

            cursor_pos_point = graphics.Point(cursor_pos[0], cursor_pos[1])
            cursor_pos_prev = cursor_pos
            cursor = graphics.Circle(cursor_pos_point, cursor_radius)
            #cursor.setFill(CURSOR_COLOR_REST)
            #cursor.setOutline(CURSOR_COLOR_REST)
            cursor.setFill(graphics.color_rgb(mi_params.CURSOR_COLOR_REST[0], mi_params.CURSOR_COLOR_REST[1], mi_params.CURSOR_COLOR_REST[2]))
            cursor.setOutline(graphics.color_rgb(mi_params.CURSOR_COLOR_REST[0], mi_params.CURSOR_COLOR_REST[1], mi_params.CURSOR_COLOR_REST[2]))
            cursor.draw(win)

            #time.sleep(1.0 / (FREQ_S/LEN_DATA_CHUNK_READ)) no
            #win.getMouse()
            counter += 1

        # End of if
    # End of while


    # Get the average rest state offset
    X_feat_rest_offset = np.mean(X_feat_log[(counter-(mi_params.FREQ_S*5.0/mi_params.LEN_DATA_CHUNK_READ)):counter])
    print 'X_feat_log[0:counter]: ', X_feat_log[0:counter]
    print 'X_feat_rest_offset: ', X_feat_rest_offset


    # Cursor control loop
    #counter = 0 go on
    #while True:
    while counter < (mi_params.LEN_REC_SEC * mi_params.FREQ_S / mi_params.LEN_DATA_CHUNK_READ):
        print 'counter: ', counter

        # Clear the canvas
        win.delete('all')

        if not is_simulation_mode:
            # Wait for new data and get it
            data_last_chunk = recorder.get_new_data(mi_params.LEN_DATA_CHUNK_READ, mi_params.AMP_WAIT_SEC)
            recorder.acknowledge_new_data()
            print 'recorder.new_data_counter:', recorder.new_data_counter
        else:
            time.sleep(1.0 / (mi_params.FREQ_S/mi_params.LEN_DATA_CHUNK_READ))
            data_last_chunk = 1000.0 * np.random.rand(mi_params.LEN_DATA_CHUNK_READ, mi_params.NUM_CHANNELS)
            #print 'Random data_last_chunk size:', data_last_chunk

        if True:
            # Insert the new sample to our time series
            X_buf_raw_live[((counter+mi_params.LEN_PADDING)*mi_params.LEN_DATA_CHUNK_READ):((counter+mi_params.LEN_PADDING+1)*mi_params.LEN_DATA_CHUNK_READ), :] = data_last_chunk
            #print 'data_last_chunk:', data_last_chunk
            #data_last_chunk = np.random.rand(LEN_DATA_CHUNK_READ, NUM_CHANNELS)
            #print 'data_last_chunk.shape:', data_last_chunk.shape
            #print '(data_last_chunk[:, 7]-data_last_chunk[:, 3]).shape:', (data_last_chunk[:, 7]-data_last_chunk[:, 3]).shape
            #data_last_reref = data_last_chunk[:, (7, 10)]
            #print 'data_last_reref.shape:', data_last_reref.shape
            data_last_reref = np.array([ (data_last_chunk[:, 7]-data_last_chunk[:, 4]), (data_last_chunk[:, 10]-data_last_chunk[:, 4])]).T  # Re-reference
            #print 'data_last_reref.shape:', data_last_reref.shape
            #print 'data_last_reref:', data_last_reref
            X_buf_live[((counter+mi_params.LEN_PADDING)*mi_params.LEN_DATA_CHUNK_READ):((counter+mi_params.LEN_PADDING+1)*mi_params.LEN_DATA_CHUNK_READ), :]\
                            = data_last_reref   # TODO which channel ids
            #print 'X_buf_live[((counter+LEN_PADDING)*LEN_DATA_CHUNK_READ):((counter+LEN_PADDING+1)*LEN_DATA_CHUNK_READ), :]:', X_buf_live[((counter+LEN_PADDING)*LEN_DATA_CHUNK_READ):((counter+LEN_PADDING+1)*LEN_DATA_CHUNK_READ), :]
            X_events_live[((counter+mi_params.LEN_PADDING)*mi_params.LEN_DATA_CHUNK_READ):((counter+mi_params.LEN_PADDING+1)*mi_params.LEN_DATA_CHUNK_READ), :]\
                            = cursor_event_list[counter % int(mi_params.LEN_PERIOD_SEC * mi_params.FREQ_S / mi_params.LEN_DATA_CHUNK_READ)]

            # Process the data
            i_2 = (counter+mi_params.LEN_PADDING+1)*mi_params.LEN_DATA_CHUNK_READ
            #print 'numer, denom:', numer, denom
            #print 'X_buf_live[(i_2-M_FIR):i_2, :]', X_buf_live[(i_2-M_FIR):i_2, :]
            X_filt = signal.lfilter(numer, denom, X_buf_live[(i_2-mi_params.M_FIR):i_2, :].T).T
            #X_to_filt = X_buf_live[(i_2-M_FIR):i_2, :]
            #print 'X_to_filt.shape:', X_to_filt.shape
            #X_filt = np.array(Parallel(n_jobs=4)(delayed(signal.lfilter)
            #        (numer, denom, X_to_filt[:, ch]) for ch in range(X_to_filt.shape[1]))).T
            #print 'X_filt:', X_filt
            #print 'X_filt.shape:', X_filt.shape
            X_pow = X_filt ** 2
            #print 'X_pow:', X_pow
            X_pow_mean = np.mean(X_pow, axis=0)
            print 'X_pow mean:', X_pow_mean
            X_pow_diff = X_pow_mean[0] - X_pow_mean[1]

            #cursor_pos = graphics.Point(IMAGE_W/2 + 100*math.cos(w*counter), IMAGE_H/2)
            #diff_mult = 4000.0  # Ok for simulation
            X_feat_pre = FEAT_MULT_1*X_pow_diff - X_feat_rest_offset
            print 'X_feat_pre: ', X_feat_pre
            X_feat = FEAT_MULT_2 * X_feat_pre
            print 'X_feat: ', X_feat
            X_feat_log[counter] = X_feat
            X_buf_feat_live[((counter+mi_params.LEN_PADDING)*mi_params.LEN_DATA_CHUNK_READ):((counter+mi_params.LEN_PADDING+1)*mi_params.LEN_DATA_CHUNK_READ), :]\
                            = X_feat * np.ones((mi_params.LEN_DATA_CHUNK_READ, 1))
            if counter > mi_params.IMP_RESP_LEN:
                cursor_pos = cursor_pos_prev + np.array([X_feat, 0])
                print 'cursor_pos: ', cursor_pos

            cursor_pos_point = graphics.Point(cursor_pos[0], cursor_pos[1])
            cursor_pos_prev = cursor_pos
            cursor = graphics.Circle(cursor_pos_point, cursor_radius)
            #cursor.setFill(cursor_color_list[counter % int(LEN_PERIOD_SEC * FREQ_S / LEN_DATA_CHUNK_READ)])
            #cursor.setOutline(cursor_color_list[counter % int(LEN_PERIOD_SEC * FREQ_S / LEN_DATA_CHUNK_READ)])
            color_temp = cursor_color_arr_final[counter % int(mi_params.LEN_PERIOD_SEC * mi_params.FREQ_S / mi_params.LEN_DATA_CHUNK_READ)]
            cursor.setFill(graphics.color_rgb(color_temp[0], color_temp[1], color_temp[2]))
            cursor.setOutline(graphics.color_rgb(color_temp[0], color_temp[1], color_temp[2]))
            cursor.draw(win)

            #time.sleep(1.0 / (FREQ_S/LEN_DATA_CHUNK_READ)) no
            #win.getMouse()
            counter += 1

        # End of if
    # End of while


    # Stop recording
    recorder.stop_recording()


    # Close the window
    win.close()




    # Save data to file
    time_axis = np.arange(X_buf_live.shape[0]).reshape((X_buf_live.shape[0], 1))
    print 'time_axis.shape:', time_axis.shape
    #rec_data, rec_times = recorder.get_data() no cuz of simu
    #data_merged = np.concatenate((time_axis, X, marker_axis_arr), axis=1)
    data_merged = np.concatenate((time_axis, X_buf_raw_live, X_events_live, X_buf_live, X_buf_feat_live), axis=1)
    print 'data_merged.shape: ', data_merged.shape
    time_save = datetime.now()
    np.savetxt('BME_BCI_MI_REC_{0}{1:02}{2:02}_{3:02}h{4:02}m{5:02}s.csv'.format(time_save.year, time_save.month, time_save.day,
               time_save.hour, time_save.minute, time_save.second),
               X=data_merged, fmt='%.8f', delimiter=",",
               header=str(1), comments='time, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, rh, lh, idle, calib, b1, b2, feat')  # TODO


    print 'cursor_func(.) terminates.'
pa = 0
pb = 0
pc = 0
for i, p in enumerate(points):
    if i % 3 == 0:
        pa = p
    if i % 3 == 1:
        pb = p
    if i % 3 == 2:
        pc = p
        polygon = gl.Polygon(pa, pb, pc)
        ci = int(i / 3) # color index
        red = colors[ci][0] * 255
        green = colors[ci][1] * 255
        blue = colors[ci][2] * 255 
        currentColor = gl.color_rgb(red, green, blue)
        polygon.setFill(currentColor)
        polygon.setOutline(currentColor)
        polygon.draw(win)

print len(points)
var = raw_input("Press any to exit...")
"""
a = np.matrix([[3, 5], [4, 6]])
b = a.sum(axis=1)
print a
print b
"""

Beispiel #48
0
#  Copyright (c) 2008 Brian Mason. All rights reserved.
#
#  Wood graphic from http://www.time2photoshop.com/create-a-wood-texture.
#  All other graphics created by myself in Adobe Photoshop CS3.
#  Button class adapted from Button class that was included with the textbook with some methods removed, added, or changed.
#
#  NOTE: This file uses a slightly edited version of the graphics module that allows an image's undraw method to be called when it has not yet been drawn without crashing the program.
#  It will not work with the normal version of the graphics module, so use the one provided.

import graphics
from time import sleep

#  These are declared here because I got sick of putting quotation marks around white and black, among other things.
white = 0
black = 1
textColor = graphics.color_rgb(229, 229, 229)
whitePath = 'othello_graphics/white.gif'
blackPath = 'othello_graphics/black.gif'
boardPath = 'othello_graphics/board.gif'
bottomPath = 'othello_graphics/bottomBar.gif'
movePath = 'othello_graphics/move.gif'
blackTokenPath = 'othello_graphics/blackToken.gif'
whiteTokenPath = 'othello_graphics/whiteToken.gif'
choosePlayerPath = 'othello_graphics/playerWindow.gif'
playAgainPath = 'othello_graphics/playAgain.gif'
quitPath = 'othello_graphics/quitButton.gif'
reallyQuitPath = 'othello_graphics/reallyQuit.gif'
winMessagePath = 'othello_graphics/winMessage.gif'
difficultyPath = 'othello_graphics/difficultyWindow.gif'

#  These are various board weight schemes.
def colorscheme(num, iteration):
    # return color based on a float
    r,g,b = modifier(num, iteration)
    new = graphics.color_rgb(r,g,b)
    return new
Beispiel #50
0
# returns: the scheme (dict)
def getScheme(name):
	return __schemes[name.lower()]


# creates a dictionary with the right keys for game.TileSettings
# syntax: createScheme(shadedFill, shadedOutline, unshadedFill, unshadedOutline)
# parameters:
	# shadedFill: color of a shaded tile (graphics.color_rgb or string)
	# shadedOutline: color of a shaded tile outline (graphics.color_rgb or string)
	# unshadedFill: color of an unshaded tile (graphics.color_rgb or string)
	# unshadedOutline: color of an unshaded tile outline (graphics.color_rgb or string)
# returns the color scheme (dict)
def createScheme(shadedFill, shadedOutline, unshadedFill, unshadedOutline):
	return {
		"shadedFill": shadedFill,
		"shadedOutline": shadedOutline,
		"unshadedFill": unshadedFill,
		"unshadedOutline": unshadedOutline
	}
	
__schemes = {
	"classic": createScheme("black", "black", "white", "black"),
	"grassy": createScheme(color_rgb(50,50,50), color_rgb(50,50,50), "green", color_rgb(50,50,50)),
	"watermelon": createScheme("green", color_rgb(50,50,50), "pink", color_rgb(50,50,50)),
	"eighties": createScheme(color_rgb(237,0,140), color_rgb(146,39,143), color_rgb(254,242,0), color_rgb(1,165,200)),
	"modern": createScheme("black", "white", "white", "black"),
	"reverse": createScheme("white", "white", "black", "white"),
	"sleek": createScheme("black", "black", "white", "white"),
}
Beispiel #51
0
# GLOBALS
# Set sizes in pixels
GRID_SIZE   = 30
MARGIN      = GRID_SIZE
PAC_SIZE    = GRID_SIZE * 0.8
PAC_SPEED   = 0.25 # grid points per tick
GHOST_SPEED = 0.20
FOOD_SIZE   = GRID_SIZE * 0.15
DEG_TO_RAD  = math.pi / 180
CAP_SIZE    = GRID_SIZE * 0.3
SCARED_TIME = 100
WARN_TIME   = 50

# Set colors
BACKGROUND_COLOR = 'black'
WALL_COLOR       = gx.color_rgb(int(0.6 * 255), int(0.9 * 255), int(0.9 * 255))
PAC_COLOR        = 'yellow'
FOOD_COLOR       = 'red'
GHOST_COLORS     = ['red','green','blue','purple']
CAP_COLOR        = 'white'
SCARED_COLOR     = 'white'

# Ghost shape layout
GHOST_SHAPE = [
    ( 0.00,  0.50),
    ( 0.25,  0.75),
    ( 0.50,  0.50),
    ( 0.75,  0.75),
    ( 0.75, -0.50),
    ( 0.50, -0.75),
    (-0.50, -0.75),
Beispiel #52
0
#!/usr/bin/env python
import argparse
from math import sin, cos, pi

from graphics import GraphWin, Circle, Point, Line, color_rgb

from difference import DiffState

WIN_SIZE = 800
R = WIN_SIZE / 3
CENTER = (WIN_SIZE / 2, WIN_SIZE / 2)
set_color = color_rgb(255, 0, 0)
all_color = color_rgb(200, 200, 200)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--size", type=int, default=3, help="Size of k")
    args = parser.parse_args()

    win = GraphWin("My Circle", WIN_SIZE, WIN_SIZE)

    k = args.size
    m = k * (k - 1) + 1
    r = min(pi * R / m * 0.50, 20)

    ds = DiffState(k)
    ds.search()

    points = []
    for i in range(m):