Article 5GQK2 Control the snake.

Control the snake.

by
teckk
from LinuxQuestions.org on (#5GQK2)
Use the arrow keys on your keyboard to control the snake. If the snake touches the edge of the terminal, game over. Ages 3-7, or if you are bored, alter it for practice.

Code:#!/usr/bin/python

import time, curses

def snake(screen):
curses.curs_set(0)
screen.nodelay(True)

directions = {
curses.KEY_UP: (-1, 0),
curses.KEY_DOWN: (1, 0),
curses.KEY_LEFT: (0, -1),
curses.KEY_RIGHT: (0, 1),
}

direction = directions[curses.KEY_RIGHT]
snake = [(0, i) for i in reversed(range(20))]

while True:
screen.erase()
try:
screen.addstr(*snake[0], '@', curses.A_BOLD)

except:
print('Game Over!')
time.sleep(1)
exit()

for segment in snake[1:]:
screen.addstr(*segment, '*')

snake.pop()
snake.insert(0, tuple(map(sum, zip(snake[0], direction))))
direction = directions.get(screen.getch(), direction)

screen.refresh()
time.sleep(0.04)

if __name__ == '__main__':
curses.wrapper(snake)latest?d=yIl2AUoC8zA latest?i=PsW-T8txD8U:7ZWHhSL86Sc:F7zBnMy latest?i=PsW-T8txD8U:7ZWHhSL86Sc:V_sGLiP latest?d=qj6IDK7rITs latest?i=PsW-T8txD8U:7ZWHhSL86Sc:gIN9vFwPsW-T8txD8U
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments