So I wrote a code and when I start it, it runs for 1-2 seconds but then it eventually stops. Here is the problem: I press start then the window pops up with the name of the code/game and with the background color, but nothing else happens. Then it closes. I get this exit code every time:
Process finished with exit code 0
I don't know why it does this, but I am really curious. If someone can figure it out I would be more than happy.
Thanks in advance!
Here is the code:
import random
import pygame
pygame.init()
clock = pygame.time.Clock()
orangecolor = (255, 123, 7)
greencolor = (0, 255, 0)
blackcolor = (0, 0, 0)
redcolor = (213, 50, 80)
bluecolor = (50, 153, 213)
display_width = 600
display_height = 400
dis = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Snake')
snake_block = 10
snake_speed = 15
snake_list = []
def snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, greencolor, [x[0], x[1], snake_block, snake_block])
def snakegame():
game_over = False
game_end = False
x1 = display_width / 2
y1 = display_height / 2
x1_change = 0
y1_change = 0
snake_list = []
Length_of_snake = 1
foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
while not game_over:
while game_end:
score_font = pygame.font.SysFont("timesnewromanpsmt", 35)
dis.fill(blackcolor)
mesg = score_font.render("Press 'P' to start again", True, greencolor)
dis.blit(mesg, [display_width / 6, display_height / 3])
score = Length_of_snake - 1
value = score_font.render("Your score: " + str(score), True, greencolor)
dis.blit(value, [display_width / 3, display_height / 5])
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
snakegame()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
game_end = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = snake_block
x1_change = 0
elif event.key == pygame.K_LEFT:
y1_change = snake_block
x1_change = 0
if x1 >= display_width or x1 < 0 or y1 >= display_height or y1 < 0:
x1 += x1_change
y1 += y1_change
dis.fill(blackcolor)
pygame.draw.rect(dis, redcolor, [foodx, foody, snake_block, snake_block])
snake_Head = [x1, y1]
snake_list.append(snake_Head)
if len(snake_list) > Length_of_snake:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_Head:
game_end = True
snake(snake_block, snake_list)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
snakegame()