Snake Game in Python

Hello again. I made a snake game in Python.

Here is the source code.

import random
import curses

s = curses.initscr()
curses.curs_set(0)
sh, sw = s.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)

snk_x = sw/4
snk_y = sh/2
snake = [
    [snk_y, snk_x],
    [snk_y, snk_x-1],
    [snk_y, snk_x-2]
]

food = [sh/2, sw/2]
w.addch(int(food[0]), int(food[1]), curses.ACS_PI)

key = curses.KEY_RIGHT

while True:
    next_key = w.getch()
    key = key if next_key == -1 else next_key

    if snake[0][0] in [0, sh] or snake[0][1]  in [0, sw] or snake[0] in snake[1:]:
        curses.endwin()
        quit()

    new_head = [snake[0][0], snake[0][1]]

    if key == curses.KEY_DOWN:
        new_head[0] += 1
    if key == curses.KEY_UP:
        new_head[0] -= 1
    if key == curses.KEY_LEFT:
        new_head[1] -= 1
    if key == curses.KEY_RIGHT:
        new_head[1] += 1

    snake.insert(0, new_head)

    if snake[0] == food:
        food = None
        while food is None:
            nf = [
                random.randint(1, sh-1),
                random.randint(1, sw-1)
            ]
            food = nf if nf not in snake else None
        w.addch(food[0], food[1], curses.ACS_PI)
    else:
        tail = snake.pop()
        w.addch(int(tail[0]), int(tail[1]), ' ')

    w.addch(int(snake[0][0]), int(snake[0][1]), curses.ACS_CKBOARD


This was my first foray into Python, and it was very... weird. I usually program into more lower-level languages like C# and C++, or something with understandable syntax like HTML. Python is just... very weirdly structured. I still understand most of the syntax, but there isn't a whole lot you can mess around with in the context of your program. Especially in the context of being universal. The simplicity of the language doesn't give much to work with, and is pretty slow. It's good for making small games and web/widget applications, but is not great in much else. I may develop a Discord bot in Python, since there is a framework out for it and I do want to learn the language in order to code faster. I do not think however it will replace C++/C# for me.

No comments:

Post a Comment

Officially Retiring This Blog

This blog has now been sunset as of Today on this very date. No more posts here.  Instead, you can follow my Youtube channel here. https://w...