|
| 1 | +import pygame |
| 2 | +import random |
| 3 | + |
| 4 | +# Check for modules of pygame |
| 5 | +pygame.init() |
| 6 | + |
| 7 | +# Defining RGB color |
| 8 | +white = (255, 255, 255) |
| 9 | +red = (255, 0, 0) |
| 10 | +black = (0, 0, 0) |
| 11 | + |
| 12 | +# Creating Screen |
| 13 | +screen_width = 900 |
| 14 | +screen_height = 600 |
| 15 | +gameWindow = pygame.display.set_mode((screen_height, screen_height)) |
| 16 | + |
| 17 | +pygame.display.set_caption('Snake Game') |
| 18 | +# this is used to pygameDisplay |
| 19 | +pygame.display.update() |
| 20 | + |
| 21 | +# Game Specific Variables |
| 22 | +clock = pygame.time.Clock() |
| 23 | +exit_game = False |
| 24 | +game_over = False |
| 25 | + |
| 26 | +snake_x = 45 |
| 27 | +snake_y = 55 |
| 28 | +snake_size = 11 |
| 29 | + |
| 30 | +score = 0 |
| 31 | + |
| 32 | +food_size = 10 |
| 33 | + |
| 34 | +init_vel = 5 |
| 35 | +velocity_x = 0 |
| 36 | +velocity_y = 0 |
| 37 | +fps = 60 |
| 38 | + |
| 39 | +food_x = random.randint(20, int(screen_width / 2)) |
| 40 | +food_y = random.randint(20, int(screen_height / 2)) |
| 41 | + |
| 42 | +while not exit_game: |
| 43 | + for event in pygame.event.get(): |
| 44 | + |
| 45 | + if event.type == pygame.QUIT: |
| 46 | + exit_game = True |
| 47 | + |
| 48 | + if event.type == pygame.KEYDOWN: |
| 49 | + if event.key == pygame.K_RIGHT: |
| 50 | + velocity_x = init_vel |
| 51 | + velocity_y = 0 |
| 52 | + |
| 53 | + if event.key == pygame.K_LEFT: |
| 54 | + velocity_x = - init_vel |
| 55 | + velocity_y = 0 |
| 56 | + |
| 57 | + if event.key == pygame.K_UP: |
| 58 | + velocity_y = - init_vel |
| 59 | + velocity_x = 0 |
| 60 | + |
| 61 | + if event.key == pygame.K_DOWN: |
| 62 | + velocity_y = init_vel |
| 63 | + velocity_x = 0 |
| 64 | + |
| 65 | + if abs(snake_x - food_x) < 6 and abs(snake_y - food_y) < 6: |
| 66 | + score += 1 |
| 67 | + print('SCORE: ', score * 10) |
| 68 | + food_x = random.randint(20, int(screen_width / 2)) |
| 69 | + food_y = random.randint(20, int(screen_height / 2)) |
| 70 | + |
| 71 | + snake_x = snake_x + velocity_x |
| 72 | + snake_y = snake_y + velocity_y |
| 73 | + |
| 74 | + gameWindow.fill(white) |
| 75 | + pygame.draw.rect(gameWindow, black, [snake_x, snake_y, snake_size, snake_size]) |
| 76 | + pygame.draw.rect(gameWindow, red, [food_x, food_y, food_size, food_size]) |
| 77 | + pygame.display.update() |
| 78 | + clock.tick(fps) |
| 79 | + |
| 80 | +pygame.quit() |
| 81 | +quit() |
0 commit comments