creating a simple key press checker in python using pygame - keyboard

I'm making a messenger application in python using pygame for the gui. I'm trying to detect key presses but the code I'm using is a large amount and i don't like it, i was wondering if there is a better way of checking which keys where pressed then sending that to a string variable.
My code:
##------>>>__ Letters __<<<------##
if event.key == pygame.K_q:
self.CharKeyPressed = "q"
if event.key == pygame.K_w:
self.CharKeyPressed = "w"
if event.key == pygame.K_e:
self.CharKeyPressed = "e"
if event.key == pygame.K_r:
self.CharKeyPressed = "r"
if event.key == pygame.K_t:
self.CharKeyPressed = "t"
if event.key == pygame.K_y:
self.CharKeyPressed = "y"
if event.key == pygame.K_u:
self.CharKeyPressed = "u"
if event.key == pygame.K_i:
self.CharKeyPressed = "i"
if event.key == pygame.K_o:
self.CharKeyPressed = "o"
if event.key == pygame.K_p:
self.CharKeyPressed = "p"
if event.key == pygame.K_a:
self.CharKeyPressed = "a"
if event.key == pygame.K_s:
self.CharKeyPressed = "s"
if event.key == pygame.K_d:
self.CharKeyPressed = "d"
if event.key == pygame.K_f:
self.CharKeyPressed = "f"
if event.key == pygame.K_g:
self.CharKeyPressed = "g"
if event.key == pygame.K_h:
self.CharKeyPressed = "h"
if event.key == pygame.K_j:
self.CharKeyPressed = "j"
if event.key == pygame.K_k:
self.CharKeyPressed = "k"
if event.key == pygame.K_l:
self.CharKeyPressed = "l"
if event.key == pygame.K_z:
self.CharKeyPressed = "z"
if event.key == pygame.K_x:
self.CharKeyPressed = "x"
if event.key == pygame.K_c:
self.CharKeyPressed = "c"
if event.key == pygame.K_v:
self.CharKeyPressed = "v"
if event.key == pygame.K_b:
self.CharKeyPressed = "b"
if event.key == pygame.K_n:
self.CharKeyPressed = "n"
if event.key == pygame.K_m:
self.CharKeyPressed = "m"
##------>>>__ Numbers __<<<------##
if event.key == pygame.K_1:
if self.BlnShift:
self.CharKeyPressed = "!"
else:
self.CharKeyPressed = "1"
if event.key == pygame.K_2:
if self.BlnShift:
self.CharKeyPressed = '"'
else:
self.CharKeyPressed = "2"
if event.key == pygame.K_3:
if self.BlnShift:
self.CharKeyPressed = "£"
else:
self.CharKeyPressed = "3"
if event.key == pygame.K_4:
if self.BlnShift:
self.CharKeyPressed = "$"
else:
self.CharKeyPressed = "4"
if event.key == pygame.K_5:
if self.BlnShift:
self.CharKeyPressed = "%"
else:
self.CharKeyPressed = "5"
if event.key == pygame.K_6:
if self.BlnShift:
self.CharKeyPressed = "^"
else:
self.CharKeyPressed = "6"
if event.key == pygame.K_7:
if self.BlnShift:
self.CharKeyPressed = "&"
else:
self.CharKeyPressed = "7"
if event.key == pygame.K_8:
if self.BlnShift:
self.CharKeyPressed = "*"
else:
self.CharKeyPressed = "8"
if event.key == pygame.K_9:
if self.BlnShift:
self.CharKeyPressed = "("
else:
self.CharKeyPressed = "9"
if event.key == pygame.K_0:
if self.BlnShift:
self.CharKeyPressed = ")"
else:
self.CharKeyPressed = "0"
##------>>>__ Specials __<<<------##
if event.key == pygame.K_SPACE:
self.CharKeyPressed = " "
if event.key == pygame.K_PERIOD:
if self.BlnShift:
self.CharKeyPressed = "#"
else:
self.CharKeyPressed = ". "
if event.key == pygame.K_COMMA:
if self.BlnShift:
self.CharKeyPressed = "'"
else:
self.CharKeyPressed = ", "
if event.key == pygame.K_SLASH:
self.CharKeyPressed = "/"
if event.key == pygame.K_SEMICOLON:
if self.BlnShift:
self.CharKeyPressed = ":"
else:
self.CharKeyPressed = ";"

For most cases, you can simply use the unicode attribute of the KEYDOWN event:
self.CharKeyPressed = event.unicode

