Skip to content Skip to sidebar Skip to footer

Pygame Window Won't Stay Open

I decided to try and make the snake-eating dot game on my own. I can't make my pygame window stay open when I try and run what I have. How can I make it stay open? import pygame im

Solution 1:

Had to rewrite more than half of the code. I wouldn't suggest following what guide you were using. Furthermore if you are very beginner at the python language I wouldn't recommend looking into object orientation just yet. First learn about data types, and loops. You can still make pygame projects without object orientation, but if you know how to use OOP then still use it.

import pygame
import time
import random

red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
black = (0,0,0)
white = (255,255,255)

snake_width = 20
snake_height = 20

pygame.init()

game_width = 800
game_height = 600

x_change = 0
y_change = 0

gameDisplay = pygame.display.set_mode((game_width,game_height))
pygame.display.set_caption('Snake Game!')
clock = pygame.time.Clock()
gameDisplay.fill(black)

class snake:

    def __init__(self, color, thingw, thingh, movementspeedX, movementspeedY):
        self.color = color
        self.width = thingw
        self.height = thingh
        self.Xspeed = movementspeedX
        self.Yspeed = movementspeedY
        self.snake_startx = (game_width/2)
        self.snake_starty = (game_height/2)
        self.Xpos = self.snake_startx
        self.Ypos = self.snake_starty


    def Draw(self):

        pygame.draw.rect(gameDisplay, self.color, pygame.Rect([self.Xpos, self.Ypos, self.width, self.height]))

    def Update(self):
        self.Xpos += self.Xspeed
        self.Ypos += self.Yspeed







SnakeObject = snake(white, snake_width, snake_height, x_change, y_change)
SnakeObject.Draw()

gameRunning = True
while gameRunning:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            print("QUIT")
            pygame.quit()
            gameRunning = False
            quit() 

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                SnakeObject.Xspeed = -5
                SnakeObject.Yspeed = 0
            elif event.key == pygame.K_RIGHT:
                SnakeObject.Xspeed = 5
                SnakeObject.Yspeed = 0
            elif event.key == pygame.K_DOWN:
                SnakeObject.Yspeed = 5
                SnakeObject.Xspeed = 0
            elif event.key == pygame.K_UP:
                SnakeObject.Yspeed = -5
                SnakeObject.Xspeed = 0

    print(SnakeObject.Yspeed)
    print(SnakeObject.Xspeed)
    SnakeObject.Update()
    SnakeObject.Draw()
    pygame.display.update()
    clock.tick(60)

Post a Comment for "Pygame Window Won't Stay Open"