# ai snake game

May 19th, 2022
573
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import pygame
2. import sys
3. import random
4.
5. SCREEN_WIDTH = 480
6. SCREEN_HEIGHT = 480
7.
8. GRIDSIZE = 20  # kick thuoc moi o
9. GRID_WIDTH = SCREEN_WIDTH / GRIDSIZE
10. GRID_HEIGHT = SCREEN_HEIGHT / GRIDSIZE
11. YELLOW = (255, 255, 0)
12. BFSPath = (0, 255, 0)
13. UP = (0, -1)
14. DOWN = (0, 1)
15. LEFT = (-1, 0)
16. RIGHT = (1, 0)
17.
18.
19. def drawGrid(surface):
20.     for y in range(0, int(GRID_HEIGHT)):
21.         for x in range(0, int(GRID_WIDTH)):
22.             if (x + y) % 2 == 0:
23.                 r = pygame.Rect((x*GRIDSIZE, y*GRIDSIZE), (GRIDSIZE, GRIDSIZE))
24.                 pygame.draw.rect(surface, (93, 216, 228), r)
25.             else:
26.                 rr = pygame.Rect((x*GRIDSIZE, y*GRIDSIZE),
27.                                  (GRIDSIZE, GRIDSIZE))
28.                 pygame.draw.rect(surface, (84, 194, 205), rr)
29.
30.
31. class Snake(object):
32.     def __init__(self):
33.         self.length = 1
34.         self.positions = [((SCREEN_WIDTH)/2, (SCREEN_HEIGHT)/2)]
35.         self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
36.         self.color = (17, 24, 47)
37.
39.         return self.positions[0]
40.
41.     def turn(self, point):  # direction
42.         if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction:
43.             return
44.         else:
45.             self.direction = point
46.
47.     def move(self):
49.         x, y = self.direction
50.         new = (((cur[0] + (x*GRIDSIZE)) % SCREEN_WIDTH),
51.                (cur[1]+(y*GRIDSIZE)) % SCREEN_HEIGHT)
52.         # đầu con rắn bị trùng với thân của nó
53.         if len(self.positions) > 2 and new in self.positions[2:]:
54.             self.reset()
55.         else:
56.             self.positions.insert(0, new)  # insert vào top
57.             if len(self.positions) > self.length:  # thêm vào đầu bớt ở cuối
58.                 self.positions.pop()
59.
60.     def reset(self):
61.         self.length = 1
62.         self.positions = [((SCREEN_WIDTH)/2, (SCREEN_HEIGHT)/2)]
63.         self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
64.
65.     def draw(self, surface):  # draw snake thân
66.         for p in self.positions:
67.             r = pygame.Rect((p[0], p[1]), (GRIDSIZE, GRIDSIZE))
68.             pygame.draw.rect(surface, YELLOW, r)
69.             pygame.draw.rect(surface, YELLOW, r, 1)  # border
70.
71.     def handle_keys(self):  # di chuyen
72.         for event in pygame.event.get():
73.             if event.type == pygame.QUIT:
74.                 pygame.quit()
75.                 sys.exit()
76.             elif event.type == pygame.KEYDOWN:
77.                 if event.key == pygame.K_UP:
78.                     self.turn(UP)
79.                 elif event.key == pygame.K_DOWN:
80.                     self.turn(DOWN)
81.                 elif event.key == pygame.K_LEFT:
82.                     self.turn(LEFT)
83.                 elif event.key == pygame.K_RIGHT:
84.                     self.turn(RIGHT)
85.
86.     def handle(self, dir):
87.         if dir == 'u':
88.             self.turn(UP)
89.         elif dir == 'd':
90.             self.turn(DOWN)
91.         elif dir == 'l':
92.             self.turn(LEFT)
93.         elif dir == 'r':
94.             self.turn(RIGHT)
95.
96.
97. class Food(object):
98.     def __init__(self):
99.         self.position = (0, 0)
100.         self.color = (233, 163, 49)
101.         self.randomize_position()
102.
103.     def randomize_position(self):
104.         self.position = (random.randint(0, GRID_WIDTH-1)*GRIDSIZE,
105.                          random.randint(0, GRID_HEIGHT-1)*GRIDSIZE)
106.
107.     def draw(self, surface):
108.         r = pygame.Rect(
109.             (self.position[0], self.position[1]), (GRIDSIZE, GRIDSIZE))
110.         pygame.draw.rect(surface, self.color, r)
111.         pygame.draw.rect(surface, (93, 216, 228), r, 1)  # border
112.
113. class Point:
114.     def __init__(self,lat,long):
115.         self.lat = lat
116.         self.long = long
117.
118.
119. def bfs(food, snake, surface, prev):
120.     queue = []
122.     found = False
123.     list = []
125.     while len(queue) != 0:
126.         idx = queue.pop(0)
127.         cur = idx
128.         x = UP[0]
129.         y = UP[1]
130.         new = (((cur[0] + (x*GRIDSIZE)) % SCREEN_WIDTH),
131.                (cur[1]+(y*GRIDSIZE)) % SCREEN_HEIGHT)
132.         if new == food.position:
133.             tePoint1 = (int(new[0]), int(new[1]))
134.             tePoint2 = (int(cur[0]), int(cur[1]), 'u')
135.             prev.update({tePoint1: tePoint2})
136.             found = True
137.             return True
138.         if new not in snake.positions[2:] and new not in list:
139.             tePoint1 = (int(new[0]), int(new[1]))
140.             tePoint2 = (int(cur[0]), int(cur[1]), 'u')
141.             prev.update({tePoint1:tePoint2})
142.             queue.append(new)
143.             list.append(new)
144.             r = pygame.Rect(new, (GRIDSIZE, GRIDSIZE))
145.             # pygame.draw.rect(surface, BFSPath, r)
146.         x = DOWN[0]
147.         y = DOWN[1]
148.         new = (((cur[0] + (x*GRIDSIZE)) % SCREEN_WIDTH),
149.                (cur[1]+(y*GRIDSIZE)) % SCREEN_HEIGHT)
150.         if new == food.position:
151.             tePoint1 = (int(new[0]), int(new[1]))
152.             tePoint2 = (int(cur[0]), int(cur[1]), 'd')
153.             prev.update({tePoint1: tePoint2})
154.             found = True
155.             return True
156.         if new not in snake.positions[2:] and new not in list:
157.             tePoint1 = (int(new[0]), int(new[1]))
158.             tePoint2 = (int(cur[0]), int(cur[1]), 'd')
159.             prev.update({tePoint1: tePoint2})
160.             queue.append(new)
161.             list.append(new)
162.             r = pygame.Rect(new, (GRIDSIZE, GRIDSIZE))
163.             # pygame.draw.rect(surface, BFSPath, r)
164.         x = LEFT[0]
165.         y = LEFT[1]
166.         new = (((cur[0] + (x*GRIDSIZE)) % SCREEN_WIDTH),
167.                (cur[1]+(y*GRIDSIZE)) % SCREEN_HEIGHT)
168.         if new == food.position:
169.             tePoint1 = (int(new[0]), int(new[1]))
170.             tePoint2 = (int(cur[0]), int(cur[1]), 'l')
171.             prev.update({tePoint1: tePoint2})
172.             found = True
173.             return True
174.         if new not in snake.positions[2:] and new not in list:
175.             tePoint1 = (int(new[0]), int(new[1]))
176.             tePoint2 = (int(cur[0]), int(cur[1]), 'l')
177.             prev.update({tePoint1: tePoint2})
178.             queue.append(new)
179.             list.append(new)
180.             r = pygame.Rect(new, (GRIDSIZE, GRIDSIZE))
181.             # pygame.draw.rect(surface, BFSPath, r)
182.         x = RIGHT[0]
183.         y = RIGHT[1]
184.         new = (((cur[0] + (x*GRIDSIZE)) % SCREEN_WIDTH),
185.                (cur[1]+(y*GRIDSIZE)) % SCREEN_HEIGHT)
186.         if new == food.position:
187.             tePoint1 = (int(new[0]), int(new[1]))
188.             tePoint2 = (int(cur[0]), int(cur[1]), 'r')
189.             prev.update({tePoint1: tePoint2})
190.             found = True
191.             return True
192.         if new not in snake.positions[2:] and new not in list:
193.             tePoint1 = (int(new[0]), int(new[1]))
194.             tePoint2 = (int(cur[0]), int(cur[1]), 'r')
195.             prev.update({tePoint1: tePoint2})
196.             queue.append(new)
197.             list.append(new)
198.             r = pygame.Rect(new, (GRIDSIZE, GRIDSIZE))
199.             # pygame.draw.rect(surface, BFSPath, r)
200.     return found
201.
202.
203. def main():
204.     pygame.init()
205.     clock = pygame.time.Clock()
206.     screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
207.     surface = pygame.Surface(screen.get_size())
208.     surface = surface.convert()
209.
210.     # drawGrid(surface)
211.     snake = Snake()
212.     food = Food()
213.     FPS = 10
214.     myfont = pygame.font.SysFont('monospace', 16)
215.     score = 0
216.     while True:
217.         # snake.handle_keys()
218.         prev = {}
219.         print(bfs(food, snake, surface, prev))
221.         foodPosition = (int(food.position[0]), int(food.position[1]))
222.         tePoint = prev.get(foodPosition)
223.         path = []
225.             path.append(foodPosition)
226.             foodPosition = tePoint
227.             print(foodPosition)
228.             if foodPosition is None:
229.                 break
230.             tePoint = prev.get((foodPosition[0], foodPosition[1]))
231.         path = path[::-1]
232.         print(path)
233.         for i in path:
234.             drawGrid(surface)
235.             for j in path:
236.                 r = pygame.Rect((j[0], j[1]), (GRIDSIZE, GRIDSIZE))
237.                 pygame.draw.rect(surface, BFSPath, r)
238.             if len(i) != 2:
239.                 snake.handle(i[2])
240.             snake.move()
242.                 snake.length += 1
243.                 score += 1
244.                 food.randomize_position()
245.             snake.draw(surface)
246.             food.draw(surface)
247.             screen.blit(surface, (0, 0))
248.             text = myfont.render("Score {0}".format(score), 1, (0, 0, 0))
249.
250.         # break
251.
252.             screen.blit(text, (5, 10))
253.             pygame.display.update()
254.             clock.tick(FPS)
255.
256.
257. if __name__ == '__main__':
258.     main()
259.