1

Here is my code below. Every time when I try to increase the length, It does not seem to increase and when I run the game.

When I run the game, It sometimes makes the head of the snake flicker/blink certain times and when snake eats the food, still it does not increase the length instead of blinking little at certain times

I have attached code with my applied logic. Please is there any solution to this problem?

Here is my code with what I applied as the increase length logic:

Here is my logic:

import pygame
import time
import sys
import random


a = print("1) Easy")
b = print("2) Medium")
c = print("3) Hard")

while True:
    difficulty = input("Enter Difficulty Level: ")
    if difficulty == "1":
        speed = 5
        break
    elif difficulty == "2":
        speed = 6
        break
    elif difficulty == "3":
        speed = 8
    else:
        print("Choose from Above Options Only!")


# Initialise Game
pygame.init()
clock = pygame.time.Clock()


# Screen and Window Size:
screen_width = 800
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
caption = pygame.display.set_caption("Snake Game")
icon = pygame.image.load("snake.png")
pygame.display.set_icon(icon)

# Colors
red = (255, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
white = (255, 255, 255)

# Snake Editing
x1 = 350
y1 = 300
snake = pygame.Rect([x1, y1, 20, 20])

x1_change = 0       
y1_change = 0

snake_size = 15

snk_list = []
snk_length = 1

# Snake Food
food_x = random.randint(30, screen_width - 40)
food_y = random.randint(30, screen_height - 40)
food_height = 15
food_width = 15

# Game State
game_over = True

# Game over
font = pygame.font.SysFont("freelansbold.tff", 64)

# Score Counter
score = 0
score_font = pygame.font.SysFont("chiller", 50)


# TO INCREASE SNAKE LENGTH LOGIC:
def plot_snake(gameWindow, color, snk_list, snake_size):
    for x, y in snk_list:
        pygame.draw.rect(gameWindow, color, [x, y, snake_size, snake_size])


def game_over_text(text, color):
    x = font.render(text, True, (240, 0, 0))
    screen.blit(x, [screen_width//2 - 135, screen_height//2 - 25])


def score_show():
    text = score_font.render("Score: " + str(score), True, (255, 255, 255))
    screen.blit(text, (20, 10))


def main_loop():
    global x1, y1, x1_change, y1_change, game_over, food_x, food_y, score, speed, snk_list, snake_size, snk_length
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # User Input
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                x1_change = speed * -1
                y1_change = 0
            elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                x1_change = speed
                y1_change = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_w:
                y1_change = speed * -1
                x1_change = 0
            elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
                y1_change = speed
                x1_change = 0

    # Game Over Checking
    if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
        game_over = False

    x1 += x1_change
    y1 += y1_change

    if abs(x1 - food_x) < 7 and abs(y1 - food_y) < 7:
        score += 1
        food_x = random.randint(30, screen_width - 40)
        food_y = random.randint(30, screen_height - 40)
        speed += 0.2
        snk_length += 5

    # Drawing On Screen
    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, red, [x1, y1, 15, 15])
    pygame.draw.rect(screen, green, [food_x, food_y, food_width, food_height])
    score_show()
    pygame.display.flip()

#SNAKE LENGTH LOGIC
    head = []
    head.append(x1)
    head.append(y1)
    snk_list.append(head)

    if len(snk_list) > snk_length:
        del snk_list[0]

    plot_snake(screen, red, snk_list, snake_size)
    # Final Initialisation
    pygame.display.flip()
    clock.tick(70)


# Main Game Loop
while game_over:
    main_loop()

# Game_Over
screen.fill((0, 0, 0))
game_over_text("Game Over!!!", (255, 0, 0))
pygame.display.flip()
time.sleep(2)
pygame.quit()
quit()

  • What have you tried so far? – Rabbid76 Dec 27 '20 at 12:28
  • I have applied my logic you can check in code. I have commented where i hve put my logic in. PLease check sir. –  Dec 27 '20 at 12:33
  • I recommend to study [How do I chain the movement of a snake's body?](https://stackoverflow.com/questions/62010434/how-do-i-chain-the-movement-of-a-snakes-body) – Rabbid76 Dec 27 '20 at 12:35
  • Okay sir, i will check it. –  Dec 27 '20 at 12:35
  • @Rabbid76 sir, I am not able to understand it, can you tell solution looking my code please. I am beginner and my first game made. so.. –  Dec 27 '20 at 12:39
  • 1
    Your snk_length stays at 1 throughout the code. You should increase this somewhere – Stefan Dec 27 '20 at 12:51
  • @Stefan oh ya sorry, I forgot to increment the length. I tried after correction now snake is increasing length but sir the snake's body other than head is blinking continously while moving! what could be the problem? –  Dec 27 '20 at 13:04
  • @RishitPant See the answer – Rabbid76 Dec 27 '20 at 13:05

1 Answers1

0

The moving distance of the snake must be "snake_size":

def main_loop():

    # [...]

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # User Input
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                x1_change = -snake_size
                y1_change = 0
            elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                x1_change = snake_size
                y1_change = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_w:
                y1_change = -snake_size
                x1_change = 0
            elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
                y1_change = snake_size
                x1_change = 0

But use pygame.time.Clock to control the frames per second and thus the game speed.

def main_loop():
 
    # [...]

    clock.tick(speed)

Use pygame.Rect and collidrect to find the collision of the snake and the food. See also How to detect collisions between two rectangular objects or images in pygame. Increment snk_length, when a collision is detected:

def main_loop():
    # [...]

    global snk_length

    # [...]

    snake_rect = pygame.Rect(x1, y1, snake_size, snake_size)
    food_rect = pygame.Rect(food_x, food_y, snake_size, snake_size)
    if snake_rect.colliderect(food_rect):
        snk_length += 1
        score += 1
        food_x = random.randint(30, screen_width - 40)
        food_y = random.randint(30, screen_height - 40)
        speed += 1

Follow the instructions of How do I chain the movement of a snake's body?. Put the new head position of the snake at the head of snk_list, but delete the elements at the tail:

def main_loop():

    # [...]

    #SNAKE LENGTH LOGIC
    snk_list.insert(0, [x1, y1])
    if len(snk_list) > snk_length:
        del snk_list[-1]

Complete main_loop:

def main_loop():
    global x1, y1, x1_change, y1_change, game_over, food_x, food_y, score, speed, snk_list, snake_size
    global snk_length
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # User Input
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                x1_change = -snake_size
                y1_change = 0
            elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                x1_change = snake_size
                y1_change = 0
            elif event.key == pygame.K_UP or event.key == pygame.K_w:
                y1_change = -snake_size
                x1_change = 0
            elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
                y1_change = snake_size
                x1_change = 0

    # Game Over Checking
    if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
        game_over = False

    x1 += x1_change
    y1 += y1_change

    snake_rect = pygame.Rect(x1, y1, snake_size, snake_size)
    food_rect = pygame.Rect(food_x, food_y, snake_size, snake_size)
    if snake_rect.colliderect(food_rect):
        snk_length += 1
        score += 1
        food_x = random.randint(30, screen_width - 40)
        food_y = random.randint(30, screen_height - 40)
        speed += 1

    # Drawing On Screen
    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, red, [x1, y1, 15, 15])
    pygame.draw.rect(screen, green, [food_x, food_y, food_width, food_height])
    score_show()
    pygame.display.flip()

    #SNAKE LENGTH LOGIC
    snk_list.insert(0, [x1, y1])
    if len(snk_list) > snk_length:
        del snk_list[-1]

    plot_snake(screen, red, snk_list, snake_size)
    # Final Initialisation
    pygame.display.flip()
    clock.tick(speed)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174