本文整理汇总了Python中tkinter.Canvas.update方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.update方法的具体用法?Python Canvas.update怎么用?Python Canvas.update使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.Canvas
的用法示例。
在下文中一共展示了Canvas.update方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_pinballview
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import update [as 别名]
def run_pinballview(width, height, configuration):
"""
Changed from original Pierre-Luc Bacon implementation to reflect
the visualization changes in the PinballView Class.
"""
width, height = float(width), float(height)
master = Tk()
master.title('RLPY Pinball')
screen = Canvas(master, width=500.0, height=500.0)
screen.configure(background='LightGray')
screen.pack()
environment = PinballModel(configuration)
environment_view = PinballView(screen, width, height, environment)
actions = [
PinballModel.ACC_X,
PinballModel.DEC_Y,
PinballModel.DEC_X,
PinballModel.ACC_Y,
PinballModel.ACC_NONE]
done = False
while not done:
user_action = np.random.choice(actions)
environment_view.blit()
if environment.episode_ended():
done = True
if environment.take_action(user_action) == environment.END_EPISODE:
done = True
environment_view.blit()
screen.update()
示例2: Wall
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import update [as 别名]
class Wall(object):
MIN_RED = MIN_GREEN = MIN_BLUE = 0x0
MAX_RED = MAX_GREEN = MAX_BLUE = 0xFF
PIXEL_WIDTH = 50
def __init__(self, width, height):
self.width = width
self.height = height
self._tk_init()
self.pixels = [(0, 0, 0) for i in range(self.width * self.height)]
def _tk_init(self):
self.root = Tk()
self.root.title("ColorWall %d x %d" % (self.width, self.height))
self.root.resizable(0, 0)
self.frame = Frame(self.root, bd=5, relief=SUNKEN)
self.frame.pack()
self.canvas = Canvas(self.frame,
width=self.PIXEL_WIDTH * self.width,
height=self.PIXEL_WIDTH * self.height,
bd=0, highlightthickness=0)
self.canvas.pack()
self.root.update()
def set_pixel(self, x, y, hsv):
self.pixels[self.width * y + x] = hsv
def get_pixel(self, x, y):
return self.pixels[self.width * y + x]
def draw(self):
self.canvas.delete(ALL)
for x in range(len(self.pixels)):
x_0 = (x % self.width) * self.PIXEL_WIDTH
y_0 = (x / self.width) * self.PIXEL_WIDTH
x_1 = x_0 + self.PIXEL_WIDTH
y_1 = y_0 + self.PIXEL_WIDTH
hue = "#%02x%02x%02x" % self._get_rgb(self.pixels[x])
self.canvas.create_rectangle(x_0, y_0, x_1, y_1, fill=hue)
self.canvas.update()
def clear(self):
for i in range(self.width * self.height):
self.pixels[i] = (0, 0, 0)
def _hsv_to_rgb(self, hsv):
rgb = colorsys.hsv_to_rgb(*hsv)
red = self.MAX_RED * rgb[0]
green = self.MAX_GREEN * rgb[1]
blue = self.MAX_BLUE * rgb[2]
return (red, green, blue)
def _get_rgb(self, hsv):
red, green, blue = self._hsv_to_rgb(hsv)
red = int(float(red) / (self.MAX_RED - self.MIN_RED) * 0xFF)
green = int(float(green) / (self.MAX_GREEN - self.MIN_GREEN) * 0xFF)
blue = int(float(blue) / (self.MAX_BLUE - self.MIN_BLUE) * 0xFF)
return (red, green, blue)
示例3: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import update [as 别名]
def __init__(self, root, x1, y1, x2, y2):
t = time.time()
self.img = PhotoImage(width=wid, height=hei)
canv = Canvas(root, width = wid, height = hei)
canv.pack()
canv.create_image(0, 0, image = self.img, anchor=NW)
dx = abs(x2-x1)/wid
dy = abs(y2-y1)/hei
#c = complex(-0.8, 0.156)
#c = complex(-0.74543,+0.11301)
#c = complex(-0.1,0.651)
#c = complex(-0.70176,-0.3842)
c = complex(-0.835,-0.2321)
#c = complex(-0.74434, -0.10772)
#c = complex(-0.62772, 0.42193)
y = y1
for j in range(hei):
line = '{'
x = x1
for i in range(wid):
x = x + dx
a = complex(x, y)
for k in range(maxiter):
a = a*a + c
if(abs(a) > blowup):
break
if(k == maxiter-1):
#line += '#%02x%02x%02x ' % (255,255,255)
line += '#%02x%02x%02x ' % (0,0,0)
else:
line += '#%02x%02x%02x ' % color(k)
line += '}'
self.img.put(line, (0, j))
canv.update()
y = y - dy
print(time.time() - t)
示例4: Visual
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import update [as 别名]
#.........这里部分代码省略.........
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
示例5: Schedules
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import update [as 别名]
#.........这里部分代码省略.........
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")
示例6: Classes
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import update [as 别名]
#.........这里部分代码省略.........
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")
示例7: rmap
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import update [as 别名]
#.........这里部分代码省略.........
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()
示例8: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import update [as 别名]
#.........这里部分代码省略.........
new_ball = Ball(radius, x, y, vx, vy, mass)
if not new_ball.check_overlap(self.balls):
self.balls.append(new_ball)
break
#init_wall_collision_times will set all of the balls' minimum collision time
#for both horizontal and vertical walls and store that time in their respective arrays
def init_wall_collision_times(self):
for i in np.arange(len(self.balls)):
bi = self.balls[i]
tix = bi.horizontal_wall_collision_time(self.min_x, self.max_x)
tiy = bi.vertical_wall_collision_time(self.min_y, self.max_y)
self.PQ.insert(i, -1, tix + self.time, self.balls[i].count, -1)
self.PQ.insert(-1, i, tiy + self.time, -1, self.balls[i].count)
return
#init_ball_collision_times will set all of the balls' minimum collision time
#with all other balls and store that time within the ith and jth index of
#PQ.ball_collision_time
def init_ball_collision_times(self):
for i in np.arange(self.num_balls):
bi = self.balls[i]
for j in np.arange(i+1, self.num_balls):
bj = self.balls[j]
tij = bi.ball_collision_time(bj)
self.PQ.insert(i, j, tij + self.time, self.balls[i].count, self.balls[j].count)
# self.ball_collision_times[i][j] = tij
# self.ball_collision_times[j][i] = tij
return
#update collision times is meant to update collision times of ball i with all
#walls (horizontal and vertical) and all other balls within the PQ array
def update_collision_times(self, i):
bi = self.balls[i]
tix = bi.horizontal_wall_collision_time(self.min_x, self.max_x)
tiy = bi.vertical_wall_collision_time(self.min_y, self.max_y)
self.PQ.insert(i, -1, tix + self.time,self.balls[i].count, -1)
self.PQ.insert(-1, i, tiy + self.time, -1, self.balls[i].count)
for j in np.arange(self.num_balls):
bj = self.balls[j]
tij = bi.ball_collision_time(bj) + self.time
if i > j:
self.PQ.insert(j, i, tij,self.balls[j].count,self.balls[i].count)
else:
self.PQ.insert(i, j, tij,self.balls[i].count, self.balls[j].count)
return
#draw will draw the borders and all balls within self.balls
def draw(self):
#Draw walls
self.canvas.create_line((self.min_x, self.min_y), (self.min_x, self.max_y), fill = "red")
self.canvas.create_line((self.min_x, self.min_y), (self.max_x, self.min_y), fill = "red")
self.canvas.create_line((self.min_x, self.max_y), (self.max_x, self.max_y), fill = "red")
self.canvas.create_line((self.max_x, self.min_y), (self.max_x, self.max_y), fill = "red")
#Draw balls
for b in self.balls:
obj = self.canvas.create_oval(b.x - b.radius, b.y - b.radius, b.x + b.radius, b.y + b.radius, outline=b.tk_rgb, fill=b.tk_rgb)
self.ball_handles[b] = obj
self.canvas.update()
#refresh is called to update the state of the simulation
#-each refresh call can be considered one iteration of the simulation
#-all balls will be moved and if there is a collision then it will be computed
def refresh(self):
示例9: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import update [as 别名]
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")
#.........这里部分代码省略.........
示例10: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import update [as 别名]
class Painter:
def __init__(
self, root, width=800, height=600, offset=5, min_radius=5, max_radius=10, num_balls=20, refresh_speed=5
):
# Draw frame etc
self.app_frame = Frame(root)
self.app_frame.pack()
self.canvas = Canvas(self.app_frame, width=width, height=height)
self.canvas_size = (int(self.canvas.cget("width")), int(self.canvas.cget("height")))
self.canvas.pack()
self.refresh_speed = refresh_speed
# Work area
self.min_x = offset
self.max_x = width - offset
self.min_y = offset
self.max_y = height - offset
self.num_balls = num_balls
self.balls = []
self.ball_handles = dict()
self.init_balls(max_radius, min_radius, num_balls)
self.time = 0
self.wall_collision_times = np.zeros(num_balls)
self.init_wall_collision_times()
self.ball_collision_times = np.zeros((num_balls, num_balls))
self.init_ball_collision_times()
self.draw()
self.refresh()
return
def init_balls(self, max_radius, min_radius, num_balls):
for i in np.arange(num_balls):
while True:
radius = (max_radius - min_radius) * rand.random_sample() + min_radius
ball_min_x = self.min_x + radius
ball_max_x = self.max_x - radius
x = (ball_max_x - ball_min_x) * rand.random_sample() + ball_min_x
ball_min_y = self.min_y + radius
ball_max_y = self.max_y - radius
y = (ball_max_y - ball_min_y) * rand.random_sample() + ball_min_y
vx = rand.random_sample()
vy = rand.random_sample()
mass = rand.random_sample()
new_ball = Ball(radius, x, y, vx, vy, mass)
if not new_ball.check_overlap(self.balls):
self.balls.append(new_ball)
break
def draw(self):
# Draw walls
self.canvas.create_line((self.min_x, self.min_y), (self.min_x, self.max_y), fill="red")
self.canvas.create_line((self.min_x, self.min_y), (self.max_x, self.min_y), fill="red")
self.canvas.create_line((self.min_x, self.max_y), (self.max_x, self.max_y), fill="red")
self.canvas.create_line((self.max_x, self.min_y), (self.max_x, self.max_y), fill="red")
# Draw balls
for b in self.balls:
obj = self.canvas.create_oval(b.x - b.radius, b.y - b.radius, b.x + b.radius, b.y + b.radius)
self.ball_handles[b] = obj
self.canvas.update()
def next_wall_collision_idx(self):
collided = []
for i in np.arange(self.num_balls):
if self.wall_collision_times[i] <= self.time:
collided.append(i)
return collided
def next_ball_collision_idx(self):
min_i = 0
min_j = 0
collided = []
# min_tij = float('inf')
for i in np.arange(self.num_balls):
for j in np.arange(i, self.num_balls):
tij = self.ball_collision_times[i][j]
if tij <= self.time:
collided.append((i, j))
return collided
# CODE YOU NEED TO IMPLEMENT
def init_wall_collision_times(self):
for i in np.arange(self.num_balls):
self.wall_collision_times[i] = self.balls[i].compute_wall_collision_time(
self, self.min_x, self.max_x, self.min_y, self.max_y
)
# def update_wall_collision_time(self, i):
#
def init_ball_collision_times(self):
#.........这里部分代码省略.........
示例11: Pinball
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import update [as 别名]
class Pinball(Domain):
"""
The goal of this domain is to maneuver a small ball on a plate into a hole.
The plate may contain obstacles which should be avoided.
**STATE:**
The state is given by a 4-dimensional vector, consisting of position and
velocity of the ball.
**ACTIONS:**
There are 5 actions, standing for slanting the plat in x or y direction
or a horizontal position
of the plate.
**REWARD:**
Slanting the plate costs -4 reward in addition to -1 reward for each timestep.
When the ball reaches the hole, the agent receives 10000 units of reward.
**REFERENCE:**
.. seealso::
G.D. Konidaris and A.G. Barto:
*Skill Discovery in Continuous Reinforcement Learning Domains using Skill Chaining.*
Advances in Neural Information Processing Systems 22, pages 1015-1023, December 2009.
"""
#: default location of config files shipped with rlpy
default_config_dir = os.path.join(
__rlpy_location__,
"Domains",
"PinballConfigs")
def __init__(self, noise=.1, episodeCap=1000,
configuration=os.path.join(default_config_dir, "pinball_simple_single.cfg")):
"""
configuration:
location of the configuration file
episodeCap:
maximum length of an episode
noise:
with probability noise, a uniformly random action is executed
"""
self.NOISE = noise
self.configuration = configuration
self.screen = None
self.episodeCap = episodeCap
self.actions_num = 5
self.actions = [
PinballModel.ACC_X,
PinballModel.DEC_Y,
PinballModel.DEC_X,
PinballModel.ACC_Y,
PinballModel.ACC_NONE]
self.statespace_limits = np.array(
[[0.0, 1.0], [0.0, 1.0], [-2.0, 2.0], [-2.0, 2.0]])
self.continuous_dims = [4]
super(Pinball, self).__init__()
self.environment = PinballModel(
self.configuration,
random_state=self.random_state)
def showDomain(self, a):
if self.screen is None:
master = Tk()
master.title('RLPY Pinball')
self.screen = Canvas(master, width=500.0, height=500.0)
self.screen.configure(background='LightGray')
self.screen.pack()
self.environment_view = PinballView(
self.screen,
500.0,
500.0,
self.environment)
self.environment_view.blit()
self.screen.pack()
self.screen.update()
def step(self, a):
s = self.state
[self.environment.ball.position[0],
self.environment.ball.position[1],
self.environment.ball.xdot,
self.environment.ball.ydot] = s
if self.random_state.random_sample() < self.NOISE:
# Random Move
a = self.random_state.choice(self.possibleActions())
reward = self.environment.take_action(a)
self.environment._check_bounds()
state = np.array(self.environment.get_state())
self.state = state.copy()
return reward, state, self.isTerminal(), self.possibleActions()
def s0(self):
self.environment.ball.position[0], self.environment.ball.position[
1] = self.environment.start_pos
self.environment.ball.xdot, self.environment.ball.ydot = 0.0, 0.0
self.state = np.array(
[self.environment.ball.position[0], self.environment.ball.position[1],
self.environment.ball.xdot, self.environment.ball.ydot])
return self.state, self.isTerminal(), self.possibleActions()
#.........这里部分代码省略.........
示例12: World
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import update [as 别名]
#.........这里部分代码省略.........
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)
示例13: __init__
# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import update [as 别名]
#.........这里部分代码省略.........
414, 10, width=2)
self.canvas.create_line(354, 275 - cos(2*pi/360*deg)*leng,
354, 10, width=2)
self.canvas.create_line(354, 10, 414, 10, width=2)
self.canvas.pack()
def animate(self):
while (self.machine.current_state not in self.machine.accept_states) and\
(self.machine.current_state not in self.machine.reject_states):
try:
self.step()
except TclError:
return
self.finalise()
return
def step(self):
if self.machine.current_state in self.machine.accept_states or\
self.machine.current_state in self.machine.reject_states:
self.finalise()
return
left_from_head = ''
right_from_head = ''
head = str(self.machine.tape.middle)
for i in self.machine.tape.right:
right_from_head += str(i)
for i in self.machine.tape.left:
left_from_head += str(i)
if len(right_from_head) > 8:
right_from_head = right_from_head[:8]
elif len(right_from_head) < 8:
right_from_head = right_from_head + '_'*(8 - len(right_from_head))
if len(left_from_head) > 8:
left_from_head = left_from_head[-8:]
elif len(left_from_head) < 8:
left_from_head = '_'*(8 - len(left_from_head)) + left_from_head
text = left_from_head + head + right_from_head
for i in range(17):
if self.tape_symbol[i]:
self.canvas.delete(self.tape_symbol[i])
self.tape_symbol[i] = self.canvas.create_text(10 + i * 44, 275,
text="%c" % text[i],
font=("Default",
30),
anchor="nw")
stack_text = ''
for i in range(min(5, len(self.machine.stack))):
if self.machine.stack[i] is not None:
stack_text += self.machine.stack[i]
else:
stack_text = '_' + stack_text
for i in range(min(5, len(self.machine.stack))):
if self.stack_symbol[i]:
self.canvas.delete(self.stack_symbol[i])
self.stack_symbol[i] = self.canvas.create_text(714, 10+i*44,
text="%c" %
stack_text[i],
font=("Default",
30),
anchor="nw")
rule = self.machine.step()
if rule is None:
self.finalise()
return
else:
self.canvas.delete(self.text_rule)
self.text_rule = self.canvas.create_text(54 + 374-sin(pi/4)*150,
275 - cos(pi/4)*150,
text="%s" % rule,
font=("Default", 12),
anchor="nw")
self.canvas.update()
def finalise(self):
stack_id = self.canvas.create_text(150, 350, font=("Default", 30),
anchor='nw')
self.canvas.itemconfig(stack_id)
self.canvas.insert(stack_id, 12, "%s" % ''.join(self.machine.stack))
mesg = self.canvas.create_text(0, 0, font=("Default", 30), anchor="nw")
self.canvas.itemconfig(mesg)
if self.machine.current_state in self.machine.accept_states:
self.canvas.insert(mesg, 12, "%s" % 'Accept !!!')
photo = PhotoImage(file="img/HappyTuring.gif")
label = Label(image=photo)
label.pack()
self.root.mainloop()
elif self.machine.current_state in self.machine.reject_states:
self.canvas.insert(mesg, 12, "%s" % 'Reject !!!')
photo = PhotoImage(file="img/SadTuring.gif")
label = Label(image=photo)
label.pack()
self.root.mainloop()
else:
self.canvas.insert(mesg, 12, "%s" % 'Halt !!!')
photo = PhotoImage(file="img/ConfusedTuring.gif")
label = Label(image=photo)
label.pack()
self.root.mainloop()