0
votes

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()
2
for loop in your code should be part of the above while loop. And if statement with condition event.type=pygame.KEYDOWN should be part of for loop. And statement for drawing rectangle should be part of a while loop. - Abhishek kumar

2 Answers

1
votes

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.

0
votes
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()