Reputation: 423
I ran this code for testing if it works and continue but I saw this closes immediately after opening why what is the problem here I checked many different things What is wrong in this code? How to fix that?
import pygame
import random
pygame.init()
x=480
y=680
tick=pygame.time.Clock()
x_change=0
red=(0,0,255)
green=(0,255,0)
white=(255,255,255)
graphic=pygame.display.set_mode((700,700))
graphic.fill(green)
noexit=True
while noexit:
pygame.draw.rect(graphic,white,(x,y,20,20))
pygame.display.flip()
for event in pygame.event.get():
if event.type==pygame.QUIT:
noexit=False
elif event.type==pygame.KEYDOWN:
if event.key==K_RIGHT:
x_change=+2
elif event.key==K_LEFT:
x_change=-2
elif event.type==pygame.KEYUP:
if event.key==K_RIGHT or event.key==K_LEFT:
x_change=0
tick.tick(60)
pygame.quit()
quit()
Upvotes: 0
Views: 313
Reputation: 36
Suggestions:
import sys
...
sys.quit()
Like as https://stackoverflow.com/users/14531062/matiiss said, you should add pygame.
to all the consonants that come from pygame.
You might consider use pgzero (pygame zero) because it is easier.
Errors:
There is a syntax error in lines 22 and 27 where it's +=
and -=
not =+
and =-
.
Just remove quit.
Here's what your converted code might look like from all the suggestions and errors:
import pgzrun #this line imports pygame zero
import random
import pygame
pygame.init()
x=480
y=680
rect1 = Rect(x, y, 20, 20)
tick=pygame.time.Clock()
def draw(): #you don't have to call draw or update in pygame zero
screen.clear()
screen.fill("green")
screen.draw.filled_rect(rect1, "white")
def update():
global rect1
if keyboard.right:
rect1.x += 2
elif keyboard.left:
rect1.x -= 2
tick.tick(60)
pgzrun.go()
NOTES:
Since pygame zero is a third-party program, install it in the command terminal.
Windows: pip install pgzero Mac: pip3 install pgzero
You might need to learn pygame zero to understand the code. Go to https://pygame-zero.readthedocs.io/en/stable/ to learn more about pygame zero.
Upvotes: 2