Related

how can I edit a sudoku grid in pygame using mouse and keyboard detection?

I want to insert values on the sudoku grid, using pygame, editing an internal matrix. If the user clicks an empty cell, I want them to be able to choose a keyboard number and the internal matrix would be updated, with this number in the respective cell. For now, my loop code looks like this:
while custom:
pygame.display.flip()
screen.blit(bgCustom, (0, 0))
for event in pygame.event.get():
if (event.type == pygame.MOUSEBUTTONDOWN):
setGrid(board)
and setGrid looks like this:
def setGrid(board):
position = pygame.mouse.get_pos()
x = position[0]
y = position[1]
#print(y, x)
line = x // 92
col = y // 80
#print(col, line)
#print(board)
for event in pygame.event.get():
if event.type == pygame.KEYUP :
if event.key == pygame.K_1:
board[line][col] = 1
print(board)
elif event.key == pygame.K_2:
board[line][col] = 2
elif event.key == pygame.K_3:
board[line][col] = 3
elif event.key == pygame.K_4:
board[line][col] = 4
elif event.key == pygame.K_5:
board[line][col] = 5
elif event.key == pygame.K_6:
board[line][col] = 6
elif event.key == pygame.K_7:
board[line][col] = 7
elif event.key == pygame.K_8:
board[line][col] = 8
elif event.key == pygame.K_9:
board[line][col] = 9
There is no syntax error, but the board remains uneditaded. My guess is that, when the user activates setGrid, the computer immediately tries to detect keyboard input, but the user is not "fast enough" to make the function work. I thought about making some kind of wait function, to wait for keyboard input, but I don't want the user to get stuck in setGrid. Any thoughts?
Thanks in advance
You have to set a variable (clicked_cell) which is initialized by None. Assign a tuple with the line and column to the cell when it is clicked. Reset the variable after the button was pressed:
clicked_cell = None
while custom:
# [...]
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
line = event.pos[0] // 92
col = event.pos[1] // 80
clicked_cell = (line, col)
if event.type == pygame.KEYUP:
if clicked_cell != None:
if pygame.K_1 <= event.key <= pygame.K_9:
line, col = clicked_cell
clicked_cell = None
number = int(event.unicode)
board[line][col] = number
# [...]

I made a game where blocks fall and you have to dodge it but can't get the hitboxes right

The hitbox seems to be on the left side of the cube, so it feels like the game is ending without me even hitting anything. I want to make it that the hitbox is exactly on the red rectangle, so that it's obvious that the black rectangle had hit you.
the up and down controls are just for future movement option if needed.
here's the code
import pygame as pg,pygame
import random
import sys
pygame.init()
WIDTH = 1000
HEIGHT = 800
# Positions, sizes
SPEED = 10
MIDDLE = [500, 400]
score = 0
player_size = 90
player_pos = [WIDTH/2, HEIGHT-2*player_size]
playerX_move = 0
playerY_move = 0
enemy_size = 50
enemy_pos = [random.randint(0,WIDTH - enemy_size), 30]
enemy_list = [enemy_pos]
# Colors
WHITE = [255, 255, 255]
GREY = [25, 25, 25]
BLUE = [65,105,225]
BLACK = [0,0,0]
GREEN = [65,255,105]
RED = [255,0,0]
# -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
screen = pygame.display.set_mode((WIDTH,HEIGHT))
game_over = False
clock = pygame.time.Clock()
def drop_enemies(enemy_list):
delay = random.random()
if len(enemy_list) < 10 and delay < 0.1:
x_pos = random.randint(0,WIDTH-enemy_size)
y_pos = 30
enemy_list.append([x_pos, y_pos])
def draw_enemies(enemy_list):
for enemy_pos in enemy_list:
pygame.draw.rect(screen,BLACK, (enemy_pos[0], enemy_pos[1], enemy_size, enemy_size))
def update_enemy_positions(enemy_list, score):
for idx, enemy_pos in enumerate(enemy_list):
if enemy_pos[1] >= 0 and enemy_pos[1] < HEIGHT:
enemy_pos[1] += SPEED
else:
enemy_list.pop(idx)
score += 1
return score
def collision_check(enemy_list, player_pos):
for enemy_pos in enemy_list:
if detect_collision(enemy_pos, player_pos):
return True
return False
def detect_collision(player_pos, enemy_pos):
p_x = player_pos[0]
p_y = player_pos[1]
e_x = enemy_pos[0]
e_y = enemy_pos[1]
if (e_x >= p_x and e_x < (p_x + player_size)) or (p_x >= e_x and p_x < (e_x+enemy_size)):
if (e_y >= p_y and e_y < (p_y + player_size)) or (p_y >= e_y and p_y < (e_y+enemy_size)):
return True
return False
while not game_over:
player_pos[0] += playerX_move
player_pos[1] += playerY_move
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_move = -5
if event.key == pygame.K_RIGHT:
playerX_move = 5
# if event.key == pygame.K_UP:
# playerY_move = -5
# if event.key == pygame.K_DOWN:
# playerY_move = 5
if event.key == pygame.K_a:
playerX_move = -15
if event.key == pygame.K_d:
playerX_move = 15
# if event.key == pygame.K_w:
# playerY_move = -15
# if event.key == pygame.K_s:
# playerY_move = 15
if event.key == pg.K_SPACE:
print("SPACE")
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d or event.key == pygame.K_s or event.key == pygame.K_w:
playerX_move = 0
playerY_move = 0
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_DOWN or event.key == pygame.K_UP:
playerX_move = 0
playerY_move = 0
screen.fill(BLACK)
drop_enemies(enemy_list)
score = update_enemy_positions(enemy_list,score)
if collision_check(enemy_list, player_pos):
game_over = True
draw_enemies(enemy_list)
pygame.draw.rect(screen, RED, (player_pos[0], player_pos[1], 90, 90))
clock.tick(30)
pygame.display.update()
I would recommend using a list of pygame.Rects instead of a List with the positions of your enemies. This would also allow you to use pygame.Rect.colliderect() instead of your detect_collision function.
I've also linked the Pygame Docs.

