Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- from random import randint
- scale = 10
- width, height = 64, 64
- pygame.init()
- win = pygame.display.set_mode((width * 10, height * 10))
- pygame.display.set_caption("Snek")
- class Snake:
- def __init__(self, x, y, snakes, apples, color=None, is_player=False):
- self.body = [(x, y)]
- self.direction = randint(0, 3)
- self.alive = True
- self.length = 3
- self.snakes, self.apples = snakes, apples
- if color is None:
- color = [(255, 0, 0)]
- self.color = color
- self.is_player = is_player
- def tick(self):
- last_x, last_y = self.body[-1]
- # Right
- if self.direction == 0:
- self.body.append((last_x + 1, last_y))
- # Up
- elif self.direction == 1:
- self.body.append((last_x, last_y - 1))
- # Left
- elif self.direction == 2:
- self.body.append((last_x - 1, last_y))
- # Down
- elif self.direction == 3:
- self.body.append((last_x, last_y + 1))
- else:
- print("Direction does not exist.")
- # Removes the oldest segments until it has reached the proper length
- while self.length < len(self.body):
- self.body.pop(0)
- self.collision()
- def collision(self):
- x, y = head = self.body[-1]
- # Collision with our own body
- if head in self.body[0:-1]:
- self.alive = False
- # Collision with other snakes
- for snake in self.snakes:
- if snake != self and head in snake.body:
- self.alive = False
- # Collisions with food
- if head in self.apples:
- self.length += 1
- # Outside the map
- if not 0 <= x < width:
- self.alive = False
- elif not 0 <= y < height:
- self.alive = False
- def draw_tile(x, y, color):
- pygame.draw.rect(win, color, (x * scale + 1, y * scale + 1, scale - 2, scale - 2))
- def main():
- ticks = 0
- snakes, foods = [], [(10, 10)]
- max_foods = 1
- key_presses = []
- running = True
- # Game loop
- while running:
- # Ticking
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- running = False
- elif event.type == pygame.KEYDOWN:
- key_presses.append(event)
- for snake in snakes:
- snake.tick()
- while len(foods) < max_foods:
- foods.append((randint(0, width - 1), randint(0, height - 1)))
- # Drawing
- for snake in snakes:
- body, color = snake.body, snake.color
- for body_index, segment in enumerate(body):
- segment_x, segment_y = segment
- pygame.draw.rect(win, color[body_index % len(color)],
- (segment_x * scale, segment_y * scale,
- (segment_x + 1) * scale, (segment_y + 1) * scale))
- for food in foods:
- food_x, food_y = food
- draw_tile(food_x, food_y, (222, 0, 0))
- pygame.display.update()
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement