snake python

Solutions on MaxInterview for snake python by the best coders in the world

showing results for - "snake python"
Gaia
13 Nov 2020
1import pygame
2import numpy
3import random
4import math
5pygame.init()
6clock = pygame.time.Clock()
7screen = pygame.display.set_mode((377, 377))
8grid = numpy.zeros((15, 15), dtype="int8")
9for i in range(4):
10    grid[7][2+i] = 2
11apple_pos = [7, 11]
12grid[apple_pos[0]][apple_pos[1]] = 5
13snake = [[7, 2], [7, 5]]
14d = [2, 2]
15direction_list = []
16keys = [pygame.K_UP, pygame.K_RIGHT, pygame.K_DOWN, pygame.K_LEFT]
17colors = [(0, 150, 150), (0, 255, 0), (255, 0, 0)]
18frames = 0
19moving = False
20while True:
21    frames += 1
22    for event in pygame.event.get():
23        if event.type == pygame.QUIT:
24            quit()
25        if event.type == pygame.KEYDOWN:
26            for i in range(len(keys)):
27                if event.key == keys[i]:
28                    moving = True
29                    direction_list.append(i+1)
30    if moving and frames >= 10:
31        frames = 0
32        if len(direction_list) > 0:
33            d[1] = direction_list[0]
34            direction_list.pop(0)
35        d[0] = grid[snake[0][0]][snake[0][1]]
36        last_pos = [snake[0][:], snake[1][:]]
37        for i in range(2):
38            snake[i][round((d[i] % 2-1)*-1)] += round(5/24*d[i]**4 - 25/12*d[i]**3 + 151/24*d[i]**2 - 65/12*d[i])
39            grid[last_pos[i][0]][last_pos[i][1]] = d[i] * i
40            if i:
41                for n in range(2):
42                    if snake[i][n] < 0 or snake[i][n] > 14:
43                        quit()
44                if 5 > grid[snake[i][0]][snake[i][1]] > 0:
45                    quit()
46                if snake[i] == apple_pos:
47                    grid[last_pos[0][0]][last_pos[0][1]] = d[0]
48                    snake[0] = last_pos[0]
49                    while grid[apple_pos[0]][apple_pos[1]] != 0:
50                        apple_pos = [random.randint(0, 14), random.randint(0, 14)]
51                    grid[apple_pos[0]][apple_pos[1]] = 5
52                grid[snake[i][0]][snake[i][1]] = d[1]
53    for row in range(len(grid)):
54        for pos in range(len(grid[row])):
55            pygame.draw.rect(screen, colors[round((math.log(grid[row][pos]+1))-0.15)], (25*pos + 2, 25*row + 2, 23, 23))
56    clock.tick(60)
57    pygame.display.update()
58
Christian
18 Sep 2016
1wrong python my guy