Skip to content
Advertisement

Curses snake game not removing cells in linux os

It’s code from a curses tutorial that I’ve been using to get a grasp of it but even though I’ve checked the code multiple times, it’s still not removing the old cells. The guy that wrote the code is on a mac and I’m using linux so would that be a problem?

import curses
import time
import random

screen = curses.initscr()
dims = screen.getmaxyx()
def game():
    screen.nodelay(1)
    head = [1, 1]
    body = [head[:]]*5
    screen.border()
    direction = 0 # 0:right, 1:down, 2:left, 3:up
    gameover = False

    while not gameover:
        deadcell = body[-1][:]
        if deadcell not in body:
            screen.addch(deadcell[0], deadcell[1], ' ')
        screen.addch(head[0], head[1], 'X')
        if direction == 0:
            head[1] += 1
        elif direction == 2:
            head[1] -= 1
        elif direction == 1:
            head[0] += 1
        elif direction == 3:
            head[0] -= 1

        deadcell = body[-1][:]
        for z in range(len(body)-1, 0, -1):
            body[z] = body[z-1][:]

        body[0] = head[:]

        if screen.inch(head[0], head[1]) != ord(' '):
            gameover = True

        screen.move(dims[0]-1, dims[1]-1)
        screen.refresh()
        time.sleep(0.1)

game()
curses.endwin()

Advertisement

Answer

The problem seems to be near the lines:

while not gameover:
    deadcell = body[-1][:]
    if deadcell not in body:
        screen.addch(deadcell[0], deadcell[1], ' ')

deadcell is always going to be in body, so no cells will ever get cleared.

Try this instead:

deadcell = body[-1][:]

while not gameover:
    if deadcell not in body:
        screen.addch(deadcell[0], deadcell[1], ' ')
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement