karen_constantine

Untitled

Aug 26th, 2023
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. #Вызов библиотек
  2. from tkinter import *
  3. from random import randint
  4.  
  5. class Game:
  6. #Инициализация
  7. def __init__(self, canvas):
  8. self.canvas = canvas
  9. self.snake_coords = [[14, 14]]
  10. self.apple_coords = [randint(0, 29) for i in range(2)]
  11. self.vector = {"Up":(0,-1), "Down":(0, 1), "Left": (-1,0), "Right": (1, 0)}
  12. self.direction = self.vector["Right"]
  13. self.canvas.focus_set()
  14. self.canvas.bind("<KeyPress>", self.set_direction)
  15. self.GAME()
  16. #Метод для нового положения "Яблока"
  17. def set_apple(self):
  18. self.apple_coords = [randint(0, 29) for i in range(2)]
  19. #Условие, для того чтобы яблоко не лежало на змейке
  20. if self.apple_coords in self.snake_coords:
  21. self.set_apple()
  22. #Установка нового направления змейки
  23. def set_direction(self, event):
  24. #Условие, которое проверяет нажатие кнопки
  25. if event.keysym in self.vector:
  26. self.direction = self.vector[event.keysym]
  27. #Отрисовка игры
  28. def draw(self):
  29. self.canvas.delete(ALL)
  30. x_apple, y_apple = self.apple_coords
  31. self.canvas.create_rectangle(x_apple*10, y_apple*10, (x_apple+1)*10, (y_apple+1)*10, fill="red", width=0)
  32. for x, y in self.snake_coords:
  33. self.canvas.create_rectangle(x*10, y*10, (x+1)*10, (y+1)*10, fill="green", width=0)
  34. #Метод, который возращает координаты на интервале [0, 29]
  35. @staticmethod
  36. def coord_check(coord):
  37. return 0 if coord > 29 else 29 if coord < 0 else coord
  38. #Алгоритм "Оторванный Хвост\Логика игры"
  39. def GAME(self):
  40. self.draw()
  41. x,y = self.snake_coords[0]
  42. x += self.direction[0]; y += self.direction[1]
  43. x = self.coord_check(x)
  44. y = self.coord_check(y)
  45. if x == self.apple_coords[0] and y == self.apple_coords[1]:
  46. self.set_apple()
  47. elif [x, y] in self.snake_coords:
  48. self.snake_coords = []
  49. else:
  50. self.snake_coords.pop()
  51. self.snake_coords.insert(0, [x,y])
  52. self.canvas.after(100, self.GAME)
  53.  
  54.  
  55. #Каркас игры
  56. root = Tk()
  57. canvas = Canvas(root, width=300, height=300, bg="black")
  58. canvas.pack()
  59. game = Game(canvas)
  60. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment