Hey I've been trying to call the pygame events in a function to reduce the clutter of my code. But I am unable to perform the process due to an error with global variables. Any help would be appreciated.
from pygame.locals import *
import pygame, sys
def color():
screen.fill((85,163,48))
def events():
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
print "left"
#sets the game map variables
tilesize = 100
map_width = 600
map_height = 300
#initialises the game screen setting it up with the game map variables
pygame.init()
screen = pygame.display.set_mode((map_width,map_height))
while True:
color()
events()
pygame.display.update()
If you're unable to access a value locally from within a function, the answer is to simply pass the value into the function. Something simple like this should suffice:
def events(ev_list):
for event in ev_list:
if event.type == QUIT:
pygame.quit()
within your game loop you'd call it with:
event_list = pygame.event.get()
events(event_list)
alternatively (less desirable) you can import a library from within the function or declare a variable global
Related
I keep getting an error about system not being initialised. The error is about the pygame.display.update()
Where is this meant to go?
import pygame #IMPORTS THE PYGAME CLASSES, METHODS AND ATTRIBUTES
from pygame.locals import * #IMPORTING ALL PYGAME MODULES
pygame.init() #INITIALISING PYGAME
WIDTH, HEIGHT = 1000, 600
WINDOW = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("On The Run")
blue = 146,244,255 #BACKGROUND COLOUR
width = 80
height = 60
x = 200 #X-POSITION OF THE CHARACTER
y = 100 #Y-POSITION OF THE CHARACTER
player1 = pygame.image.load('assets/characterMove3.jpg') #DISPLAYING THE IMAGE ONTO THE SCREEN
player1 = pygame.transform.scale(player1,(width,height)) #SCALING THE IMAGE TO SUITABLE DIMENSIONS
WINDOW.blit(player1,(x,y))
def game_loop(): #WHERE THE WINDOW IS CREATED
run = True
while run:
WINDOW.fill(blue)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False #WE WILL QUIT THE GAME AS THE VARIABLE run IS NOW FALSE
pygame.quit() #IT WON'T SHOW THE MOST RECENT THING I DREW UNLESS I MANUALLY UPDATE IT
pygame.display.update()
game_loop()
The problem is that pygame.quit() is called in the application loop. pygame.quit() deinitializes all Pygame modules and crashes all subsequent Pygame API calls. pygame.quit() must be the very last Pygame API call. Call pygame.quit() after the application loop:
def game_loop(): #WHERE THE WINDOW IS CREATED
run = True
while run:
WINDOW.fill(blue)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#pygame.quit() <-- DELETE
pygame.display.update()
pygame.quit() # <-- INSERT
game_loop()
I have been looking for a way to make an autoclicker, since I haven't had any experience with clicking/typing in Python via a macro. I wanted the program to be able to detect when I press a button (F1) and start clicking constantly until I press the stop button (F2); unfortunately, my code won't output the cps variable and the x and y variable. I just need to be able to detect that it's working there to move on to my actual clicking.
Basically, I'm asking how to fix the key detection.
Python version: 3.6.5
EDIT: i know it checks for 1 and 2, the f1 was opening a python help screen when pressed- so for now im just doing 1 and 2
import random, pygame, pyautogui, time
loop = 1
on = 0
pygame.init()
while(loop == 1):
key = pygame.key.get_pressed()
if(key[pygame.K_1]):
on = 1
elif(key [pygame.K_2]):
on = 0
if(on == 1):
x,y = pygame.mouse.get_pos()
cps = random.randint(10,20)
print(cps, x,y)
Define a user event and call pygame.time.set_timer with this event as the first argument and pygame will start adding the event to the queue after the specified time interval.
import random
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
CLICK_EVENT = pg.USEREVENT + 1
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_1:
pg.time.set_timer(CLICK_EVENT, 1000) # Start the timer.
elif event.key == pg.K_2:
pg.time.set_timer(CLICK_EVENT, 0) # Stop the timer.
elif event.type == CLICK_EVENT:
print(random.randint(10, 20), pg.mouse.get_pos())
screen.fill(BG_COLOR)
pg.display.flip()
clock.tick(30)
pg.quit()
Your code currently checks for the 1 and 2 number keys.
You want K_F1 and K_F2, not K_1 and K_2, for the function keys.
I've got this code:
import pygame, sys
from pygame.locals import *
pygame.init()
WHITE = (255,255,255)
class setup():
def set_resolution(x, y):
global surf
global screen
surf = pygame.Surface((x,y))
screen = pygame.display.set_mode((x,y))
pygame.display.set_caption("Lewis' Game")
pygame.draw.rect(screen, WHITE,(200,150,150,50))
def menu():
pass
setup.set_resolution(1024,768)
setup.menu()
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
For some reason, the pygame.draw.rect(screen, WHITE,(200,150,150,50)) at the end of the setup function doesn't actually appear unless I show the desktop and them tab back in. I'm not sure why this is happening as it's never happened before. I should mention that I'm still learning pygame, and this code is just for practice.
Many thanks in advance.
change your while loop to include this:
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
pygame.display.flip() # pygame.display.update works as well
if you want more on the difference of these, see Difference between pygame.display.update and pygame.display.flip
This question already has answers here:
How to get keyboard input in pygame?
(11 answers)
What all things happens inside pygame when I press a key? When to use pygame.event==KEYDOWN
(1 answer)
Closed 2 years ago.
I have installed vs code and added pygame snippets to use pygame library. My big problem is, every time I try to use any key option of pygame, like pygame.KEYDOWN or pygame.QUIT it tells me that QUIT is not a function of pygame. Can someone help me?
Everything else seems to work, like display or surface
even pygame.key.get_pressed() don’t make problems.
import pygame, random, sys
from pygame.locals import *
from pygame.key import *
def set_Background():
screen = pygame.display.set_mode((500,500))
surface = pygame.image.load('Background.png')
surface = pygame.transform.scale(surface, (500, 500))
screen.blit(surface, (0,0))
pygame.display.update()
return screen
def set_Enemy():
enemy = pygame.image.load('Enemy.png')
enemy = pygame.transform.scale(enemy, (50, 50))
return enemy
def set_Player():
player = pygame.image.load('Player.png')
player = pygame.transform.scale(player, (70, 70))
return player
RUNNING = True
while RUNNING:
background = set_Background()
enemy = set_Enemy()
player = set_Player()
enemy_rect = enemy.get_rect()
player_rect = player.get_rect()
e_x = random.randint(10,450)
e_y = random.randint(10,450)
background.blit(enemy, (e_x, e_y))
pygame.display.update()
for event in pygame.event.get():
key = pygame.key.get_pressed()
if event.type == key[pygame.K_ESCAPE]:
#module pygame has no K_ESCAPE member
sys.exit()
if event.type == pygame.QUIT:
#says module pygame has no QUIT member
sys.exit()
pygame.key.get_pressed() shouldn't be in the event loop, but in the main while loop. In the event loop you need to check if the event type is pygame.QUIT and then set the running flag to False.
Here's a fixed version:
import pygame
pygame.init()
screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()
running = True # Uppercase names are for constants not variables.
while running:
# The event loop.
for event in pygame.event.get():
# If a pygame.QUIT event is in the queue.
if event.type == pygame.QUIT:
running = False
# To check if it was a `KEYDOWN` event.
elif event.type == pygame.KEYDOWN:
# If the escape key was pressed.
if event.key == pygame.K_ESCAPE:
running = False
# Use pygame.key.get_pressed to see if a key is held down.
# This should not be in the event loop.
key = pygame.key.get_pressed()
if key[pygame.K_UP]:
print('up arrow pressed')
screen.fill((30, 30, 30))
pygame.display.flip()
clock.tick(60)
Add from pygame.locals import * at the top of your code.
You are mixing two types of key presses in one go. You should instead either
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SOMEKEY:
do_something()
or
keys = pygame.key.get_pressed()
if keys[pygame.K_somekey]:
do_something()
so the code above with the pygame.key.get_pressed() should not be in the event loop
im trying to split my code into functions and i want to input my own values for x and y. so the character can move from the inputed values. When i try to do this from the function call, nothing happens.
Any suggestions?
import pygame, sys
from pygame.locals import *
pygame.init()
width,height=(842,595)
screen = pygame.display.set_mode((width,height),0,32)
pygame.display.set_caption("game")
man = pygame.image.load("man.png")
target = pygame.image.load("star.png")
#setting a background image
bgimage= pygame.image.load("background.jpg")
##image for the jupiter object
another_target = pygame.image.load("jupiter.gif")
x = 100
y = height-300
another_targetx = 400
another_targety = 500
#allows movement whilst holding down key.
clock= pygame.time.Clock()
def move(x,y):
movingX =0
movingY =0
speedX =0
speedY=0
while True:
pygame.display.update()
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
elif event.type==KEYDOWN:
if event.key ==K_LEFT:
x-=5
elif event.key==K_RIGHT:
x+=5
elif event.key==K_UP:
y-=5
elif event.key==K_DOWN:
y+=5
time_Passed=clock.tick(25)
time_elapsed_seconds=time_Passed/1000.0
distanceX = time_elapsed_seconds*speedX
movingX+=distanceX
distanceY=time_elapsed_seconds*speedY
movingY+=distanceY
x+=movingX
y+=movingY
clock.tick(50)
pygame.display.update()
move(x,y)
screen.blit(bgimage,(0,0))
screen.blit(man, (x,y))
screen.blit( another_target,( another_targetx, another_targety))
screen.blit(target,(200,400))
pygame.display.update()
You have an infinite loop within the command move(x, y). The stuff on the outside of this loop which updates the screen is never reached, so nothing ever appears to happen. Try putting everything after the command definition into the while True loop inside the command.