SNAKE2D Game based on Python ( pygames ) .
- Vaibhav Mishra
- Dec 21, 2020
- 1 min read
Updated: Dec 26, 2020
This is a simple snake 2d game we have been playing since long.
When I started learning python, building games such as these were among the few projects I started with.
The module used here is "pygames".
Here is a python code snippet of the game :
import pygame
import sys
import copy
import random
import time
pygame.init()
width = 500
height = 500
scale = 10
score = 0
food_x = 10
food_y = 10
display = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")
clock = pygame.time.Clock()
background = (23, 32, 42)
snake_colour = (236, 240, 241)
food_colour = (148, 49, 38)
snake_head = (247, 220, 111)
# ----------- Snake Class ----------------
class Snake:
def __init__(self, x_start, y_start):
self.x = x_start
self.y = y_start
self.w = 10
self.h = 10
self.x_dir = 1
self.y_dir = 0
self.history = [[self.x, self.y]]
self.length = 1
def reset(self):
self.x = width/2-scale
self.y = height/2-scale
self.w = 10
self.h = 10
self.x_dir = 1
self.y_dir = 0
self.history = [[self.x, self.y]]
self.length = 1
def show(self):
for i in range(self.length):
if not i == 0:
pygame.draw.rect(display, snake_colour, (self.history[i][0], self.history[i][1], self.w, self.h))
else:
pygame.draw.rect(display, snake_head, (self.history[i][0], self.history[i][1], self.w, self.h))
def check_eaten(self):
if abs(self.history[0][0] - food_x) < scale and abs(self.history[0][1] - food_y) < scale:
return True
def grow(self):
self.length += 1
self.history.append(self.history[self.length-2])
def death(self):
i = self.length - 1
while i > 0:
if abs(self.history[0][0] - self.history[i][0]) < self.w and abs(self.history[0][1] - self.history[i][1]) < self.h and self.length > 2:
return True
i -= 1
def update(self):
i = self.length - 1
while i > 0:
self.history[i] = copy.deepcopy(self.history[i-1])
i -= 1
self.history[0][0] += self.x_dir*scale
self.history[0][1] += self.y_dir*scale
Comments