python_snake

悠悠 2022-07-17 02:23 63阅读 0赞
  1. #!/usr/bin/env python3
  2. from threading import Thread
  3. from threading import Timer
  4. from threading import Event
  5. from threading import Lock
  6. import tkinter as tk
  7. import copy
  8. import time
  9. dird = {"Right":[1, 0], "Left":[-1, 0], "Up":[0, -1], "Down":[0, 1]}
  10. class MyTimer(Thread):
  11. def __init__(self, interval, function, args=None, kwargs=None):
  12. Thread.__init__(self)
  13. self.interval = interval
  14. self.function = function
  15. self.args = args if args is not None else []
  16. self.kwargs = kwargs if kwargs is not None else {}
  17. self.finished = Event()
  18. def cancel(self):
  19. self.finished.set()
  20. def run(self):
  21. while not self.finished.is_set():
  22. self.finished.wait(self.interval)
  23. if not self.finished.is_set():
  24. self.function(*self.args, **self.kwargs)
  25. def set_interval(self, interval):
  26. self.interval = interval
  27. class Snake():
  28. def __init__(self, map, id = 1, snake_pos = (0,0), snake_length = 3, dir = "Right", color = "black"):
  29. self.dir = dird[dir]
  30. self.id = id
  31. self.map = map
  32. self.color = color
  33. self.__initSnakeBody__(snake_pos, snake_length)
  34. def __initSnakeBody__(self, snake_pos, snake_length):
  35. self.body = []
  36. self.body.append(list(snake_pos))
  37. if snake_length < 2:
  38. snake_length = 2
  39. for i in range(1, snake_length, 1):
  40. self.add()
  41. self.map.setMapValue(self.body, self.id)
  42. def move(self, is_add = False):
  43. self.map.setMapValue(self.body, 0)
  44. if is_add == False:
  45. self.body.pop(0)
  46. self.add()
  47. self.map.setMapValue(self.body, self.id)
  48. def add(self, node = None):
  49. head = self.body[len(self.body) - 1]
  50. if not node:
  51. node = [head[0] + self.dir[0], head[1] + self.dir[1]]
  52. self.body.append(node)
  53. def isSnakeDead(self):
  54. return self.map.isSnakeDead(self.body, self.dir)
  55. def change_dir(self, newdir):
  56. newdir = dird[newdir]
  57. curdir = [self.body[-1][i]-self.body[-2][i] for i in range(2)]
  58. if curdir != newdir:
  59. self.dir = newdir
  60. class Map(tk.Frame):
  61. def __init__(self, width = 100, height = 100, span = 5, bgcolor = "white"):
  62. self.root = tk.Tk()
  63. self.root.geometry(repr(width*span)+'x'+repr(height*span))
  64. super().__init__(self.root)
  65. self.bg = bgcolor
  66. self.width = width
  67. self.height = height
  68. self.span = span
  69. self.__initMap__()
  70. self.root.resizable(False, False)
  71. def __initMap__(self):
  72. self.cvs = tk.Canvas(self.root, width = self.width *self.span,
  73. height = self.height * self.span, bg = self.bg)
  74. self.map = [[0]*self.width for i in range(self.height)]
  75. self.cvs.bind('<KeyPress>', self.__getKeyEvent)
  76. self.cvs.focus_set()
  77. self.cvs.grid(row=0, column=0, columnspan=self.width, rowspan=self.height)
  78. def drawRectangle(self, start, color):
  79. self.cvs.create_rectangle(start[0]*self.span, start[1]*self.span,
  80. (start[0]+1)*self.span, (start[1]+1)*self.span,
  81. fill = color, outline = self.bg)
  82. def createSnake(self):
  83. self.snake = Snake(self)
  84. def __getKeyEvent(self, event):
  85. print(event.keysym)
  86. self.snake.change_dir(event.keysym)
  87. pass
  88. def isSnakeDead(self, body, dir):
  89. head = body[len(body)-1]
  90. xpos = head[0]+dir[0]
  91. ypos = head[1]+dir[1]
  92. if xpos >= self.width or xpos < 0:
  93. return True
  94. elif ypos >= self.height or ypos < 0:
  95. return True
  96. elif self.map[xpos][ypos] != 0:
  97. return True
  98. return False
  99. def setMapValue(self, body, value, color = "black"):
  100. for n in body:
  101. self.map[n[0]][n[1]] = value
  102. if value != 0:
  103. self.drawRectangle(n, color)
  104. else:
  105. self.drawRectangle(n, self.bg)
  106. def moveSnake(self):
  107. self.snake.move()
  108. return False
  109. def mainloop(self):
  110. self.root.mainloop()
  111. class GameClient(Thread):
  112. def __init__(self):
  113. super().__init__()
  114. self.map = Map()
  115. self.map.createSnake()
  116. def startGame(self):
  117. self.start()
  118. self.map.mainloop()
  119. def run(self):
  120. while(self.map.moveSnake() == False):
  121. #snake run
  122. time.sleep(1)
  123. else:
  124. print("snake dead")
  125. self.map.quit()
  126. if __name__ == "__main__":
  127. game = GameClient()
  128. game.startGame()

发表评论

表情:
评论列表 (有 0 条评论,63人围观)

还没有评论,来说两句吧...

相关阅读