Advertisement
here2share

# Tk_speedy_car.py

Oct 9th, 2020
1,342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. # Tk_speedy_car.py
  2.  
  3. import Tkinter
  4. from PIL import ImageGrab
  5. import random
  6. root=Tkinter.Tk()
  7. ww=root.winfo_screenwidth()
  8. hh=root.winfo_screenheight()
  9. root.geometry(str(ww+10)+"x"+str(hh+10)+"+-10+-32") # to hide the frame
  10. canvas=Tkinter.Canvas(width=ww, height=hh, bg='green')
  11. canvas.pack()
  12.  
  13. momentum = 0
  14.  
  15. carbox=10
  16. road=[ww/2-50]*(hh/carbox)
  17.  
  18. def draw_road():
  19.     canvas.delete('road')
  20.     for i in range(len(road)):
  21.         canvas.create_rectangle(road[i],i*10,road[i]+100,i*10+10, fill='white', outline='', tags='road')
  22.  
  23. def draw_car():
  24.     canvas.delete('car')
  25.     c='black'
  26.     bbox = ImageGrab.grab([carx-3,cary+7,carx+10,cary+8])
  27.     t=[bbox.getpixel((0, 0)), bbox.getpixel((12, 0))]
  28.     if (0,255,0) in t:
  29.         c='red'
  30.     canvas.create_rectangle(carx,cary,carx+10,cary+16, fill=c, tags='car')
  31.  
  32. def veer_left(z):
  33.     global carx
  34.     carx-=10
  35.    
  36. def veer_right(z):
  37.     global carx
  38.     carx+=10
  39.  
  40. def animate():
  41.     apply_road()
  42.     draw_road()
  43.     draw_car()
  44.     canvas.after(3, animate)
  45.    
  46. def apply_road():
  47.     global momentum
  48.     momentum=min(8,max(-8,momentum))
  49.     if road[0]+momentum<500:
  50.         momentum+=0.075
  51.         roadside=road[0]+momentum
  52.     elif road[0]+momentum>ww-600:
  53.         momentum-=0.075
  54.         roadside=road[0]+momentum
  55.     else:
  56.         momentum+=random.choice([-0.1,0.1,-0.2,0.2,-0.25,0.25])
  57.         roadside=road[0]+momentum
  58.     road.insert(0, roadside)
  59.     road.pop()
  60.  
  61. draw_road()
  62. carx=ww/2-5
  63. cary=hh-100
  64.  
  65. draw_car()
  66. animate()
  67. canvas.bind_all('<Left>',veer_left)
  68. canvas.bind_all('<Right>',veer_right)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement