Pygame Snake - Apple spawning inside snake - python

i'm learning how to make a snake game in pygame from the thenewboston tutorials on youtube and make it my own.
There's a problem in the game where the 'apple' spawns behind the snake's position which is something that i don't want.
I'm sure i have to state that apple position can't be the same as the snake but can't figure it out how:
# Snake eating the apple
if snake_x_pos == apple_x and snake_y_pos == apple_y:
pygame.mixer.Sound.play(eat_apple_sound)
snakelength += 1
apple_x = random.randrange(box_size, field_x, box_size)
apple_y = random.randrange(box_size, field_y, box_size)
Full code:
import pygame
import random
pygame.init()
# Game Title
pygame.display.set_caption("Original Snake")
# Game display 4:3
screen_w = 640
screen_h = 480
surface = pygame.display.set_mode((screen_w, screen_h))
bg_color = (170, 204, 102)
box_color = (43, 51, 26)
box_size = screen_h / 24
# PLAYING FIELD
field_x = screen_w - (box_size*2)
field_y = screen_h - (box_size*2)
# Frames per Second
clock = pygame.time.Clock()
FPS = 8
# Font settings
kongtext = "C:\Windows\Fonts\kongtext.ttf"
verysmall = pygame.font.Font(kongtext, 12)
small = pygame.font.Font(kongtext, 15)
medium = pygame.font.Font(kongtext, 30)
large = pygame.font.Font(kongtext, 60)
verylarge = pygame.font.Font(kongtext, 80)
# sound settings
game_over_sound = pygame.mixer.Sound("sounds/game_over.wav")
eat_apple_sound = pygame.mixer.Sound("sounds/eat_apple.wav")
def snake(box_size, snakelist):
for XnY in snakelist:
pygame.draw.rect(surface, box_color, [XnY[0], XnY[1], box_size, box_size])
# Text Object
def text_objects(text, color, size):
if size == "small":
text_surface = small.render(text, True, color)
elif size == "verysmall":
text_surface = verysmall.render(text, True, color)
elif size == "medium":
text_surface = medium.render(text, True, color)
elif size == "large":
text_surface = large.render(text, True, color)
elif size == "verylarge":
text_surface = large.render(text, True, color)
return text_surface, text_surface.get_rect()
# Start screen
def start_screen():
intro = True
while intro:
# IF USER CLICKS ON THE X
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# Start Game
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
intro = False
surface.fill(bg_color)
# SCREEN FIELD WITH BORDER 3
pygame.draw.rect(surface, box_color, [16, 16, screen_w-33, screen_h-33-box_size], 3)
# START SCREEN
message_to_screen("SNAKE", box_color, -25, size="verylarge")
message_to_screen("PRESS SPACE TO PLAY", box_color, 35, size="verysmall")
pygame.display.update()
clock.tick(15)
# Message to screen
def message_to_screen(msg, color, text_y_pos=0, size="small"):
text_surf, text_rect = text_objects(msg, color, size)
text_rect.center = (screen_w / 2), (screen_h / 2)+text_y_pos
surface.blit(text_surf, text_rect)
def score(score):
text = small.render("Score: "+str((score*10)-20), True, box_color)
surface.blit(text, [box_size, screen_h-box_size-7])
def game_loop():
direction = "right"
quit_game = False
game_over = False
# Box settings
box_color = (43, 51, 26)
# Defining snake position
snakelist = []
snakelength = 3
snake_x_pos = screen_w / 2
snake_y_pos= screen_h / 2
snake_x_chg = box_size
snake_y_chg = 0
# Randomizing the apple position
apple_x = random.randrange(box_size, field_x, box_size)
apple_y = random.randrange(box_size, field_y, box_size)
while not quit_game:
# Game Over
while game_over:
surface.fill(bg_color)
message_to_screen("GAME OVER", box_color, -10, size="large")
message_to_screen("PRESS SPACE TO PLAY AGAIN OR Q TO QUIT", box_color, 50, size="small")
# PLAYING FIELD
pygame.draw.rect(surface, box_color,
[16, 16, screen_w - 33, screen_h - 33 - box_size], 3)
# SCORE
score(snakelength - 1)
pygame.display.update()
# Closing Game Over screen with X
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit_game = True
game_over = False
# Closing Game Over screen with Q or Restart with space
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
quit_game = True
game_over = False
if event.key == pygame.K_SPACE:
direction = "right"
game_loop()
for event in pygame.event.get():
# Closing the game
if event.type == pygame.QUIT:
quit_game = True
game_over = False
# Controlling the snake
if event.type == pygame.KEYDOWN:
if (event.key == pygame.K_LEFT) and direction != "right":
snake_x_chg = -box_size
snake_y_chg = 0
direction = "left"
elif (event.key == pygame.K_RIGHT) and direction != "left":
snake_x_chg = box_size
snake_y_chg = 0
direction = "right"
elif (event.key == pygame.K_UP) and direction != "down":
snake_y_chg = -box_size
snake_x_chg = 0
direction = "up"
elif (event.key == pygame.K_DOWN) and direction != "up":
snake_y_chg = box_size
snake_x_chg = 0
direction = "down"
# Screen boundaries
if snake_x_pos > (field_x) or snake_x_pos < box_size or snake_y_pos > (field_y) or snake_y_pos < box_size:
pygame.mixer.Sound.play(game_over_sound)
game_over = True
# Snake new position
snake_x_pos += snake_x_chg
snake_y_pos += snake_y_chg
# Clear screen
surface.fill(bg_color)
# Draw and update
pygame.draw.rect(surface, box_color, [apple_x, apple_y, box_size, box_size])
snakehead = []
snakehead.append(snake_x_pos)
snakehead.append(snake_y_pos)
snakelist.append(snakehead)
if len(snakelist) > snakelength:
del snakelist[0]
for snaketail in snakelist[:-1]:
if snaketail == snakehead:
pygame.mixer.Sound.play(game_over_sound)
game_over = True
snake(box_size, snakelist)
# PLAYING FIELD
pygame.draw.rect(surface, box_color, [16, 16, screen_w-33, screen_h-33-box_size], 3)
# SCORE
score(snakelength-1)
pygame.display.update()
# Snake eating the apple
if snake_x_pos == apple_x and snake_y_pos == apple_y:
pygame.mixer.Sound.play(eat_apple_sound)
snakelength += 1
apple_x = random.randrange(box_size, field_x, box_size)
apple_y = random.randrange(box_size, field_y, box_size)
clock.tick(FPS)
pygame.quit()
quit()
start_screen()
game_loop()

Create a rectangle at the new random "apple" position:
apple_rect = pygame.Rect(apple_x, apple_y, box_size, box_size)
Check for each position (pos) in snakelist if the "apple" rectangle collides with the part of the snake by pygame.Rect.collidepoint:
apple_rect.collidepoint(*pos)
Use any() to check if the apple "collides" with any part of the snake:
any(apple_rect.collidepoint(*pos) for pos in snakelist)
If the apple "collides" with the snake the create a new random point and repeat the process:
# Snake eating the apple
if snake_x_pos == apple_x and snake_y_pos == apple_y:
pygame.mixer.Sound.play(eat_apple_sound)
snakelength += 1
while True:
apple_x, apple_y = (random.randrange(box_size, fs, box_size) for fs in (field_x, field_y))
apple_rect = pygame.Rect(apple_x, apple_y, box_size, box_size)
if not any(apple_rect.collidepoint(*pos) for pos in snakelist):
break

The snake seems to be a list of "boxes", held in the list snakelist. So to ensure the apple does not appear inside the parts of the snake, the generated random point needs to be created outside the snake's boxes.
A simple (but inefficient) way to do this is to keep generating random points, and testing them for collision.
collision = True
while collision == True:
# Randomizing the apple position
apple_x = random.randrange(box_size, field_x, box_size)
apple_y = random.randrange(box_size, field_y, box_size)
# Check apple not within snake
collision = False
for XnY in snakelist:
part = pygame.Rect( XnY[0], XnY[1], box_size, box_size )
# is the apple-point within the snake part?
if part.collidepoint( apple_x, apple_y ) == True:
collision = True
break # any collision is final, stop checking
It would be worth thinking of a more efficient way to move the point away from the snake instead of looping over-and-over. Picking a random point may simply pick the same point, or a near-by bad point again. Also the longer the snake gets, the worse this looping will be as there are less "non-snake" points on the screen. I guess there's some known safe-spots, like the space the snake just moved out of, but these are obviously not random.

Related

Python Snake doesn't grow [duplicate]

This question already has an answer here:
How do I get the snake to grow and chain the movement of the snake's body?
(1 answer)
Closed 1 year ago.
I'm new to python and only now the basics, I'm trying to make a snake game but I can't seem to figure out how to make my snake grow 1 extra square each time it eats an apple. My reasoning is that I keep a list of all the old positions but only show the last one on the screen, and each time the snakes eats another apple it shows 1 extra old positions making the snake 1 square longer.
This is my code:
import pygame
from random import randint
WIDTH = 400
HEIGHT = 300
dis = pygame.display.set_mode((WIDTH,HEIGHT))
white = (255,255,255)
BACKGROUND = white
blue = [0,0,255]
red = [255,0,0]
class Snake:
def __init__(self):
self.image = pygame.image.load("snake.bmp")
self.rect = self.image.get_rect()
self.position = (10,10)
self.direction = [0,0]
self.positionslist = [self.position]
self.length = 1
pygame.display.set_caption('Snake ')
def draw_snake(self,screen):
screen.blit(self.image, self.position)
def update(self):
self.position = (self.position[0] + self.direction[0],self.position[1] + self.direction[1])
self.rect = (self.position[0],self.position[1],5, 5 )
self.positionslist.append(self.position)
if self.position[0]< 0 :
self.position = (WIDTH,self.position[1])
elif self.position[0] > WIDTH:
self.position = (0,self.position[1])
elif self.position[1] > HEIGHT:
self.position = (self.position[0],0)
elif self.position[1] < 0 :
self.position = (self.position[0],HEIGHT)
class Food:
def __init__(self):
self.image = pygame.image.load("appel.png")
self.rect = self.image.get_rect()
apple_width = -self.image.get_width()
apple_height = -self.image.get_height()
self.position = (randint(0,WIDTH+apple_width-50),randint(0,HEIGHT+apple_height-50))
self.rect.x = self.position[0]
self.rect.y = self.position[1]
def draw_appel(self,screen):
screen.blit(self.image, self.position)
def eat_appel (self, snake):
if self.rect.colliderect(snake.rect) == True:
self.position = (randint(0,WIDTH),randint(0,HEIGHT))
self.rect.x = self.position[0]
self.rect.y = self.position[1]
snake.length += 1
def main():
game_over = False
while not game_over:
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
snake = Snake()
food = Food()
while True:
screen.fill(BACKGROUND)
font = pygame.font.Font('freesansbold.ttf', 12)
text = font.render(str(snake.length), True, red, white)
textRect = text.get_rect()
textRect.center = (387, 292)
screen.blit(text,textRect)
snake.update()
#snake.update_list()
snake.draw_snake(screen)
food.draw_appel(screen)
food.eat_appel(snake)
pygame.display.flip()
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
snake.direction = [0,1]
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
snake.direction = [1,0]
if event.key == pygame.K_LEFT:
snake.direction = [-1,0]
if event.key == pygame.K_UP:
snake.direction = [0,-1]
if event.key == pygame.K_DOWN:
snake.direction = [0,1]
if __name__ == "__main__":
main()
This can have multiple reasons. Firstly, I saw you tried to increase the length of the snake by typing snake.length += 1, which may work (probably won't because the module pygame allows the snake to hover around, but not like the loop or conditional statements). One of my tips would be, to increase the length of the snake by using the idea of adding the score with your present snake.length every time (because once your score is 1 by eating an apple, your snake.length would be 2. And it increases with the score). This is my code (a few modifications might be needed):
import pygame
import time
import random
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
orange = (255, 165, 0)
width, height = 600, 400
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Mania")
clock = pygame.time.Clock()
snake_size = 10
snake_speed = 15
message_font = pygame.font.SysFont('ubuntu', 30)
score_font = pygame.font.SysFont('ubuntu', 25)
def print_score(score):
text = score_font.render("Score: " + str(score), True, orange)
game_display.blit(text, [0,0])
def draw_snake(snake_size, snake_pixels):
for pixel in snake_pixels:
pygame.draw.rect(game_display, white, [pixel[0], pixel[1], snake_size, snake_size])
def run_game():
game_over = False
game_close = False
x = width / 2
y = height / 2
x_speed = 0
y_speed = 0
snake_pixels = []
snake_length = 1
target_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
target_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
while not game_over:
while game_close:
game_display.fill(black)
game_over_message = message_font.render("Game Over!", True, red)
game_display.blit(game_over_message, [width / 3, height / 3])
print_score(snake_length - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
game_over = True
game_close = False
if event.key == pygame.K_2:
run_game()
if event.type == pygame.QUIT:
game_over = True
game_close = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_speed = -snake_size
y_speed = 0
if event.key == pygame.K_RIGHT:
x_speed = snake_size
y_speed = 0
if event.key == pygame.K_UP:
x_speed = 0
y_speed = -snake_size
if event.key == pygame.K_DOWN:
x_speed = 0
y_speed = snake_size
if x >= width or x < 0 or y >= height or y < 0:
game_close = True
x += x_speed
y += y_speed
game_display.fill(black)
pygame.draw.rect(game_display, orange, [target_x, target_y, snake_size, snake_size])
snake_pixels.append([x, y])
if len(snake_pixels) > snake_length:
del snake_pixels[0]
for pixel in snake_pixels[:-1]:
if pixel == [x, y]:
game_close = True
draw_snake(snake_size, snake_pixels)
print_score(snake_length - 1)
pygame.display.update()
if x == target_x and y == target_y:
target_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
target_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
snake_length += 1
clock.tick(snake_speed)
pygame.quit()
quit()
run_game()

How can i collide with a 45 degree slope?

I have spent the past 3 days trying to understand this but with every article I have read and every youtube video I have watched I have failed to comprehend the concept. I have given this my best go at listening and reading from what I have seen online, before asking here.
I just want one rectangle to go up one slope. I am not after a function for this. Each tutorial/article/video I watch explains how their function/class works. Some are using lists of classes and functions that call other functions inside them. It gets very abstract and it is to much for me right now.
I need someone to really baby this down for me it seems. No functions and no classes. I just want to move one rectangle up one 45 degree slope.
One youtube video explained that I need y = mx + b. But did not explain how to use this function. So if anyone out there has a formula for a basic 45 degree slope and can show me in my own code how to use it without functions or classes, i will be grateful.
After I understand it I can make my own functions and classes for implementing it. My attempt at this has been to make a rectangle behind my ramp image. Is this wrong? Should I be using a single line?
My attempt at code:
import pygame
import sys
pygame.init()
clock = pygame.time.Clock()
screensize = (800, 600)
screen = pygame.display.set_mode(screensize)
colour = [(0, 0, 0), (255, 0, 0), (255, 255, 255), (114, 216, 242), (200, 200, 200), (255, 199, 241), (50, 50, 50)]
# black 0 #red 1 #white 2 #light_blue 3 #gray 4 #light_pink 5 #dark_gray 6
moving_up = False
moving_down = False
moving_left = False
moving_right = False
gravity = 5
def collide(rect, rectangle_list):
hit_list = []
for rectangle in rectangle_list:
if rect.colliderect(rectangle):
hit_list.append(rectangle)
return hit_list
def move(rect, movement, tiles):
collision_types = {'top': False, 'bottom': False, 'right': False, 'left': False}
rect.x += movement[0]
hit_list = collide(rect, tiles)
for tile in hit_list:
if movement[0] > 0:
rect.right = tile.left
collision_types['right'] = True
elif movement[0] < 0:
rect.left = tile.right
collision_types['left'] = True
rect.y += movement[1]
hit_list = collide(rect, tiles)
for tile in hit_list:
if movement[1] > 0:
rect.bottom = tile.top
collision_types['bottom'] = True
elif movement[1] < 0:
rect.top = tile.bottom
collision_types['top'] = True
return rect, collision_types
player_rect = pygame.Rect(100, 51, 50, 50)
while True:
screen.fill(colour[6])
pygame.draw.polygon(screen, (255, 0, 255), [(300, 500), (300, 550), (250, 550)])
# ~~~~~~ List of rectangles
rectlist = []
small_rect = pygame.Rect(200, 200, 50, 50)
bottomrect_1 = pygame.Rect(0, screensize[1] - 50, screensize[0], 50)
bottomrect_2 = pygame.Rect(300, screensize[1] - 100, screensize[0], 50)
D_rect = pygame.Rect(250, screensize[1] - 100, 50, 50)
rectlist.append(small_rect)
rectlist.append(bottomrect_1)
rectlist.append(bottomrect_2)
# ~~~~~~ Player Movement
player_movement = [0, 0]
if moving_up:
player_movement[1] -= 2
if moving_down:
player_movement[1] += 2
if moving_left:
player_movement[0] -= 2
if moving_right:
player_movement[0] += 2
player_movement[1] += gravity
# ~~~~~~ Player Collision
my_rect, collision = move(player_rect, player_movement, rectlist)
# my attempt at this diagonal humbug. D_rect is the diagonal rect. (the slope)
if my_rect.colliderect(D_rect):
yy = D_rect.height + (my_rect.x - D_rect.x) * 1
my_rect.y -= yy/3.6
# ~~~~~~ Event Loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == pygame.K_w:
moving_up = True
if event.key == pygame.K_s:
moving_down = True
if event.key == pygame.K_a:
moving_left = True
if event.key == pygame.K_d:
moving_right = True
if event.key == pygame.K_SPACE:
gravity = -gravity
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
moving_up = False
if event.key == pygame.K_s:
moving_down = False
if event.key == pygame.K_a:
moving_left = False
if event.key == pygame.K_d:
moving_right = False
# ~~~~~~ Draw.
pygame.draw.rect(screen, (0, 255, 125), D_rect, 1)
pygame.draw.rect(screen, colour[3], small_rect)
pygame.draw.rect(screen, colour[4], my_rect)
pygame.draw.rect(screen, colour[5], bottomrect_1)
pygame.draw.rect(screen, colour[5], bottomrect_2)
pygame.display.update()
clock.tick(60)
Calculate the height of the diagonal rectangle on the right edge of the moving rectangle (my_rect.right):
dia_height = D_rect.height * (my_rect.right-D_rect.left) / D_rect.width
Compute the top of the the diagonal rectangle on the right edge of the moving rectangle:
D_rect_top = D_rect.bottom - round(dia_height)
The top of the the diagonal rectangle on the right edge of the moving rectangle is the bottom of the moving rectangle:
my_rect.bottom = D_rect_top
If the diagonal is in the opposite direction, find the height of the diagonal on the left edge (my_rect.left) instead of the right edge (my_rect.right).
The formula y = mx + b is hidden in this code:
x is my_rect.right - D_rect.left
m is -D_rect.height / D_rect.width
b is D_rect.bottom
y is my_rect.bottom
while True:
# [...]
if my_rect.colliderect(D_rect):
dia_height = D_rect.height * (my_rect.right-D_rect.left) / D_rect.width
D_rect_top = D_rect.bottom - round(dia_height)
my_rect.bottom = D_rect_top
# [....]

Restarting a snake game after game over screen appears in pygame

in the game that I have found on github there is a game over screen that shows your score, now I want to make the game restart if you press space so that you don't need to close the program and open it again to play it again. The problem isn't how to make the game restart when you press space but to actually make it restart. Here is the code:
import pygame
import random
import sys
import time
# Difficulty settings
# Easy -> 10
# Medium -> 25
# Hard -> 40
# Harder -> 60
# Impossible-> 120
difficulty = 25
# Window size
frame_size_x = 720
frame_size_y = 480
# Checks for errors encountered
check_errors = pygame.init()
# pygame.init() example output -> (6, 0)
# second number in tuple gives number of errors
if check_errors[1] > 0:
print(f'[!] Had {check_errors[1]} errors when initialising game, exiting...')
sys.exit(-1)
else:
print('[+] Game successfully initialised')
# Initialise game window
pygame.display.set_caption('Snake Eater')
game_window = pygame.display.set_mode((frame_size_x, frame_size_y))
# Colors (R, G, B)
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# FPS (frames per second) controller
fps_controller = pygame.time.Clock()
# Game variables
snake_pos = [100, 50]
snake_body = [[100, 50], [100 - 10, 50], [100 - (2 * 10), 50]]
food_pos = [random.randrange(1, (frame_size_x // 10)) * 10, random.randrange(1, (frame_size_y // 10)) * 10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
score = 0
# Game Over
def game_over():
my_font = pygame.font.SysFont('times new roman', 90)
game_over_surface = my_font.render('YOU DIED', True, red)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (frame_size_x / 2, frame_size_y / 4)
game_window.fill(black)
game_window.blit(game_over_surface, game_over_rect)
show_score(0, red, 'times', 20)
pygame.display.update()
time.sleep(3)
pygame.quit()
sys.exit()
# Score
def show_score(choice, color, font, size):
score_font = pygame.font.SysFont(font, size)
score_surface = score_font.render('Score : ' + str(score), True, color)
score_rect = score_surface.get_rect()
if choice == 1:
score_rect.midtop = (frame_size_x - 100, 15)
else:
score_rect.midtop = (frame_size_x / 2, frame_size_y / 1.25)
game_window.blit(score_surface, score_rect)
# pygame.display.flip()
# Main logic
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Whenever a key is pressed down
elif event.type == pygame.KEYDOWN:
# W -> Up; S -> Down; A -> Left; D -> Right
if event.key == pygame.K_UP or event.key == ord('w'):
change_to = 'UP'
if event.key == pygame.K_DOWN or event.key == ord('s'):
change_to = 'DOWN'
if event.key == pygame.K_LEFT or event.key == ord('a'):
change_to = 'LEFT'
if event.key == pygame.K_RIGHT or event.key == ord('d'):
change_to = 'RIGHT'
# Esc -> Create event to quit the game
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# Making sure the snake cannot move in the opposite direction instantaneously
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# Moving the snake
if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'RIGHT':
snake_pos[0] += 10
# Snake body growing mechanism
snake_body.insert(0, list(snake_pos))
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
score += 1
food_spawn = False
else:
snake_body.pop()
# Spawning food on the screen
if not food_spawn:
food_pos = [random.randrange(1, (frame_size_x // 10)) * 10, random.randrange(1, (frame_size_y // 10)) * 10]
food_spawn = True
# GFX
game_window.fill(black)
for pos in snake_body:
# Snake body
# .draw.rect(play_surface, color, xy-coordinate)
# xy-coordinate -> .Rect(x, y, size_x, size_y)
pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10))
# Snake food
pygame.draw.rect(game_window, white, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
# Game Over conditions
# Getting out of bounds
if snake_pos[0] < 0 or snake_pos[0] > frame_size_x - 10:
game_over()
if snake_pos[1] < 0 or snake_pos[1] > frame_size_y - 10:
game_over()
# Touching the snake body
for block in snake_body[1:]:
if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
game_over()
show_score(1, white, 'consolas', 20)
# Refresh game screen
pygame.display.update()
# Refresh rate
fps_controller.tick(difficulty)
Implement a function that initializes all the global game states:
def init_game():
global snake_pos, snake_body
global food_pos, food_spawn
global direction, change_to, score
# Game variables
snake_pos = [100, 50]
snake_body = [[100, 50], [100 - 10, 50], [100 - (2 * 10), 50]]
food_pos = [random.randrange(1, (frame_size_x // 10)) * 10, random.randrange(1, (frame_size_y // 10)) * 10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
score = 0
Invoke the function when SPACE is pressed:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Whenever a key is pressed down
elif event.type == pygame.KEYDOWN:
# [...]
if event.key == pygame.K_SPACE:
init_game()

How do I stop my snake moving into itself (python, pygame)

this is my first game I have created using pygame, it's basically snake.
Please do not mind my hideous comments.
## William's Snake Game
import pygame
import time
import random
pygame.init()
##Global variables
# Colours
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 155, 0)
bground = (204, 204, 0)
# Display vars.
display_width = 800
display_height = 600
# Variables
gameDisplay = pygame.display.set_mode((display_width, display_height)) ##resolution, note that this is a tuple.
pygame.display.set_caption("Snake VS Apple") # Title at the top of the screen
icon = pygame.image.load('logoapple32x32.png') # Loads the icon for the top left
pygame.display.set_icon(icon) # Sets the icon for the top left
snakeHeadImg = pygame.image.load("snakeHead.png") # Loads the image for the snake head
appleImg = pygame.image.load("apple20x20.png") # Loads the image for the apple
appleThickness = 20 # Defines how thick apple will be. Note to self: This is changable
clock = pygame.time.Clock() # Starts clocking the game, used later for FPS
blockSize = 20 # Defines how big the snake will be. Changing this will mess up collision detection.
FPS = 15 # Frames per second. Called at the bottom of script
smallfont = pygame.font.SysFont("arial", 25) ## format: ("font", fontsize)
medfont = pygame.font.SysFont("arial", 40) ##
largefont = pygame.font.SysFont("arial", 80) ##
direction = "right" # Starting direction of snake, used in main gameLoop
##
def pauseGame():
gameisPaused = True
while gameisPaused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
gameisPaused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("Paused",
black,
-100,
size="large")
message_to_screen("Press ESC to continue or Q to quit.",
black,
25,
size="small")
pygame.display.update()
clock.tick(5)
def text_objects(text, color, size): # Function to render text
if size == "small":
textSurface = smallfont.render(text, True, color)
elif size == "medium":
textSurface = medfont.render(text, True, color)
elif size == "large":
textSurface = largefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def message_to_screen(msg, color, y_displace=0, size="medium"): # Function to blit (draw) text to surface
textSurf, textRect = text_objects(msg, color, size)
textRect.center = (display_width / 2), (display_height / 2) + y_displace
gameDisplay.blit(textSurf, textRect)
##
def score(score):
text = smallfont.render("Score: " + str(score), True, black)
gameDisplay.blit(text, [0, 0])
def randAppleGen(): # Function to generate random apples
randAppleX = round(
random.randrange(0, display_width - appleThickness)) # /10.0)*10.0 ##Create another rand X value for new apple
randAppleY = round(
random.randrange(0, display_height - appleThickness)) # /10.0)*10.0 ##Create another rand Y value for new apple
return randAppleX, randAppleY
def gameIntro(): # Function for game menu.
intro = True
while intro: # Event handling during menu
for eachEvent in pygame.event.get():
if eachEvent.type == pygame.QUIT:
pygame.quit()
quit()
if eachEvent.type == pygame.KEYDOWN:
if eachEvent.key == pygame.K_c:
gameLoop()
if eachEvent.key == pygame.K_q:
pygame.quit()
quit()
# Text displayed in menu
gameDisplay.fill(white)
message_to_screen("Welcome to Slither",
green,
-90,
"large")
message_to_screen("The more apples you eat, the longer you are",
black,
100)
message_to_screen("The objective of the game is to eat red apples",
black,
0,
"small")
message_to_screen("If you run into yourself, or the edges, you die!",
black,
30,
"small")
message_to_screen("Press C to play or Q to quit.",
black,
180)
pygame.display.update()
clock.tick(500)
def snake(blockSize, snakeList): # Function to draw snake
if direction == "right":
head = pygame.transform.rotate(snakeHeadImg,
270) # In gameLoop, right,left,up,down are used to change direction of snakeHead
elif direction == "left":
head = pygame.transform.rotate(snakeHeadImg, 90)
elif direction == "up":
head = snakeHeadImg
elif direction == "down":
head = pygame.transform.rotate(snakeHeadImg, 180)
gameDisplay.blit(head, (snakeList[-1][0], snakeList[-1][1])) ##???
for XandY in snakeList[:-1]:
pygame.draw.rect(gameDisplay, green,
[XandY[0], XandY[1], blockSize, blockSize]) ##width height, width height, drawing
##Main Game Loop
def gameLoop():
global direction ## Make direction a global var. Important
# Local variables
gameExit = False
gameOver = False
lead_x = display_width / 2
lead_y = display_height / 2
lead_x_change = 10
lead_y_change = 0
snakeList = []
snakeLength = 3
randAppleX, randAppleY = randAppleGen() # Generate apples. Calls randAppleGen()
# Main Game Loop ##eventHandler
while not gameExit:
snakeHead = [] # Creates list snakeHead
snakeHead.append(lead_x) # Appends snakeHead x value to list
snakeHead.append(lead_y) # Appends snakeHead y value to list
snakeList.append(snakeHead) # Appends coordinates of snakeHead x,y to list
while gameOver == True: # Handles game over
gameDisplay.fill(white)
message_to_screen("Game over",
red,
-50,
size="large")
message_to_screen("Press C to play again or Q to quit",
black,
50,
size="medium")
pygame.display.update()
for event in pygame.event.get(): # eventHandler for loss screen
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
direction = "right"
gameLoop()
for event in pygame.event.get(): # eventHandler for keyboard events during game
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a: # Each of these handles either arrow keys or WASD key events.
lead_x_change = -blockSize
lead_y_change = 0
direction = "left"
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
lead_x_change = blockSize
lead_y_change = 0
direction = "right"
elif event.key == pygame.K_UP or event.key == pygame.K_w:
lead_y_change = -blockSize
lead_x_change = 0
direction = "up"
elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
lead_y_change = blockSize
lead_x_change = 0
direction = "down"
elif event.key == pygame.K_ESCAPE:
pauseGame()
# Checks if user has hit screen boundaries.
if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0: # If user hits display boundaries
gameOver = True # They lose
lead_x += lead_x_change # Ensures continous movement of the snake
lead_y += lead_y_change
# Drawing
gameDisplay.fill(bground) # Fills the display background with predefined bground colour (defined at the top)
gameDisplay.blit(appleImg,
(randAppleX, randAppleY)) ##Draws the apple using the appleImg, at random coordinates.
if len(
snakeList) > snakeLength: # If the length of the list of snake body coordinates is greater than the length
del snakeList[0] # Delete the oldest value in the list (as the snake is constantly moving)
for eachSegment in snakeList[:-1]: # For each coordinate in snakeList
if eachSegment == snakeHead: # If the segment touches the snakeHead
## gameDisplay.fill(bground)
## snake(blockSize, snakeList)
##
## pygame.display.update
time.sleep(0.3)
gameOver = True # Game over
snake(blockSize, snakeList) ##Creates snake using function snake
score(snakeLength - 3) # Displays score (it minuses 3 because the snake starts at 3)
pygame.display.update() ##Updates to screen
## COLLISION DETECTION
if lead_x + blockSize > randAppleX and lead_x < randAppleX + appleThickness:
if lead_y + blockSize > randAppleY and lead_y < randAppleY + appleThickness:
randAppleX, randAppleY = randAppleGen()
snakeLength += 1
clock.tick(FPS)
pygame.quit()
quit()
##update screen
##
gameIntro()
gameLoop()
##Code goes above.
I have a problem where if my snake is going right, and then it turns left, my snake will crash onto itself and the game will end.
I want to design this so when my snake is going right, it cannot simply turn left, crash into itself and end the game. So when it turns right, it can only turn up, down, or keep going right. So simply, I want to make it so it cannot run backwards into itself.
I have tried coding this in myself, and I have tried many methods but nothing has worked.
Please help!!
Without altering your code too much (and without testing), an easy way to get what you want is to add another condition to your key checks. If you alter the relevant code section as follows, all should be fine:
for event in pygame.event.get(): # eventHandler for keyboard events during game
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if (event.key == pygame.K_LEFT or event.key == pygame.K_a) and direction != "right": # Each of these handles either arrow keys or WASD key events.
lead_x_change = -blockSize
lead_y_change = 0
direction = "left"
elif (event.key == pygame.K_RIGHT or event.key == pygame.K_d) and direction != "left":
lead_x_change = blockSize
lead_y_change = 0
direction = "right"
elif (event.key == pygame.K_UP or event.key == pygame.K_w) and direction != "down":
lead_y_change = -blockSize
lead_x_change = 0
direction = "up"
elif (event.key == pygame.K_DOWN or event.key == pygame.K_s) and direction != "up":
lead_y_change = blockSize
lead_x_change = 0
direction = "down"
elif event.key == pygame.K_ESCAPE:
pauseGame()
Mind the parentheses around the or'd key checks!

How do implement classes into my Nibbles remake?

So I made a Nibbles/Snake remake by following the pygame tutorials on thenewboston youtube channel by sentdex. I made a lot of minor aesthetic changes, but overall, it's the same game. Here's the code for that:
import pygame
import time
import random
pygame.init()
# A few extra colors just for testing purposes.
WHITE = (pygame.Color("white"))
BLACK = ( 0, 0, 0)
RED = (245, 0, 0)
TURQ = (pygame.Color("turquoise"))
GREEN = ( 0, 155, 0)
GREY = ( 90, 90, 90)
SCREEN = (800, 600)
gameDisplay = pygame.display.set_mode(SCREEN)
#Set the window title and picture
pygame.display.set_caption('Slither')
ICON = pygame.image.load("apple10pix.png")
pygame.display.set_icon(ICON)
CLOCK = pygame.time.Clock()
FPS = 20
FONT = pygame.font.SysFont("arial", 25)
SNAKE_SIZE = 10 # The width of the snake in pixels, not the length. Start length is defined in the game loop.
APPLE_SIZE = 10
TINY_FONT = pygame.font.SysFont("candara", 15)
SMALL_FONT = pygame.font.SysFont("candara", 25)
MED_FONT = pygame.font.SysFont("candara", 50)
LARGE_FONT = pygame.font.SysFont("krabbypatty", 75)
HUGE_FONT = pygame.font.SysFont("krabbypatty", 150)
IMG = pygame.image.load("snakehead.png")
APPLE_IMG = pygame.image.load("apple10pix.png")
DIRECTION = "up"
def pause():
paused = True
message_to_screen("Paused",
BLACK,
Y_DISPLACE = -100,
size = "huge")
message_to_screen("Press C to continue or Q to quit.",
BLACK,
Y_DISPLACE = 25)
pygame.display.update()
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key in (pygame.K_c, pygame.K_p):
paused = False
elif event.key in(pygame.K_q, pygame.K_ESCAPE):
pygame.quit()
quit()
CLOCK.tick(5)
def score(score):
text = SMALL_FONT.render("Score: " + str(score), True, BLACK)
gameDisplay.blit(text, [0, 0])
pygame.display.update
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
if event.key in (pygame.K_q, pygame.K_ESCAPE):
pygame.quit()
quit()
gameDisplay.fill(WHITE)
message_to_screen("Welcome to",
GREEN,
Y_DISPLACE = -170,
size = "large")
message_to_screen("Block Worm",
GREEN,
Y_DISPLACE = -50,
size = "huge")
message_to_screen("The objective of the game is to eat apples.",
BLACK,
Y_DISPLACE = 36,
size = "tiny")
message_to_screen("The more apples you eat the longer you get.",
BLACK,
Y_DISPLACE = 68,
size = "tiny")
message_to_screen("If you run into yourself or the edges, you die.",
BLACK,
Y_DISPLACE = 100,
size = "tiny")
message_to_screen("Press C to play or Q to quit.",
GREY,
Y_DISPLACE = 210,)
pygame.display.update()
CLOCK.tick(FPS)
def snake(SNAKE_SIZE, SNAKE_LIST):
if DIRECTION == "right":
HEAD = pygame.transform.rotate(IMG, 270)
elif DIRECTION == "left":
HEAD = pygame.transform.rotate(IMG, 90)
elif DIRECTION == "down":
HEAD = pygame.transform.rotate(IMG, 180)
else:
DIRECTION == "up"
HEAD = IMG
gameDisplay.blit(HEAD, (SNAKE_LIST[-1][0], SNAKE_LIST[-1][1]))
for XnY in SNAKE_LIST[:-1]:
pygame.draw.rect(gameDisplay, GREEN, [XnY[0], XnY[1], SNAKE_SIZE, SNAKE_SIZE])
pygame.display.update
def text_objects(text, color, size):
if size == "tiny":
TEXT_SURFACE = TINY_FONT.render(text, True, color)
elif size == "small":
TEXT_SURFACE = SMALL_FONT.render(text, True, color)
elif size == "medium":
TEXT_SURFACE = MED_FONT.render(text, True, color)
elif size == "large":
TEXT_SURFACE = LARGE_FONT.render(text, True, color)
elif size == "huge":
TEXT_SURFACE = HUGE_FONT.render(text, True, color)
return TEXT_SURFACE, TEXT_SURFACE.get_rect()
def message_to_screen(msg, color, Y_DISPLACE = 0, size = "small"):
TEXT_SURF, TEXT_RECT = text_objects(msg, color, size)
TEXT_RECT.center = (SCREEN[0] / 2), (SCREEN[1] / 2) + Y_DISPLACE
gameDisplay.blit(TEXT_SURF, TEXT_RECT)
def randAppleGen():
randAppleX = random.randrange(0, (SCREEN[0] - APPLE_SIZE), APPLE_SIZE)
randAppleY = random.randrange(0, (SCREEN[1]- APPLE_SIZE), APPLE_SIZE)
return randAppleX, randAppleY
def gameLoop():
global DIRECTION
gameExit = False
gameOver = False
SNAKE_LIST = [] # Where the snake head has been.
SNAKE_LENGTH = 1 #Length that the snake starts.
lead_x = (SCREEN[0] / 2)
lead_y = (SCREEN[1] - (SCREEN[1] / 5))
move_speed = 10
move_speed_neg = move_speed * -1
lead_x_change = 0
lead_y_change = -move_speed
randAppleX, randAppleY = randAppleGen()
while not gameExit:
if gameOver == True:
message_to_screen("Game over",
RED,
Y_DISPLACE = -50,
size = "huge")
message_to_screen("Press C to play again or Q to quit.",
BLACK,
Y_DISPLACE = 50,
size = "small")
pygame.display.update()
while gameOver == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameOver = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameOver = False
gameExit = True
elif event.key == pygame.K_c:
gameLoop()
# Handles arrow key and WASD events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
if event.key in (pygame.K_LEFT, pygame.K_a):
lead_x_change = move_speed_neg
lead_y_change = 0
DIRECTION = "left"
elif event.key in (pygame.K_RIGHT, pygame.K_d):
lead_x_change = move_speed
lead_y_change = 0
DIRECTION = "right"
elif event.key in (pygame.K_UP, pygame.K_w):
lead_y_change = move_speed_neg
lead_x_change = 0
DIRECTION = "up"
elif event.key in (pygame.K_DOWN, pygame.K_s):
lead_y_change = move_speed
lead_x_change = 0
DIRECTION = "down"
elif event.key in (pygame.K_p, pygame.K_ESCAPE):
pause()
# If the snake goes beyond the screen borders the game will end.
if lead_x >= SCREEN[0] or lead_x < 0 or lead_y >= SCREEN[1] or lead_y <0:
gameOver = True
lead_x += lead_x_change
lead_y += lead_y_change
gameDisplay.fill(WHITE)
# Draw the apple on screen
APPLE_RECT = pygame.draw.rect(gameDisplay, RED, [randAppleX, randAppleY, APPLE_SIZE, APPLE_SIZE])
if APPLE_RECT in SNAKE_LIST:
APPLE_RECT #If the apple appears anywhere "under" the snake, it will immediately respawn elsewhere.
# Draw the snake on screen
SNAKE_HEAD = []
SNAKE_HEAD.append(lead_x)
SNAKE_HEAD.append(lead_y)
SNAKE_LIST.append(SNAKE_HEAD)
# If you hit yourself, game over.
if SNAKE_HEAD in SNAKE_LIST[:-1]:
gameOver = True
if len(SNAKE_LIST) > SNAKE_LENGTH:
del SNAKE_LIST[0]
snake(SNAKE_SIZE, SNAKE_LIST)
score(SNAKE_LENGTH - 1)
# If the snake eats the apple
if APPLE_RECT.collidepoint(lead_x, lead_y) == True:
randAppleX, randAppleY = randAppleGen()
SNAKE_LENGTH += 1
pygame.display.update()
CLOCK.tick(FPS)
pygame.quit()
quit()
game_intro()
gameLoop()
It's a pretty solid little game. But I want to make the snake and apple into classes so that I can later spawn other types of snakes (perhaps basic AI?) and other types of apples (maybe ones that are green that grow your snake 3+). I made an attempt at doing this myself with a snake class:
import pygame
import time
import random
pygame.init()
WHITE = (pygame.Color("white"))
BLACK = ( 0, 0, 0)
RED = (245, 0, 0)
TURQ = (pygame.Color("turquoise"))
GREEN = ( 0, 155, 0)
GREY = ( 90, 90, 90)
SCREEN = (800, 600)
gameDisplay = pygame.display.set_mode(SCREEN)
#Set the window title and picture
pygame.display.set_caption('Block Worm')
ICON = pygame.image.load("apple10pix.png")
pygame.display.set_icon(ICON)
CLOCK = pygame.time.Clock()
FPS = 20
FONT = pygame.font.SysFont("arial", 25)
APPLE_SIZE = 10
TINY_FONT = pygame.font.SysFont("candara", 15)
SMALL_FONT = pygame.font.SysFont("candara", 25)
MED_FONT = pygame.font.SysFont("candara", 50)
LARGE_FONT = pygame.font.SysFont("krabbypatty", 75)
HUGE_FONT = pygame.font.SysFont("krabbypatty", 150)
IMG = pygame.image.load("snakehead.png")
APPLE_IMG = pygame.image.load("apple10pix.png")
def pause():
paused = True
message_to_screen("Paused",
BLACK,
Y_DISPLACE = -100,
size = "huge")
message_to_screen("Press C to continue or Q to quit.",
BLACK,
Y_DISPLACE = 25)
pygame.display.update()
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key in (pygame.K_c, pygame.K_p):
paused = False
elif event.key in(pygame.K_q, pygame.K_ESCAPE):
pygame.quit()
quit()
CLOCK.tick(5)
def score(score):
text = SMALL_FONT.render("Score: " + str(score), True, BLACK)
gameDisplay.blit(text, [5, 5])
pygame.display.update
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
if event.key in (pygame.K_q, pygame.K_ESCAPE):
pygame.quit()
quit()
gameDisplay.fill(WHITE)
message_to_screen("Welcome to",
GREEN,
Y_DISPLACE = -170,
size = "large")
message_to_screen("Block Worm",
GREEN,
Y_DISPLACE = -50,
size = "huge")
message_to_screen("The objective of the game is to eat apples.",
BLACK,
Y_DISPLACE = 36,
size = "tiny")
message_to_screen("The more apples you eat the longer you get.",
BLACK,
Y_DISPLACE = 68,
size = "tiny")
message_to_screen("If you run into yourself or the edges, you die.",
BLACK,
Y_DISPLACE = 100,
size = "tiny")
message_to_screen("Press C to play or Q to quit.",
GREY,
Y_DISPLACE = 210,)
pygame.display.update()
CLOCK.tick(FPS)
def text_objects(text, color, size):
if size == "tiny":
TEXT_SURFACE = TINY_FONT.render(text, True, color)
elif size == "small":
TEXT_SURFACE = SMALL_FONT.render(text, True, color)
elif size == "medium":
TEXT_SURFACE = MED_FONT.render(text, True, color)
elif size == "large":
TEXT_SURFACE = LARGE_FONT.render(text, True, color)
elif size == "huge":
TEXT_SURFACE = HUGE_FONT.render(text, True, color)
return TEXT_SURFACE, TEXT_SURFACE.get_rect()
def message_to_screen(msg, color, Y_DISPLACE = 0, size = "small"):
TEXT_SURF, TEXT_RECT = text_objects(msg, color, size)
TEXT_RECT.center = (SCREEN[0] / 2), (SCREEN[1] / 2) + Y_DISPLACE
gameDisplay.blit(TEXT_SURF, TEXT_RECT)
def randAppleGen():
randAppleX = random.randrange(0, (SCREEN[0] - APPLE_SIZE), APPLE_SIZE)
randAppleY = random.randrange(0, (SCREEN[1]- APPLE_SIZE), APPLE_SIZE)
return randAppleX, randAppleY
class Snake:
def __init__(self, image, x, y, direction, speed):
self.image = image
self.rect = self.image.get_rect()
self.width = self.rect.width
self.rect.x = x
self.rect.y = y
self.direction = direction
self.speed = speed
self.trail = [] # Where the snake head has been.
self.length = 1 # Length that the snake starts.
def snake_direction_change(direction):
if direction == "right":
self.image = pygame.transform.rotate(self.image, 270)
elif direction == "left":
self.image = pygame.transform.rotate(self.image, 90)
elif direction == "down":
self.image = pygame.transform.rotate(self.image, 180)
else:
direction == "up"
pygame.display.update
def snake_grow(x, y, z):
gameDisplay.blit(self.image, (self.trail[-1][0], self.trail[-1][1]))
for XnY in snake.trail[:-1]:
pygame.draw.rect(gameDisplay, GREEN, [XnY[0], XnY[1], self.width, self.width])
pygame.display.update
def gameLoop():
gameExit = False
gameOver = False
lead_x_change = 0
lead_y_change = -snake.speed
randAppleX, randAppleY = randAppleGen()
gameDisplay.fill(WHITE)
snake = Snake(IMG,
x = (SCREEN[0] / 2),
y =(SCREEN[1] - (SCREEN[1] / 5)),
direction = "up",
speed = 10,)
while not gameExit:
if gameOver == True:
message_to_screen("Game over",
RED,
Y_DISPLACE = -50,
size = "huge")
message_to_screen("Press C to play again or Q to quit.",
BLACK,
Y_DISPLACE = 50,
size = "small")
pygame.display.update()
while gameOver == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameOver = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameOver = False
gameExit = True
elif event.key == pygame.K_c:
gameLoop()
# Handles arrow key and WASD events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
if event.key in (pygame.K_LEFT, pygame.K_a):
lead_x_change = snake.speed * -1
lead_y_change = 0
snake.snake_direction_change("left")
elif event.key in (pygame.K_RIGHT, pygame.K_d):
lead_x_change = snake.speed
lead_y_change = 0
snake.snake_direction_change("right")
elif event.key in (pygame.K_UP, pygame.K_w):
lead_y_change = snake.speed * -1
lead_x_change = 0
snake.snake_direction_change("up")
elif event.key in (pygame.K_DOWN, pygame.K_s):
lead_y_change = snake.speed
lead_x_change = 0
snake.snake_direction_change("down")
elif event.key in (pygame.K_p, pygame.K_ESCAPE):
pause()
# If the snake goes beyond the screen borders the game will end.
if snake.rect.x >= SCREEN[0] or snake.rect.x < 0 or snake.rect.y >= SCREEN[1] or snake.rect.y <0:
gameOver = True
snake.rect.x += lead_x_change
snake.rect.y += lead_y_change
gameDisplay.fill(WHITE)
# Draw the apple on screen
APPLE_RECT = pygame.draw.rect(gameDisplay, RED, [randAppleX, randAppleY, APPLE_SIZE, APPLE_SIZE])
if APPLE_RECT in snake.trail:
APPLE_RECT #If the apple appears anywhere "under" the snake, it will immediately respawn elsewhere.
# Draw the snake on screen
SNAKE_HEAD = []
SNAKE_HEAD.append(snake.rect.x)
SNAKE_HEAD.append(snake.rect.y)
snake.trail.append(SNAKE_HEAD)
# If you hit yourself, game over.
if SNAKE_HEAD in snake.trail[:-1]:
gameOver = True
if len(snake.trail) > snake.length:
del snake.trail[0]
snake.snake_grow(snake.width, snake.trail)
score(snake.length - 1)
# If the snake eats the apple
if APPLE_RECT.collidepoint(snake.rect.x, snake.rect.y) == True:
randAppleX, randAppleY = randAppleGen()
snake.length += 1
pygame.display.update()
CLOCK.tick(FPS)
pygame.quit()
quit()
game_intro()
gameLoop()
This version isn't nearly as cute. In fact, it doesn't work at all. My understanding off classes and functions is elementary at best. A lot of code from the original was changed or completely deleted in my trial and error processes. I spent several hours trying to make this work to no avail. My main goal was to produce a Snake and Apple class that can be reused for later variations of both of them.
So, I've come to you fine folks to assist me! I have two main questions:
1) What do I have to do to make this work properly?
2) How can I clean up my code to make it easier to read and more efficient overall?
"A lot of code from the original was changed or completely deleted in my trial and error processes"
Bingo. You just found the crux of your issue. Software development should be a controlled, thought out process - not trial and error. You need to proceed thoughtfully, and purposefully.
What you are trying to do (or should be trying to do) when introducing classes is refactoring your code.
You should start again with the original, working copy, and proceed to change as little as possible when you introduce a Snake class. The first step would be to simply convert your snake function into a class, and substitute that in. Below is where you might start: replace your snake method with this Snake class, and change the line where you use it
class Snake:
def __init__(self, SNAKE_SIZE, SNAKE_LIST):
if DIRECTION == "right":
HEAD = pygame.transform.rotate(IMG, 270)
elif DIRECTION == "left":
HEAD = pygame.transform.rotate(IMG, 90)
elif DIRECTION == "down":
HEAD = pygame.transform.rotate(IMG, 180)
else:
DIRECTION == "up" # note: this line does nothing
HEAD = IMG
gameDisplay.blit(HEAD, (SNAKE_LIST[-1][0], SNAKE_LIST[-1][1]))
for XnY in SNAKE_LIST[:-1]:
pygame.draw.rect(gameDisplay, GREEN, [XnY[0], XnY[1], SNAKE_SIZE, SNAKE_SIZE])
pygame.display.update # note: this likely does nothing - I think you want to call it (pygame.display.update())
and change this:
snake(SNAKE_SIZE, SNAKE_LIST)
into:
snake = Snake(SNAKE_SIZE, SNAKE_LIST)
Now at this point, if your code worked before, it should still work (assuming I haven't done anything silly). Is this a good example of a class? No. My Snake class is terrible. Your attempt at a snake class is far, far better. Doing things this way gives you a starting point though. You can then proceed to do things like:
assign the parameters to instance variables
move pretty much all the code into another method
start removing the module-level variables it has access to, and pass in additional arguments
etc.
An alternate way to refactor this module might be to change each of your functions so that none of them rely on module level variables. Pass every variable that each function needs into that function.
The main point I'd like to leave you with is that it is far easier to make working software by writing/changing just a little at a time. Make sure it still works before changing something else. Work on small bits of code & test each change so you'll know exactly where and how your program broke.

Categories

Resources