HamiClash
HamiClash

Reputation: 11

pygame window opens and instantly closes

So I have a file in the same folder as the file i'm coding right now and when the code runs in pycharm, if I press left arrow the other file is opened, but if I open the file using python straight from the file location it just opens and closes. Here is my code:

import pygame
import sys
import random
import subprocess
pygame.init()
GUI = pygame.display.set_mode((800,600))
pygame.display.set_caption("The incredible guessing game")
x = 284
y = 250
width = 68
length =  250
run = True
while run:
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        run =False
if event.type == pygame.KEYDOWN:
 command = "python AhjaiyGame.py"
 subprocess.call(command)

pygame.draw.rect(GUI, (255,210,0), (x,y,length,width))
pygame.display.update()


pygame.quit()

Upvotes: 1

Views: 23920

Answers (2)

Abhishek kumar
Abhishek kumar

Reputation: 139

import pygame
import sys
import random
import subprocess
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("The incredible guessing game")

x = 40
y = 30
width = 10
height =  20
vel=0.1
run = True
while run:
 for event in pygame.event.get():
   if event.type == pygame.QUIT:
     run =False
 keys=pygame.key.get_pressed()
 if keys[pygame.K_LEFT]:
      x-=vel
 if keys[pygame.K_RIGHT]:
      x+=vel
 if keys[pygame.K_UP]:
      y-=vel
 if keys[pygame.K_DOWN]:
      y+=vel
 win.fill((0,0,0))         
 pygame.draw.rect(win, (255,0,0), (x,y,width,height))
 pygame.display.update()

pygame.quit()

Upvotes: 0

Matt Clark
Matt Clark

Reputation: 28639

Simply put, the program exists because it has completed running.

Python is tabulation based, and in the code you posted, the while loop is not actually doing anything.

You need to indent the code you need looped:

while run:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run =False

        if event.type == pygame.KEYDOWN:
            command = "python AhjaiyGame.py"
            subprocess.call(command)

    pygame.draw.rect(GUI, (255,210,0), (x,y,length,width))
    pygame.display.update()

pygame.quit()

Notice the tabulation.

In this example, pygame.quit() will only be called when run becomes False and the while loop completes.

Upvotes: 2

Related Questions