Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import arcade
- from random import randint
- SCREEN_WIDTH = 600
- SCREEN_HEIGHT = 600
- CELL_WIDTH = 30
- class Snake(arcade.Window):
- def __init__(self, width, height):
- super().__init__(width, height)
- arcade.set_background_color(arcade.color.BLACK)
- self.apple_pos = [SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + CELL_WIDTH * 3]
- self.time = 0
- self.dir = 0 # 0, 1, 2, 3 = up, down, left, right, respectively
- self.snake = [[SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2]]
- def on_update(self, delta_time):
- self.time += delta_time
- if self.time < .2:
- return
- next_pos = self.snake[0].copy()
- if self.dir == 0:
- next_pos[1] += CELL_WIDTH
- elif self.dir == 1:
- next_pos[1] -= CELL_WIDTH
- elif self.dir == 2:
- next_pos[0] -= CELL_WIDTH
- elif self.dir == 3:
- next_pos[0] += CELL_WIDTH
- if (next_pos in self.snake[1:] or
- not (0 <= next_pos[0] < SCREEN_WIDTH) or
- not (0 <= next_pos[1] < SCREEN_HEIGHT)):
- arcade.close_window()
- self.snake.insert(0, next_pos)
- if self.snake[0] == self.apple_pos:
- self.apple_pos = [randint(0, SCREEN_WIDTH // CELL_WIDTH - 1) * CELL_WIDTH,
- randint(0, SCREEN_HEIGHT // CELL_WIDTH - 1) * CELL_WIDTH]
- while self.apple_pos in self.snake:
- self.apple_pos = [randint(0, SCREEN_WIDTH // CELL_WIDTH - 1) * CELL_WIDTH,
- randint(0, SCREEN_HEIGHT // CELL_WIDTH - 1) * CELL_WIDTH]
- else:
- self.snake.pop()
- self.time = 0
- def on_key_press(self, symbol, modifiers):
- if symbol in [arcade.key.UP, arcade.key.W]:
- self.dir = 0
- elif symbol in [arcade.key.DOWN, arcade.key.S]:
- self.dir = 1
- elif symbol in [arcade.key.LEFT, arcade.key.A]:
- self.dir = 2
- elif symbol in [arcade.key.RIGHT, arcade.key.D]:
- self.dir = 3
- def on_draw(self):
- self.clear()
- for i in self.snake:
- arcade.draw_rectangle_filled(
- i[0] + CELL_WIDTH // 2, i[1] + CELL_WIDTH // 2,
- CELL_WIDTH, CELL_WIDTH,
- arcade.color.GREEN
- )
- arcade.draw_rectangle_filled(
- self.apple_pos[0] + CELL_WIDTH // 2, self.apple_pos[1] + CELL_WIDTH // 2,
- CELL_WIDTH, CELL_WIDTH,
- arcade.color.RED
- )
- Snake(SCREEN_WIDTH, SCREEN_HEIGHT)
- arcade.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement