Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

graphicsUtils.py 12 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
  1. # graphicsUtils.py
  2. # ----------------
  3. # Licensing Information: Please do not distribute or publish solutions to this
  4. # project. You are free to use and extend these projects for educational
  5. # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
  6. # John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
  7. # For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html
  8. import sys
  9. import math
  10. import random
  11. import string
  12. import time
  13. import types
  14. import tkinter
  15. _Windows = sys.platform == 'win32' # True if on Win95/98/NT
  16. _root_window = None # The root window for graphics output
  17. _canvas = None # The canvas which holds graphics
  18. _canvas_xs = None # Size of canvas object
  19. _canvas_ys = None
  20. _canvas_x = None # Current position on canvas
  21. _canvas_y = None
  22. _canvas_col = None # Current colour (set to black below)
  23. _canvas_tsize = 12
  24. _canvas_tserifs = 0
  25. def formatColor(r, g, b):
  26. return '#%02x%02x%02x' % (int(r * 255), int(g * 255), int(b * 255))
  27. def colorToVector(color):
  28. return map(lambda x: int(x, 16) / 256.0, [color[1:3], color[3:5], color[5:7]])
  29. if _Windows:
  30. _canvas_tfonts = ['times new roman', 'lucida console']
  31. else:
  32. _canvas_tfonts = ['times', 'lucidasans-24']
  33. pass # XXX need defaults here
  34. def sleep(secs):
  35. global _root_window
  36. if _root_window == None:
  37. time.sleep(secs)
  38. else:
  39. _root_window.update_idletasks()
  40. _root_window.after(int(1000 * secs), _root_window.quit)
  41. _root_window.mainloop()
  42. def begin_graphics(width=640, height=480, color=formatColor(0, 0, 0), title=None):
  43. global _root_window, _canvas, _canvas_x, _canvas_y, _canvas_xs, _canvas_ys, _bg_color
  44. # Check for duplicate call
  45. if _root_window is not None:
  46. # Lose the window.
  47. _root_window.destroy()
  48. # Save the canvas size parameters
  49. _canvas_xs, _canvas_ys = width - 1, height - 1
  50. _canvas_x, _canvas_y = 0, _canvas_ys
  51. _bg_color = color
  52. # Create the root window
  53. _root_window = tkinter.Tk()
  54. _root_window.protocol('WM_DELETE_WINDOW', _destroy_window)
  55. _root_window.title(title or 'Graphics Window')
  56. _root_window.resizable(0, 0)
  57. # Create the canvas object
  58. try:
  59. _canvas = tkinter.Canvas(_root_window, width=width, height=height)
  60. _canvas.pack()
  61. draw_background()
  62. _canvas.update()
  63. except:
  64. _root_window = None
  65. raise
  66. # Bind to key-down and key-up events
  67. _root_window.bind("<KeyPress>", _keypress)
  68. _root_window.bind("<KeyRelease>", _keyrelease)
  69. _root_window.bind("<FocusIn>", _clear_keys)
  70. _root_window.bind("<FocusOut>", _clear_keys)
  71. _root_window.bind("<Button-1>", _leftclick)
  72. _root_window.bind("<Button-2>", _rightclick)
  73. _root_window.bind("<Button-3>", _rightclick)
  74. _root_window.bind("<Control-Button-1>", _ctrl_leftclick)
  75. _clear_keys()
  76. _leftclick_loc = None
  77. _rightclick_loc = None
  78. _ctrl_leftclick_loc = None
  79. def _leftclick(event):
  80. global _leftclick_loc
  81. _leftclick_loc = (event.x, event.y)
  82. def _rightclick(event):
  83. global _rightclick_loc
  84. _rightclick_loc = (event.x, event.y)
  85. def _ctrl_leftclick(event):
  86. global _ctrl_leftclick_loc
  87. _ctrl_leftclick_loc = (event.x, event.y)
  88. def wait_for_click():
  89. while True:
  90. global _leftclick_loc
  91. global _rightclick_loc
  92. global _ctrl_leftclick_loc
  93. if _leftclick_loc != None:
  94. val = _leftclick_loc
  95. _leftclick_loc = None
  96. return val, 'left'
  97. if _rightclick_loc != None:
  98. val = _rightclick_loc
  99. _rightclick_loc = None
  100. return val, 'right'
  101. if _ctrl_leftclick_loc != None:
  102. val = _ctrl_leftclick_loc
  103. _ctrl_leftclick_loc = None
  104. return val, 'ctrl_left'
  105. sleep(0.05)
  106. def draw_background():
  107. corners = [(0, 0), (0, _canvas_ys), (_canvas_xs, _canvas_ys), (_canvas_xs, 0)]
  108. polygon(corners, _bg_color, fillColor=_bg_color, filled=True, smoothed=False)
  109. def _destroy_window(event=None):
  110. sys.exit(0)
  111. # global _root_window
  112. # _root_window.destroy()
  113. # _root_window = None
  114. # print("DESTROY")
  115. def end_graphics():
  116. global _root_window, _canvas, _mouse_enabled
  117. try:
  118. try:
  119. sleep(1)
  120. if _root_window != None:
  121. _root_window.destroy()
  122. except(SystemExit, e):
  123. print('Ending graphics raised an exception:', e)
  124. finally:
  125. _root_window = None
  126. _canvas = None
  127. _mouse_enabled = 0
  128. _clear_keys()
  129. def clear_screen(background=None):
  130. global _canvas_x, _canvas_y
  131. _canvas.delete('all')
  132. draw_background()
  133. _canvas_x, _canvas_y = 0, _canvas_ys
  134. def polygon(coords, outlineColor, fillColor=None, filled=1, smoothed=1, behind=0, width=1):
  135. c = []
  136. for coord in coords:
  137. c.append(coord[0])
  138. c.append(coord[1])
  139. if fillColor == None: fillColor = outlineColor
  140. if filled == 0: fillColor = ""
  141. poly = _canvas.create_polygon(c, outline=outlineColor, fill=fillColor, smooth=smoothed,
  142. width=width)
  143. if behind > 0:
  144. _canvas.tag_lower(poly, behind) # Higher should be more visible
  145. return poly
  146. def square(pos, r, color, filled=1, behind=0):
  147. x, y = pos
  148. coords = [(x - r, y - r), (x + r, y - r), (x + r, y + r), (x - r, y + r)]
  149. return polygon(coords, color, color, filled, 0, behind=behind)
  150. def circle(pos, r, outlineColor, fillColor, endpoints=None, style='pieslice', width=2):
  151. x, y = pos
  152. x0, x1 = x - r - 1, x + r
  153. y0, y1 = y - r - 1, y + r
  154. if endpoints == None:
  155. e = [0, 359]
  156. else:
  157. e = list(endpoints)
  158. while e[0] > e[1]: e[1] = e[1] + 360
  159. return _canvas.create_arc(x0, y0, x1, y1, outline=outlineColor, fill=fillColor,
  160. extent=e[1] - e[0], start=e[0], style=style, width=width)
  161. def image(pos, file="../../blueghost.gif"):
  162. x, y = pos
  163. # img = PhotoImage(file=file)
  164. return _canvas.create_image(x, y, image=tkinter.PhotoImage(file=file), anchor=tkinter.NW)
  165. def refresh():
  166. _canvas.update_idletasks()
  167. def moveCircle(id, pos, r, endpoints=None):
  168. global _canvas_x, _canvas_y
  169. x, y = pos
  170. # x0, x1 = x - r, x + r + 1
  171. # y0, y1 = y - r, y + r + 1
  172. x0, x1 = x - r - 1, x + r
  173. y0, y1 = y - r - 1, y + r
  174. if endpoints == None:
  175. e = [0, 359]
  176. else:
  177. e = list(endpoints)
  178. while e[0] > e[1]: e[1] = e[1] + 360
  179. edit(id, ('start', e[0]), ('extent', e[1] - e[0]))
  180. move_to(id, x0, y0)
  181. def edit(id, *args):
  182. _canvas.itemconfigure(id, **dict(args))
  183. def text(pos, color, contents, font='Helvetica', size=12, style='normal', anchor="nw"):
  184. global _canvas_x, _canvas_y
  185. x, y = pos
  186. font = (font, str(size), style)
  187. return _canvas.create_text(x, y, fill=color, text=contents, font=font, anchor=anchor)
  188. def changeText(id, newText, font=None, size=12, style='normal'):
  189. _canvas.itemconfigure(id, text=newText)
  190. if font != None:
  191. _canvas.itemconfigure(id, font=(font, '-%d' % size, style))
  192. def changeColor(id, newColor):
  193. _canvas.itemconfigure(id, fill=newColor)
  194. def line(here, there, color=formatColor(0, 0, 0), width=2):
  195. x0, y0 = here[0], here[1]
  196. x1, y1 = there[0], there[1]
  197. return _canvas.create_line(x0, y0, x1, y1, fill=color, width=width)
  198. ##############################################################################
  199. ### Keypress handling ########################################################
  200. ##############################################################################
  201. # We bind to key-down and key-up events.
  202. _keysdown = {}
  203. _keyswaiting = {}
  204. # This holds an unprocessed key release. We delay key releases by up to
  205. # one call to keys_pressed() to get round a problem with auto repeat.
  206. _got_release = None
  207. def _keypress(event):
  208. global _got_release
  209. # remap_arrows(event)
  210. _keysdown[event.keysym] = 1
  211. _keyswaiting[event.keysym] = 1
  212. # print(event.char, event.keycode)
  213. _got_release = None
  214. def _keyrelease(event):
  215. global _got_release
  216. # remap_arrows(event)
  217. try:
  218. del _keysdown[event.keysym]
  219. except:
  220. pass
  221. _got_release = 1
  222. def remap_arrows(event):
  223. # TURN ARROW PRESSES INTO LETTERS (SHOULD BE IN KEYBOARD AGENT)
  224. if event.char in ['a', 's', 'd', 'w']:
  225. return
  226. if event.keycode in [37, 101]: # LEFT ARROW (win / x)
  227. event.char = 'a'
  228. if event.keycode in [38, 99]: # UP ARROW
  229. event.char = 'w'
  230. if event.keycode in [39, 102]: # RIGHT ARROW
  231. event.char = 'd'
  232. if event.keycode in [40, 104]: # DOWN ARROW
  233. event.char = 's'
  234. def _clear_keys(event=None):
  235. global _keysdown, _got_release, _keyswaiting
  236. _keysdown = {}
  237. _keyswaiting = {}
  238. _got_release = None
  239. def keys_pressed(d_o_e=lambda arg: _root_window.dooneevent(arg),
  240. d_w=tkinter._tkinter.DONT_WAIT):
  241. d_o_e(d_w)
  242. if _got_release:
  243. d_o_e(d_w)
  244. return _keysdown.keys()
  245. def keys_waiting():
  246. global _keyswaiting
  247. keys = _keyswaiting.keys()
  248. _keyswaiting = {}
  249. return keys
  250. # Block for a list of keys...
  251. def wait_for_keys():
  252. keys = []
  253. while keys == []:
  254. keys = keys_pressed()
  255. sleep(0.05)
  256. return keys
  257. def remove_from_screen(x,
  258. d_o_e=lambda arg: _root_window.dooneevent(arg),
  259. d_w=tkinter._tkinter.DONT_WAIT):
  260. _canvas.delete(x)
  261. d_o_e(d_w)
  262. def _adjust_coords(coord_list, x, y):
  263. for i in range(0, len(coord_list), 2):
  264. coord_list[i] = coord_list[i] + x
  265. coord_list[i + 1] = coord_list[i + 1] + y
  266. return coord_list
  267. def move_to(object, x, y=None,
  268. d_o_e=lambda arg: _root_window.dooneevent(arg),
  269. d_w=tkinter._tkinter.DONT_WAIT):
  270. if y is None:
  271. try:
  272. x, y = x
  273. except:
  274. raise ('incomprehensible coordinates')
  275. horiz = True
  276. newCoords = []
  277. current_x, current_y = _canvas.coords(object)[0:2] # first point
  278. for coord in _canvas.coords(object):
  279. if horiz:
  280. inc = x - current_x
  281. else:
  282. inc = y - current_y
  283. horiz = not horiz
  284. newCoords.append(coord + inc)
  285. _canvas.coords(object, *newCoords)
  286. d_o_e(d_w)
  287. def move_by(object, x, y=None,
  288. d_o_e=lambda arg: _root_window.dooneevent(arg),
  289. d_w=tkinter._tkinter.DONT_WAIT):
  290. if y is None:
  291. try:
  292. x, y = x
  293. except:
  294. raise Exception('incomprehensible coordinates')
  295. horiz = True
  296. newCoords = []
  297. for coord in _canvas.coords(object):
  298. if horiz:
  299. inc = x
  300. else:
  301. inc = y
  302. horiz = not horiz
  303. newCoords.append(coord + inc)
  304. _canvas.coords(object, *newCoords)
  305. d_o_e(d_w)
  306. def writePostscript(filename):
  307. """
  308. Writes the current canvas to a postscript file.
  309. """
  310. psfile = file(filename, 'w')
  311. psfile.write(_canvas.postscript(pageanchor='sw',
  312. y='0.c',
  313. x='0.c'))
  314. psfile.close()
  315. ghost_shape = [
  316. (0, - 0.5),
  317. (0.25, - 0.75),
  318. (0.5, - 0.5),
  319. (0.75, - 0.75),
  320. (0.75, 0.5),
  321. (0.5, 0.75),
  322. (- 0.5, 0.75),
  323. (- 0.75, 0.5),
  324. (- 0.75, - 0.75),
  325. (- 0.5, - 0.5),
  326. (- 0.25, - 0.75)
  327. ]
  328. if __name__ == '__main__':
  329. begin_graphics()
  330. clear_screen()
  331. ghost_shape = [(x * 10 + 20, y * 10 + 20) for x, y in ghost_shape]
  332. g = polygon(ghost_shape, formatColor(1, 1, 1))
  333. move_to(g, (50, 50))
  334. circle((150, 150), 20, formatColor(0.7, 0.3, 0.0), endpoints=[15, - 15])
  335. sleep(2)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...