How to make multi-keystroke function in Python - python

I'm using Python 3.5 and I want to make multi-keystroke function. I want to make a function that notices Ctrl+Q but my program didn't notice it.
Here's my code:
import threading, pygame
from pygame.locals import *
from time import sleep
pygame.init()
screen = pygame.display.set_mode((1160, 640), 0, 0)
screen.fill((255, 255, 255))
pygame.display.flip()
def background():
number = 0
while True:
if number < 10:
number = number + 1
print(number)
sleep(1)
else:
print("10 seconds are over!")
break
def foreground():
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.key.get_mods() & pygame.KMOD_CTRL and pygame.K_q:
print('HELLO_WORLD')
b = threading.Thread(name='background', target=background)
f = threading.Thread(name='foreground', target=foreground)
b.start()
f.start()
I also changed
def foreground():
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.key.get_mods() & pygame.KMOD_CTRL and pygame.K_q:
print('HELLO_WORLD')
to
def foreground():
while True:
key = pygame.key.get_pressed()
if key[pygame.key.get_mods() & pygame.KMOD_CTRL and pygame.K_q]:
print('HELLO_WORLD')
but it didn't notice Ctrl+Q.
How can I make it?

Here's a possible fix for your code:
import threading
import pygame
from pygame.locals import *
from time import sleep
import sys
pygame.init()
screen = pygame.display.set_mode((1160, 640), 0, 0)
screen.fill((255, 255, 255))
pygame.display.flip()
def background():
number = 0
while True:
if number < 10:
number = number + 1
print(number)
sleep(1)
else:
print("10 seconds are over!")
break
def foreground():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if pygame.key.get_mods() & pygame.KMOD_CTRL and event.key == pygame.K_q:
print('HELLO_WORLD')
pygame.display.update()
b = threading.Thread(name='background', target=background)
b.start()
foreground()

Related

Name 'event' can be undefined but event is clearly defined

I am trying to make a game from a tutorial I found on Youtube and then I come across this error that I cannot fix. I keep getting the error message: Name 'event' can be undefined. Can somebody help me? Thanks!
Here is my full code:
import pygame
from sys import exit
def display_score():
current_time = int(pygame.time.get_ticks() / 1000) - start_time
score_surf = test_font.render(f'{current_time}', False, (64, 64, 64))
score_rect = score_surf.get_rect(center=(400, 50))
screen.blit(score_surf, score_rect)
pygame.init()
screen = pygame.display.set_mode((800, 400))
pygame.display.set_caption('Runner')
clock = pygame.time.Clock()
test_font = pygame.font.Font('Pixeltype.ttf', 50)
game_active = True
start_time = 0
sky_surf = pygame.image.load('Sky.png').convert()
ground_surf = pygame.image.load('ground.png').convert()
snail_surf = pygame.image.load('snail1.png').convert_alpha()
snail_rect = snail_surf.get_rect(bottomright=(600, 300))
player_surf = pygame.image.load('player_walk_1.png').convert_alpha()
player_rect = player_surf.get_rect(midbottom=(80, 300))
player_gravity = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if game_active:
if event.type == pygame.MOUSEBUTTONDOWN:
if player_rect.collidepoint(event.pos) and player_rect.bottom >= 300:
player_gravity = -20
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and player_rect.bottom >= 300:
player_gravity = -20
else:
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
game_active = True
start_time = int(pygame.time.get_ticks() / 1000)
if game_active:
screen.blit(sky_surf, (0, 0))
screen.blit(ground_surf, (0, 300))
display_score()
snail_rect.x -= 4
if snail_rect.right <= 0: snail_rect.left = 800
screen.blit(player_surf, player_rect)
# Player
player_gravity += 1
player_rect.y += player_gravity
if player_rect.bottom >= 300: player_rect.bottom = 300
screen.blit(snail_surf, snail_rect)
# Collision
if snail_rect.colliderect(player_rect):
game_active = False
else:
screen.fill((94, 129, 162))
pygame.display.update()
clock.tick(60)
It's quite clear I have the variable 'event' defined in the while loop using the get function.
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if game_active:
if event.type == pygame.MOUSEBUTTONDOWN:
if player_rect.collidepoint(event.pos) and player_rect.bottom >= 300:
player_gravity = -20
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and player_rect.bottom >= 300:
player_gravity = -20
else:
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
game_active = True
start_time = int(pygame.time.get_ticks() / 1000)
This is the snippet of the code where the problem is:
Basically, what this else statement is supposed to do is to restart the game when clicked space bar. But it doesn't work because apparently the name event is not defined.
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
The weird thing is, is that I am only getting the error message specifically for this line of code and not any other code that has event.type in it. I believe it has something to do with this else statement and that's why it is not working. I deleted this else statement to see what would happen and the error message went away but it still won't work.
I tried reformatting the code, changing things around, indenting and unindenting, and etc. I tried re-pasting pygame.event.get(): into the else statement. Nothing worked.

How do I detect a click on an image thats being toggeled by another image

So i was messing around in computer science and starting actually getting some decent progress (for me) on a project that managed to last longer than 2 days.
I just want some help on what im doing wrong.
heres my code its like some fnaf spin off that im planning to add some watermelon enemy to. Im just confused on how to do this click detection
import pygame, random, time
import pygame_textinput
import prompts
pygame.init()
textinput = pygame_textinput.TextInputVisualizer()
font = pygame.font.SysFont("Comicsansms", 55)
display = pygame.display.set_mode((575, 375))
pygame.display.set_caption("Game")
clock = pygame.time.Clock()
pygame.key.set_repeat(200, 25)
room = pygame.image.load("assets/images/room.png")
dark = pygame.image.load("assets/images/dark.png")
light = pygame.image.load("assets/images/light.png")
mel = pygame.image.load("assets/images/waterelo.png")
tablet = pygame.image.load("assets/images/3.png")
cam1 = pygame.image.load("assets/images/winner1.png")
def wait(x):
time.sleep(x)
def insideimage(pos, rsurf):
refrect = rsurf.get_rect().move((100, 100))
pickedcol = display.get_at(pos)
return refrect.collidepoint(pos)
q = False
flash = False
while True:
display.fill((225, 225, 225))
display.blit(room, (0, 0))
events = pygame.event.get()
textinput.update(events)
for event in events:
if event.type == pygame.QUIT:
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
flash = not flash
if event.key == pygame.K_SPACE:
q = not q
elif event.type == pygame.MOUSEBUTTONDOWN and q == True:
if cam1.rect.collidepoint(event.pos):
print("hi")
if q == True:
display.blit(tablet, (-75, -75))
display.blit(cam1, (450, 240))
elif flash == True:
display.blit(light, (70, 60))
else:
display.blit(dark, (80, 55))
pygame.display.update()
clock.tick(30)
##if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
See How do I detect collision in pygame?. A pygame.Surface has no rect attribute. Use get_rect() to get a rectangle with the size of the image and set the position with keyword arguments:
elif event.type == pygame.MOUSEBUTTONDOWN and q == True:
cam1_rect = cam1.get_rect(topleft = (450, 240))
if cam1_rect .collidepoint(event.pos):
print("hi")

How to make music play when pressing the space bar?

I want to create a really simple application that starts a song while you press the SPACE bar, but when I start the application and press the space bar, I just hear a "pop" sound, and nothing starts. No music.
Here is the code:
import pygame
from pygame.locals import *
pygame.init()
backimage = pygame.display.set_mode((395, 702), RESIZABLE)
fond = pygame.image.load("background.jpg").convert()
backimage.blit(fond, (0,0))
pygame.display.flip()
pygame.mixer.pre_init(42000,-16,1,2048)
pygame.mixer.init()
musik = pygame.mixer.Sound(b'musik.wav')
continuer = 1
while continuer == 1:
for event in pygame.event.get():
if event.type == QUIT:
continuer = 0
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_SPACE:
musik.play()
Ok, thank you so much guys ! It works perfectly now.
Here is the final code if someone has the same problem as me:
import pygame
from pygame.locals import *
pygame.init()
backimage = pygame.display.set_mode((395, 702), RESIZABLE)
fond = pygame.image.load("background.jpg").convert()
backimage.blit(fond, (0,0))
pygame.display.flip()
pygame.mixer.init()
pygame.mixer.music.load(b'musik.mp3')
pygame.event.clear()
while True:
event = pygame.event.wait()
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN and event.key == K_SPACE:
pygame.mixer.music.play()
elif event.type == KEYUP and event.key == K_SPACE:
pygame.mixer.music.stop()
I don't know why the code doesn't work, but I know it does work if you use a mp3 file. try this:
import pygame
from pygame.locals import *
pygame.init()
backimage = pygame.display.set_mode((395, 702), RESIZABLE)
fond = pygame.image.load("background.jpg").convert()
backimage.blit(fond, (0,0))
pygame.display.flip()
pygame.mixer.init()
pygame.mixer.music.load(b'musik.mp3')
continuer = 1
while continuer == 1:
for event in pygame.event.get():
if event.type == QUIT:
continuer = 0
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_SPACE:
pygame.mixer.music.play()
If you want to use your .wav file you can find .wav to .mp3 online
I think that you misunderstood the use for pygame.event. You should try with pygame.event.wait() :
pygame.event.clear()
while True:
# wait until new event happens - blocking instruction
event = pygame.event.wait()
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN and event.key = K_SPACE:
musik.play()

Pausing a game using pygame by pressing two keys simultaneously - tamagotchi project

