Advertisement
here2share

# tk_offset_move.py

Feb 18th, 2025
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. # tk_offset_move.py
  2.  
  3. import tkinter as tk
  4.  
  5. root = tk.Tk()
  6. root.title("tk_offset_move.py")
  7.  
  8. canvas = tk.Canvas(root, width=300, height=300)
  9. canvas.pack()
  10.  
  11. directions = right, down, left, up = ['Right', 'Down', 'Left', 'Up']
  12. directions_dict = {right: (1, 0), down: (0, 1), left: (-1, 0), up: (0, -1)}
  13.  
  14. direction = right
  15.  
  16. matrix_str = """
  17. 00000
  18. 0ABC0
  19. 0DEF0
  20. 0GHI0
  21. 00000
  22. """
  23.  
  24. matrix = [list(row) for row in matrix_str.strip().split('\n')]
  25.  
  26. target = 'B'
  27.  
  28. c0 = len(matrix[0])
  29. r0 = len(matrix)
  30.  
  31. flat = matrix_str.replace('\n', '')
  32. idx = flat.find(target)
  33. x, y = idx % c0, idx // c0
  34. cell_size = 60
  35. padding = cell_size // 2
  36.  
  37. for i in range(r0):
  38.     for j in range(c0):
  39.         text = matrix[i][j]
  40.         canvas.create_text(
  41.             j * cell_size + cell_size // 2,
  42.             i * cell_size + cell_size // 2,
  43.             text=text,
  44.             font=("Arial", 12)
  45.         )
  46.  
  47. def chk():
  48.     sight = []
  49.     for dir in [(0, 0), (1, 0), (0, 1), (1, 1)]:
  50.         dx, dy = dir
  51.         new_x = x + dx
  52.         new_y = y + dy
  53.         t = matrix[new_y][new_x]
  54.         sight.append(t)
  55.     print(f"Current Position: ({x}, {y}), Neighbors: {sight}")
  56.  
  57. def on_key_press(event):
  58.     global x, y
  59.     key = event.keysym
  60.     if key in directions_dict:
  61.         dx, dy = directions_dict[key]
  62.         new_x = x + dx
  63.         new_y = y + dy
  64.         if 0 <= new_x < c0 - 1 and 0 <= new_y < r0 - 1:
  65.             x, y = new_x, new_y
  66.             chk()
  67.             update_canvas()
  68.         else:
  69.             print(f"Cannot Move {key}: Out Of Bounds")
  70.  
  71. def update_canvas():
  72.     canvas.delete("dot")
  73.     canvas.create_oval(
  74.         padding + x * cell_size + cell_size // 4,
  75.         padding + y * cell_size + cell_size // 4,
  76.         padding + x * cell_size + 3 * cell_size // 4,
  77.         padding + y * cell_size + 3 * cell_size // 4,
  78.         fill="orange",
  79.         tags=('dot',)
  80.     )
  81.  
  82. root.bind('<Key>', on_key_press)
  83.  
  84. chk()
  85. update_canvas()
  86.  
  87. debug_path = [
  88.     (2, 0), (3, 0), (3, 1), (3, 2), (3, 3), (2, 3), (2, 2),
  89.     (1, 2), (1, 3), (0, 3), (0, 2), (0, 1), (1, 1), (1, 0)
  90. ]
  91.  
  92. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement