-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.py
66 lines (54 loc) · 1.45 KB
/
snake.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import pygame
import random
from constants import *
from block import Block
class Snake:
def __init__(self):
self.vel = RIGHT
self.blocks = [Block(1,1)]
self.head = 0
def change_direction(self, vel):
"""Change the direction in which the snake is moving"""
self.vel = vel
def add_block(self):
"""Updates the snakes position"""
# Adds a new block to the snake
current_head = self.blocks[len(self.blocks)-1]
self.blocks.append(Block(current_head.x + self.vel[0], current_head.y + self.vel[1]))
self.head = self.head+1
def remove_block(self):
self.blocks.pop(0)
self.head = self.head-1
def respawn(self):
self.vel = RIGHT
self.blocks = [Block(1,1)]
self.head = 0
def draw(self, screen):
for c, block in enumerate(self.blocks):
if c == self.head:
color = (0,0,0)
else:
color = DARK_GREEN
block.draw(screen,color)
def is_on_food(self, food):
return self.blocks[self.head].is_on(food)
def is_on_self(self):
for block in self.blocks[:self.head]:
if self.blocks[self.head].is_on(block):
return True
else:
return False
def is_on_wall(self):
for c in range(COLUMNS):
for r in range(ROWS):
if c == 0 or c == COLUMNS-1 or r == 0 or r == ROWS-1:
if self.blocks[self.head].is_on(Block(c,r)):
return True
else:
return False
def __repr__(self):
string = "["
for block in self.blocks:
string = string + ",({},{}),".format(block.x,block.y)
string = string + "]"
return string