Displaying output after adding item to list

This is my code:
import time,sys,random
wpm = 125
userName = ""
global mirror
mirror = False
global knife
knife = False
inventory = []
vial = False
trollHit = 0
playerHit = 0
axe = False
choice2 = False
kitchenAlready = False
def death():
sys.exit()
userInput = ""
def cantPerformAction(userInput):
if userInput == "e" or userInput == "u" or userInput == "w" or userInput == "s" or "t" in userInput:
slow_type("You can't perform that action.")
def checkDirection(userInput):
if any(char in userInput for char in 'nsewudt') == False:
return False
elif any(char in userInput for char in 'nsewudt') == True:
return True
#credit to 'bill gross' for ideas on the slow type
def slow_type(y): #slow typing to make it seem like the computer is typing
for x in y:
sys.stdout.write(x)
sys.stdout.flush()
time.sleep(random.random( )*10.0/wpm)
print (' ')
def clear(): #clear the line so that another line of text can appear below it
print ("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
#CROSSROADS: All directions lead to death except right. Player cannot turn back.
def crossroads():
slow_type("\n\nCrossroads")
slow_type("\n\nA crossroads is in front of you. There is a passage to the west, east, and north.")
global choice2
global choice
choice = None
choice2 = None
youBetterChoose = 0
while choice == None and choice2 == None:
userInput = input("\n>")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input("\n>")
checkDirection(userInput)
userInput1 = userInput.lower().strip()
if userInput1 == "s":
clearingalready()
if userInput1 =="n":
slow_type("\n>You walk forward, determined... off a cliff. Tragic!")
death()
if userInput1 == "w":
slow_type("\nYou encounter a giant spider. Without a weapon, it easily tears you to shreds.")
death()
if userInput1 == "e":
fork()
if userInput1 == "d":
slow_type("You can't do down farther than the floor.")
if userInput1 == "u":
slow_type("You can't go that way.")
userInput = ""
def crossroadsalready():
slow_type("\n\nCrossroads")
global choice2
global choice
choice = None
choice2 = None
youBetterChoose = 0
while choice == None and choice2 == None:
userInput = input("\n>")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input("\n>")
checkDirection(userInput)
userInput1 = userInput.lower().strip()
if userInput1 == "s":
clearingalready()
if userInput1 =="n":
slow_type("\n>You walk forward, determined... off a cliff. Tragic!")
death()
if userInput1 == "w":
slow_type("\nYou encounter a giant spider. Without a weapon, it easily tears you to shreds.")
death()
if userInput1 == "e":
fork()
if userInput1 == "d":
slow_type("You can't do down farther than the floor.")
if userInput1 == "u":
slow_type("You can't go that way.")
userInput = ""
def fork():
choice2 = False
slow_type("\nFork")
slow_type("\nThere are another two ways to go. One goes north into a cavern, another leads down deeper into the earth.\n\n")
deeperOrFarther = ""
while choice2 == False:
userInput = input(">")
checkDirection(userInput)
if checkDirection(userInput) == False:
while checkDirection(userInput) == False:
userInput = input (">")
checkDirection(userInput)
deepLower = userInput.lower().strip()
if deepLower == "n":
slow_type("You walk forward, determined... off a cliff. Tragic!")
choice2 = True
death()
if deepLower == "d":
slow_type("You descend down into the darker regions of the cave.")
choice2 = True
if deepLower == "w":
crossroadsalready()
cantPerformAction(deepLower)
houseChoice()
wpm = 60
slow_type("Welcome to Zotan! \nn = north \ns = south \nw = west \ne = east \nu = up \nd = down \nt = take")
clear()
wpm = 120
def clearing():
slow_type("Clearing\n")
slow_type("You wake up in the middle of a clearing. There is a passage to the north.")
slow_type("\n\n")
clearingalready = True
choice = None
while choice == None:
userInput = input("\n>")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input("\n>")
checkDirection(userInput)
userInput = userInput.lower()
if userInput.strip() == "n":
choice = False
else:
slow_type("You can't go that way.")
userInput = ""
crossroads() #1
def clearingalready():
slow_type("Clearing\n")
slow_type("There is a passage to the north.")
slow_type("\n\n")
choice = None
while choice == None:
userInput = input("\n>")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input("\n>")
checkDirection(userInput)
userInput = userInput.lower()
if userInput.strip() == "n":
choice = False
else:
slow_type("You can't go that way.")
userInput = ""
crossroads() #1
def houseChoice():
slow_type("\n\n\n\nHouse Doorway\n\n")
choice = None
while choice == None:
userInput = input(">")
checkDirection(userInput)
if checkDirection(userInput) == False:
while checkDirection(userInput) == False:
userInput = input(">")
checkDirection(userInput)
userInput = userInput.lower().strip()
if userInput == "d" or userInput == "u" or userInput == "w" or userInput == "e":
slow_type("You can't go that way.")
if userInput == "n":
choice = False
if userInput == "s":
choice = False
if userInput == "s":
fork()
elif userInput == "n":
entryway()
def entryway():
slow_type("\nEntryway")
slow_type("\n\nThere is a kitchen to the west and a dark staircase. A back door hangs open in the north, revealing the entry into another dark corridor.")
userInput = input("\n>")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input("\n>")
checkDirection(userInput)
userInput = userInput.lower().strip()
if userInput == "w":
kitchen()
if userInput == "u":
attic()
if userInput == "n":
chasm()#4
if userInput == "s":
houseChoice()
def entrywayalready():
slow_type("\nEntryway")
userInput = input("\n>")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input("\n>")
checkDirection(userInput)
userInput = userInput.lower().strip()
if userInput == "w":
if kitchenAlready == False:
kitchen()
elif kitchenAlready == True:
kitchenalready()
if userInput == "u":
attic()
if userInput == "n":
chasm()#4
def kitchen():
kitchenAlready = True
slow_type("\n\nKitchen")
slow_type("It seems that the kitchen has been used recently. There is a wicked looking steak knife on the counter, and a mirror on the table.")
userInput = input("\n>")
userInput = userInput.lower().strip()
if userInput == "t knife":
if "knife" not in inventory:
slow_type("Taken.")
inventory.append("knife")
elif "knife" in inventory:
slow_type("You can't take that item.")
elif userInput == "t mirror":
if "mirror" not in inventory:
inventory.append("mirror")
elif "mirror" in inventory:
slow_type("You can't take that item.")
slow_type("You can't perform that action.")
elif userInput == "e":
entrywayalready()
def kitchenalready():
slow_type("\n\nKitchen")
userInput = input("\n>")
userInput = userInput.lower().strip()
if "knife" not in inventory:
inventory.append("knife")
elif "knife" in inventory:
slow_type("You can't take that item.")
if userInput == "t mirror":
if "mirror" not in inventory:
inventory.append("mirror")
elif "mirror" in inventory:
slow_type("You can't take that item.")
if userInput == "e":
entrywayalready()
def attic():
slow_type("\n\nAttic")
choice = None
while choice == None:
userInput = input(">")
if checkDirection(userInput) == False:
while checkDirection == False:
userInput = input(">")
checkDirection(userInput)
userInput = userInput.lower().strip()
if userInput == "n" or userInput == "s" or userInput == "e" or userInput == "w" or userInput == "u":
slow_type("You can't go that way")
if userInput == "t vial":
if "vial" not in inventory:
slow_type("Taken.")
inventory.append("vial")
elif "vial" in inventory:
slow_type("You can't take that item.")
if userInput == "d":
choice = False
entryway()#6
def chasm():
slow_type("\n\nChasm")
slow_type("\nThere is a chasm in front of you, with a rickety wooden bridge crossing the wide and endlessly deep ravine to the north, and a small passage to the west.")
userInput = input(">")
checkDirection(userInput)
if checkDirection(userInput) == False:
while checkDirection(userInput) == False:
userInput = input (">")
checkDirection(userInput)
chasmChoice = userInput.lower().strip()
if chasmChoice == "n":
slow_type("You cross the wooden bridge and it crumbles behind you. There is no turning back.")
cavern()
if chasmChoice == "w":
smallPassage()
if chasmChoice == "s":
entryway()#7
def smallPassage():
slow_type("\n\nSmall Passage")
slow_type("\nThere is a room to the west.")
userInput = input(">")
checkDirection(userInput)
if checkDirection(userInput) == False:
while checkDirection(userInput) == False:
userInput = input (">")
checkDirection(userInput)
userInputLower = userInput.lower().strip()
if userInputLower == "w":
trollRoom()
if userInputLower == "e":
chasm()
if userInputLower == "s" or userInputLower == "n" or userInputLower == "u" or userInputLower == "d" or userInputLower == "t":
slow_type("You can't perform that action.")#8
def trollRoom():
slow_type("\n\nTroll Room")
slow_type("\nThere is a troll in the room with a large blood stained axe.")
lowerr = "l"
while lowerr != "e":
userInput = input(">")
lowerr = userInput.lower().strip()
if lowerr == "attack troll":
if "knife" in inventory:
xRan = random.randint(0,3)
if xRan == "3":
slow_type("The troll parries your attack.")
if xRan == "2":
slow_type("You get a clear hit on the troll. It groans loudly, displaying a look of deep hatred on it's deformed face.")
trollHit = trollHit + 1
if trollHit == 2:
slow_type("The troll falls to the floor, dead. Its axe lays on the floor.")
axe = True
if userInput != "t axe" or userInput != "e":
slow_type("You can't perform that action.")
if xRan == 3:
if playerHit == 0:
slow_type("The troll knocks you back.")
if playerHit == 1:
slow_type("The troll lands a clean graze on your shoulder. You cry out in pain.")
if lowerr == "t axe":
if axe == True:
slow_type("Taken.")
inventory.append("axe")
elif axe != True:
slow_type("There is no axe there.")
if lowerr == "n" or lowerr == "s" or lowerr == "d" or lowerr == "u" or lowerr == "t" or lowerr == "w":
slow_type("You cannot perform that action.")#9
clearingAlready = False #Determines whether or not the player has already been to the crossroads.
clearing()
crossroads()
fork()
When I execute this particular part of the code It seems like there is no ouput from the computer, no Taken. or You can't perform that action. I can't seem to pinpoint the exact cause of the error or why it is misbehaving.
Console output:
House Doorway
>n
Entryway
>w
Kitchen
>t knife
output: nothing

Pygame - Unknown error in a multiplayer control function

I am making a two player game in which two players can move simultaneously throughout.
The while loop goes like this:
while stop==0:
for event in pygame.event.get():
if event.type == pygame.QUIT:
stop = 1
#For player 1
#on pressing an arrow key
# xv, yv = velocity at which the object moves
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xv = -1
elif event.key == pygame.K_RIGHT:
xv = 1
elif event.key == pygame.K_UP:
yv = -1
elif event.key == pygame.K_DOWN:
yv = 1
# on releasing an arrow key
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
xv = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
yv = 0
#For player 2
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
xv2 = -1
elif event.key == pygame.K_d:
xv2 = 1
elif event.key == pygame.K_w:
yv2 = -1
elif event.key == pygame.K_s:
yv2 = 1
# on releasing an arrow key
elif event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
xv2 = 0
elif event.key == pygame.K_w or event.key == pygame.K_s:
yv2 = 0
Using the above code, only player 1 was able to move while player 2 remained still.
but after modifying the code like this it worked,
while stop==0:
for event in pygame.event.get():
if event.type == pygame.QUIT:
stop = 1
#For player 1
#on pressing an arrow key
# xv, yv = velocity at which the object moves
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xv = -1
elif event.key == pygame.K_RIGHT:
xv = 1
elif event.key == pygame.K_UP:
yv = -1
elif event.key == pygame.K_DOWN:
yv = 1
# on releasing an arrow key
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
xv = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
yv = 0
#For player 2
if event.type == pygame.QUIT:
stop = 1
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
xv2 = -1
elif event.key == pygame.K_d:
xv2 = 1
elif event.key == pygame.K_w:
yv2 = -1
elif event.key == pygame.K_s:
yv2 = 1
# on releasing an arrow key
elif event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
xv2 = 0
elif event.key == pygame.K_w or event.key == pygame.K_s:
yv2 = 0
The only change made was inserting
if event.type == pygame.QUIT:
stop = 1
before the elif statement of player 2. Can anyone help with this confusion?
You have
if event.type == pygame.QUIT:
elif event.type == pygame.KEYDOWN:
# player1
elif event.type == pygame.KEYUP:
elif event.type == pygame.KEYDOWN: # <-- this will never checked
# player2
Second pygame.KEYDOWN will be never use because first pygame.KEYDOWN catchs all KEYDOWN events.
You need only one pygame.KEYDOWN
if event.type == pygame.QUIT:
elif event.type == pygame.KEYDOWN:
# player1
# player2
elif event.type == pygame.KEYUP:
# player1
# player2
or you have to use two if
if event.type == pygame.QUIT:
elif event.type == pygame.KEYDOWN:
# player1
elif event.type == pygame.KEYUP:
# player1
if event.type == pygame.KEYDOWN:
# player2
elif event.type == pygame.KEYUP:
# player2
BTW. when you will use Classes then you will have two objects with own method to check events
if event.type == pygame.QUIT:
# quit
player1.handle_event(event)
player2.handle_event(event)
and every player will have own
def handle_event(self, event)
if event.type == pygame.KEYDOWN:
# do something
elif event.type == pygame.KEYUP:
# do something

Pygame Creating Sprites While Moving Mouse

So, I'm working on a basic Pygame and one of the mechanics is having a bullet sprite follow the mouse and explode. But I'm having just two bugs.
BUG 1: Removing the bullets removes all bullets in bullet_list. I understand why this happens but I don't know how to correct it. Solved
BUG 2: Moving the mouse seems to override the detection of key presses. You cannot move or shoot bullets while moving the mouse.
Update
#Checking Keys
for event in pygame.event.get():
print("CAKE")
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
pPlayer.image = pDown
pPlayer.chy = 2
elif event.key == pygame.K_UP:
pPlayer.image = pUp
pPlayer.chy = -2
elif event.key == pygame.K_LEFT:
pPlayer.image = pLeft
pPlayer.chx = -2
elif event.key == pygame.K_RIGHT:
pPlayer.image = pRight
pPlayer.chx = 2
elif event.key == pygame.K_SPACE:
if pPlayer.canFire == True:
bullet = Bullet()
bullet.rect.x = int(player.x)
bullet.rect.y = int(player.y)
all_sprites_list.add(bullet)
bullet_list.add(bullet)
pPlayer.canFire = False
elif event.key == pygame.K_ESCAPE:
if gameState.togglePause == True:
if gameState.pause == True:
gameState.game = True
gameState.pause = False
elif gameState.pause == False:
gameState.game = False
gameState.pause = True
gameState.togglePause = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
pPlayer.chy = 0
elif event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
pPlayer.chx = 0
elif event.key == pygame.K_SPACE:
pPlayer.canFire = True
elif event.key == pygame.K_ESCAPE:
gameState.togglePause = True
else:
pPlayer.chx = 0
pPlayer.chy = 0
New Bug! I'm unfamiliar with pygame.event.get() and I'm probably doing something wrong here but the examples provided by the pygame docs don't quite help. I can't tell if it has fixed the handling of multiple events because it doesn't seem to even register them. The code prints out "cake" rarely and very delayed and very seldom do any bullets fire when I hit space.
I don't know how well this answer applies because your code is only a sample, but I'll do my best.
Bug 1: For if dist < 30, dist is not updating because you're calculating it in a different for-loop. From your sample, it looks like you can just include the kill check at the end of the first "for bullet in bullet_list" loop.
Bug 2: You're only checking for one event per step, so when multiple events happen (ie mouse motion and a keypress) you only handle on of them. To fix this, iterate through a list of all events:
for event in pygame.event.get():
#Your "Checking Keys" code goes here

Resources