I'm trying to implement a pause function in my tamagotchi clone (I'm practising for my controlled assessment next year) and I can't get the left and up keys to work simultaneously as a pause button. If possible I want to stay as true to the original game as possible so I would prefer not to use on-screen buttons. Thanks!
import pygame
import time
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
size =(200, 200)
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Tama v4.5')
screen.fill(WHITE)
pygame.init()
clock = pygame.time.Clock()
sprites = ['AdultSpriteAAA.png']
up_pressed = False
left_pressed = False
right_pressed = False
def main():
controls()
if up_pressed == True and left_pressed == True:
time.sleep(2)
pause()
player_position = pygame.mouse.get_pos()
x = player_position[0]
y = player_position[1]
screen.blit(background, [0,0])
screen.blit(sprite, [x, y])
pygame.display.flip()
clock.tick(60)
def controls():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
print(animate())
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
global up_pressed
right_pressed = True
if event.key == pygame.K_LEFT:
global left_pressed
left_pressed = True
if event.key == pygame.K_RIGHT:
global right_pressed
right_pressed = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
global up_pressed
right_pressed = False
if event.key == pygame.K_LEFT:
global left_pressed
left_pressed = False
if event.key == pygame.K_RIGHT:
global right_pressed
right_pressed = False
def info():
return 0
def food():
return 1
def toilet():
return 2
def game():
return 3
def connect():
return 4
def talk():
return 5
def medic():
return 6
def post():
return 7
def history():
return 8
def animate():
return 9
def pause():
time.sleep(2)
while True:
controls()
if up_pressed == True and left_pressed == True:
time.sleep(2)
break
sprite = pygame.image.load(sprites[0]).convert()
background = pygame.image.load('Background 200x200.png').convert()
sprite.set_colorkey(BLACK)
while True:
main()
A way to make it pause when both left iey and up key are pressed is this:
import pygame
from pygame.locals import *
#game code
…
def pause():
keyspressed = pygame.keys.get_pressed()
if keyspressed[K_LEFT] and keyspressed[K_UP]:
#pause code
…
This code should be correct, but if you find any weird things, try to research the pygame key module. Keep in note that K_LEFT and K_UP are from pygame.locals, which is imported seperately from pygame
Here is a method that I have found really useful when writing games in PyGame:
if event.type == pygame.KEYDOWN
if event.key == (pygame.K_RIGHT and pygame.K_LEFT):
while True: # Infinite loop that will be broken when the user press the space bar again
event = pygame.event.wait()
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: # decid how to unpause?
break #Exit infinite loop
An interesting tid-bit I only recently discovered is that pygame.key.get_pressed() returns a tuple of 1s and 0s representing all of the keys on the keyboard, and these can be used as booleans or indexed to get the effective "value" of a key. Some great tuts at http://programarcadegames.com/

pygame - Key pressed

I am kinda stuck with a supposed to be simple code to check if the user has pressed "w" or "s".
Below you can see my code:
import pygame
pygame.init()
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_w:
print('Forward')
elif event.type == pygame.KEYDOWN and event.key == pygame.K_s:
print('Backward')
Am I forgetting something here?
Thanks!
A window needs to be created to receive key presses, the following works.
import pygame
import sys
pygame.init()
pygame.display.set_mode((100, 100))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
print('Forward')
elif event.key == pygame.K_s:
print('Backward')
This is what seems to me the most simple and understandable way to do it:
import pygame
pygame.init()
pygame.display.set_mode((300, 300))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
print('Forward')
elif event.key == pygame.K_s:
print('Backward')
Instead of using the sys.exit() method I prefer to just use pygame.quit()
it is no good to ask the gamer to keep hitting w to get the response. If you want to read the "pressed" state. You could consider the followings:
from pygame import *
import time
flag = False # The flag is essential.
DONE = False
screen = display.set_mode((500,500)) # 1180, 216
count=0
while not DONE:
event.pump() # process event queue
keys = key.get_pressed() # It gets the states of all keyboard keys.
#print("%d"%count,keys)
count+=1
if keys[ord('w')]: # And if the key is K_DOWN:
print("%d w down"%count)
if keys[ord('s')]: # And if the key is K_DOWN:
print("%d s down"%count)
time.sleep(0.1)
Try this:
import pygame
pygame.init()
key = pygame.key.get_pressed()
while True:
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == pygame.K_w:
print('Forward')
elif event.type == KEYDOWN and event.key == pygame.K_s:
print('Backward')
Sample code to understand how key press events work.
import pygame
from pygame.locals import *
def main():
pygame.init()
pygame.display.set_caption("Move Box With Arrow Keys")
wndsize = (320, 240)
display = pygame.display.set_mode(wndsize)
x = 5
y = 5
black = (0, 0, 0)
white = (255, 255, 255)
rectpos = (x, y)
rectdim = (50, 50)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
x += 5
print("K_RIGHT")
if event.key == pygame.K_LEFT:
x -= 5
print("K_LEFT")
if event.key == pygame.K_UP:
y -= 5
print("K_UP")
if event.key == pygame.K_DOWN:
y += 5
print("K_DOWN")
# Don't allow coords below 0
if 0 > x:
x = 5
if 0 > y:
y = 5
# Don't allow overflow
if x + rectdim[0] > wndsize[0]:
x = wndsize[0] - rectdim[0] - 5
if y + rectdim[1] > wndsize[1]:
y = wndsize[1] - rectdim[1] - 5
rectpos = (x, y)
display.fill(white)
rect = pygame.draw.rect(display, black, ((rectpos), (rectdim)))
pygame.display.update()
main()
This might work:
from pygame import *
init()
if key.get_pressed()[K_w] == True:
print('Forwards')
if key.get_pressed()[K_s] == True:
print('Backwards')`

Categories