Home > other >  Python snake game Movement directions are problematic
Python snake game Movement directions are problematic

Time:02-01

from tkinter import *
import random
from random import randint

The problem with the program is that the snake does not move

Placement on page coordinates

class Snake:
    def __init__(self) -> None:
        self.body_size = BODY_SIZE
        self.cordinates = []
        self.squares = []

    for i in range(0, BODY_SIZE):
        self.cordinates.append([0, 0])

    for x, y in self.cordinates:
        square = canvas.create_rectangle(x, y, x   SPACE_SIZE , y   SPACE_SIZE, fill=SNAKE_COLOR, tags='snake')
        self.squares.append(square)
    pass

Place on page coordinates for snake food

class Food:
    def __init__(self) -> None:
        x = randint(0, (GAME_WIDTH // SPACE_SIZE) - 1) * SPACE_SIZE
        y = randint(0, (GAME_WIDTH // SPACE_SIZE) - 1) * SPACE_SIZE
        self.cordinates = [x, y]
        canvas.create_rectangle(x, y, x   SPACE_SIZE , y   SPACE_SIZE, fill=FOOD_COLOR, tags='food')

    pass    


#? ///////////////////////////////////////////////////////////////////////////

for get size screen:

def window_size():
    window_width = window.winfo_width()
    window_height = window.winfo_height()
    txt_win_print = (f'this is window_width = {window_width}\n this is window_height = {window_height}\n................')
    print(txt_win_print)


    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    txt_sc_print = (f'this is screen_width = {screen_width}\n this is screen_height = {screen_height}\n')
    print(txt_sc_print)

    x = int((screen_width /2) - (window_width /2))
    y = int((screen_height /2) - (window_height /2))
    window.geometry(f'{window_width}x{window_height} {x} {y}')

    pass

move snake and food on screen for randint :

def next_turn(snake, food):
    x, y = snake.cordinates[0]

    if direction == 'Down':
        y -= SPACE_SIZE
    elif direction == 'UP':
        y  = SPACE_SIZE
    elif direction == 'Left':
        x -= SPACE_SIZE
    elif direction == 'Right':
        x  = SPACE_SIZE

    snake.cordinates.insert(0, [x, y])
    square = canvas.create_rectangle(x, y , x   SPACE_SIZE, y   SPACE_SIZE,fill=SNAKE_COLOR) 

Add points by eating food

    snake.squares.insert(0, square)

    if x == food.cordinates[0] and y == food.cordinates[1]:
        global SCORE
        SCORE  = 1
        label.config(text=f'Score: {SCORE}')
        canvas.delete('food')
        food = Food()

    else:
        del snake.cordinates[-1]
        canvas.delete(snake.squares[-1])
        del snake.squares[-1]

    if check_game_over():
        game_over()

    else:
        window.after(SPEED, next_turn, snake, food)

    pass

Movement directions are difficult

I think this part code is problem , but I can`t fix it

for move snake on screen :

def change_direction(new_dir):
    global direction

    if new_dir == 'Left':
        if direction != 'Right':
            direction = new_dir
    elif new_dir == 'Right':
        if direction != 'Left':
            direction = new_dir
    elif new_dir == ' Up':
        if direction != 'Down':
            direction = new_dir
    elif new_dir == 'Down':
        if direction != 'Up':
            direction = new_dir
        pass





def restart_program(): 
    pass



def check_game_over():
    pass


def game_over():
    pass



color_list = ['White', 'Black']
back_ground = random.choice(color_list)

direction = 'Right'

GAME_WIDTH = 700
SPACE_SIZE = 30
GAME_HEIGHT = 700
SNAKE_SIDE = 25
BODY_SIZE = 2
SPEED = 200
SNAKE_COLOR = '#20B2AA'
FOOD_COLOR = '#FF8C00'
SCORE = 0



window = Tk()
window.resizable(False, False)
window.title('Snake Game')


label = Label(window, text=f'Score:{SCORE}', font=('Mangal', 30))
label.pack()

canvas = Canvas(window, bg=back_ground, height=GAME_HEIGHT, width=GAME_WIDTH)
canvas.pack()

restart = Button(window, text='Restart', fg='red', command=restart_program)
restart.pack()


#! ////////////////////////////////////////////////

Movement directions are difficult

window.bind('<Left>', lambda event: change_direction('Left'))
window.bind('<Right>', lambda evebt: change_direction('Right'))
window.bind('<Up>', lambda event: change_direction('Up'))
window.bind('<Down>', lambda event: change_direction('Down'))


#! ////////////////////////////////////////////////


window.update()

snake = Snake()
food = Food()
window_size()
next_turn(snake, food)


window.mainloop()

CodePudding user response:

You have an extra space in your condition for the up direction:

def change_direction(new_dir):
    global direction

    if new_dir == 'Left':
        if direction != 'Right':
            direction = new_dir
    elif new_dir == 'Right':
        if direction != 'Left':
            direction = new_dir
    elif new_dir == ' Up':     # ----> 'Up'
        if direction != 'Down':
            direction = new_dir
    elif new_dir == 'Down':
        if direction != 'Up':
            direction = new_dir
        pass

Try this:

from tkinter import *
import random
from random import randint



class Snake:
    def __init__(self) -> None:
        self.body_size = BODY_SIZE
        self.cordinates = []
        self.squares = []

        for i in range(0, BODY_SIZE):
            self.cordinates.append([0, 0])

        for x, y in self.cordinates:
            square = canvas.create_rectangle(x, y, x   SPACE_SIZE, y   SPACE_SIZE, fill=SNAKE_COLOR, tags='snake')
            self.squares.append(square)
        pass


class Food:
    def __init__(self) -> None:
        x = randint(0, (GAME_WIDTH // SPACE_SIZE) - 1) * SPACE_SIZE
        y = randint(0, (GAME_WIDTH // SPACE_SIZE) - 1) * SPACE_SIZE
        self.cordinates = [x, y]
        canvas.create_rectangle(x, y, x   SPACE_SIZE , y   SPACE_SIZE, fill=FOOD_COLOR, tags='food')


def window_size():
    window_width = window.winfo_width()
    window_height = window.winfo_height()
    txt_win_print = (f'this is window_width = {window_width}\n this is window_height = {window_height}\n................')
    print(txt_win_print)


    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    txt_sc_print = (f'this is screen_width = {screen_width}\n this is screen_height = {screen_height}\n')
    print(txt_sc_print)

    x = int((screen_width /2) - (window_width /2))
    y = int((screen_height /2) - (window_height /2))
    window.geometry(f'{window_width}x{window_height} {x} {y}')


def next_turn(snake, food):

    x, y = snake.cordinates[0]

    if direction == 'Down':
        y  = SPACE_SIZE
    elif direction == 'Up':
        y -= SPACE_SIZE
    elif direction == 'Left':
        x -= SPACE_SIZE
    elif direction == 'Right':
        x  = SPACE_SIZE

    snake.cordinates.insert(0, [x, y])
    square = canvas.create_rectangle(x, y , x   SPACE_SIZE, y   SPACE_SIZE, fill=SNAKE_COLOR)

    snake.squares.insert(0, square)

    if x == food.cordinates[0] and y == food.cordinates[1]:
        global SCORE
        SCORE  = 1
        label.config(text=f'Score: {SCORE}')
        canvas.delete('food')
        food = Food()

    else:
        del snake.cordinates[-1]
        canvas.delete(snake.squares[-1])
        del snake.squares[-1]

    if False:
        pass

    else:
        window.after(SPEED, next_turn, snake, food,)

    pass

def change_direction(new_dir):
    global direction

    if new_dir == 'Left':
        direction = new_dir
    elif new_dir == 'Right':
        direction = new_dir
    elif new_dir == 'Up':
        direction = new_dir
    elif new_dir == 'Down':
        direction = new_dir
        pass


def restart_program():
    pass



def check_game_over():
    pass


def game_over():
    pass



if __name__ == "__main__":

    window = Tk()
    window.resizable(False, False)
    window.title('Snake Game')
    color_list = ['White', 'Black']
    back_ground = random.choice(color_list)
    direction = 'Right'
    GAME_WIDTH = 700
    SPACE_SIZE = 30
    GAME_HEIGHT = 700
    SNAKE_SIDE = 25
    BODY_SIZE = 2
    SPEED = 200
    SNAKE_COLOR = '#20B2AA'
    FOOD_COLOR = '#FF8C00'
    SCORE = 0



    label = Label(window, text=f'Score:{SCORE}', font=('Mangal', 30))
    label.pack()

    canvas = Canvas(window, bg=back_ground, height=GAME_HEIGHT, width=GAME_WIDTH)
    canvas.pack()


    # restart = Button(window, text='Restart', fg='red', command=lambda: restart_loop)
    # restart.pack()

    window.bind("<Left>", lambda event: change_direction('Left'))
    window.bind("<Right>", lambda event: change_direction('Right'))
    window.bind("<Up>", lambda event: change_direction('Up'))
    window.bind("<Down>", lambda event: change_direction('Down'))

    # ! ////////////////////////////////////////////////

    window.update()

    snake = Snake()
    food = Food()
    window_size()
    next_turn(snake=snake, food=food)

    window.mainloop()
  • Related