Pygame Creating Sprites While Moving Mouse - position

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

Related

Trying to control the delay by using the keyboard in Pygame

I would like to control delay for my program, now is set to pygame.time.delay(50) as default value, below is my code snippet.
pygame.time.delay(50)
pygame.display.update()
clockobject = pygame.time.Clock()
clockobject.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
quit()
if event.key == pygame.K_1:
print('K_1')
if event.key == pygame.K_2:
print('K_2')
I tried to control it by changing the values.
if event.key == pygame.K_1:
pygame.time.delay(20)
pygame.display.update()
print('K_1')
if event.key == pygame.K_2:
pygame.time.delay(90)
pygame.display.update()
print('K_2')
When i press the keys the print value returns on my terminal but i doesn't slow down or accelerate!
You have to use a variable for the delay:
time_delay = 50
while run:
pygame.time.delay(time_delay)
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
if time_delay > 0:
time_delay -= 10
if event.key == pygame.K_2:
if time_delay < 100:
time_delay += 10
Pygame.time.delay() delays the time your code runs on the window, there is no way that pygame.time.delay() delays your keyboard inputs so what you can do is set a variable to like 20 and then if a user presses a, decrease the variable by 1 and if that variable reaches 0 or below, then do what you want to do.

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
# [...]

pygame keylogger improvement ideas?

I'm currently writing a pygame keylogger based on the pygame event handler.
My old version was based on testing all available keys needed for my application but now, because of a huge loss of processing capacity in the old one, I have based it on retrieving the unprocessed information of the pressed key, searching for its place in the list, and making pygame put out its coherent string.
I have completed the first functional version and am open for some improvement ideas.
special = '''+#-.,´ß0987654321^<'''
konverted = '''*\'_:;`?=)(/&%$§"!°>'''
print(special, konverted)
def key_get():
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
key = pygame.key.get_pressed()
for i in range(0, 253, 1): #empirisch gemessen für 'ü' (letztes bei umlauten)
if key[i]:
name = pygame.key.name(i)
mod = pygame.key.get_mods()
if mod & pygame.KMOD_SHIFT:
if all([str(x) != str(name) for x in special]):
name = name.upper()
elif any([str(y) == str(name) for y in special]):
for y in range(0, len(special), 1):
if str(special[y])== str(name):
name = konverted[y]
elif event.type == pygame.MOUSEBUTTONDOWN:name = "mousebuttondown"
elif event.type == pygame.QUIT:name = False
elif event.type == pygame.VIDEORESIZE:
screen = pygame.display.set_mode(event.dict['size'], pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.RESIZABLE)
pygame.display.flip()
I'm not really sure what you mean for us to do, but is this what you want?
for event in pygame.event.get()
if event.type == pygame.KEYDOWN:
key_name = event.unicode

pygame event keys are not responding even though idle is not showing an error?

import pygame
from pygame import *
pygame.init
pygame.display.init
pygame.display.set_caption("Test")
bg = pygame.image.load("bg.jpg")
human = pygame.image.load("human1.bmp")
display_screen = pygame.display.set_mode((1000,500))
keyboard_input = 0
clock = pygame.time.Clock()
def screen_Quit():
running = False
while not running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
keyboard_input = (90)
print("Left arrow key has been pressed.")
if event.key == pygame.K_RIGHT:
keyboard_input = (-90)
print("Right arrow key has been pressed.")
if event.key == pygame.K_UP:
keyboard_input = (20)
print("Up arrow key has been pressed.")
if event.key == pygame.K_DOWN:
keyboard_input = (-20)
print("Down arrow key has been pressed.")
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
keyboard_input = (0)
print("Left arrow key has been released.")
if event.key == pygame.K_RIGHT:
keyboard_input = (0)
print("Right arrow key has been released.")
if event.key == pygame.K_UP:
keyboard_input = (0)
print("Up arrow key has been released.")
if event.key == pygame.K_DOWN:
keyboard_input = (0)
print("Down arrow key has been released.")
# this code here has been left for later --> print(event)
display_screen.blit(bg, [0,0])
display_screen.blit(human, [50,87])
pygame.display.update()
clock.tick(60)
screen_Quit()
pygame.quit
quit()
I don't understand the problem, I have posted my full code as the problem might be something else. The problem I've been having with the program is the event keys in python it's not responding to the input which is the keyboard I'm using pygame to create a game but cannot understand why the event keys are not working. I have checked everywhere and cannot understand. The code seems fine to me, python idle is not giving any errors I'm even getting input in the idle but the character doesn't move there should be no reason for it not to move.
Here is a picture and a link to a video that goes more in depth into the problem (I created the video myself):
an image of the problem
Link to video:
https://www.youtube.com/watch?v=QVFaiuF9KY8&feature=youtu.be
Video will most likely be more useful than image.
Short Answer
Your code doesn't have any commands that tell the image to move. I fixed this and posted the full working code at the bottom. If you want a more in depth explanation, read on.
Explanation
If that is your full code, then the problem is that first of all you don't even have any code in the first place that tells the character to move. And second of all your pygame.display.update() is outside the while loop, so any changes made to the screen don't show.
For every event you just told python to print a message:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
keyboard_input = (90)
print("Left arrow key has been pressed.")
What you want to do is add another line there to actually move the character.
This can be done by changing it's x and y position. I recommend using sprites for this, but for now since you are using an image, we'll just stick to that.
To change the position of an image you have to run a new window.blit() with the desired (x,y). This means that you will have to constantly iterate this if you're going to need to move it around a lot, so it's better to put it INSIDE the running while loop. So bring this part of your code on indentation forward:
display_screen.blit(bg, [0,0])
display_screen.blit(human, [50,87])
pygame.display.update()
clock.tick(60)
screen_Quit()
pygame.quit
quit()
So now the screen get's regularly updated. The second thing you want to do is create 2 new variables x and yand change
display_screen.blit(human, [50,87])
to
display_screen.blit(human, [x,y])
This basically means that you character now gets blitted to the screen at the position YOU choose, not at a fixed position that doesn't change. So now you can add + to the x position whenever the left key is clicked, or - from the x position whenever the right key is clicked!
Here is the full working code:
import pygame
from pygame import *
pygame.init
pygame.display.init
pygame.display.set_caption("Test")
bg = pygame.image.load("bg.jpg")
human = pygame.image.load("human1.bmp")
display_screen = pygame.display.set_mode((1000,500))
keyboard_input = 0
clock = pygame.time.Clock()
running = False
x=0
y=0
moving = "none"
white = (255,255,255)
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_LEFT:
moving = "left"
print("Left arrow key has been pressed.")
elif event.key == pygame.K_RIGHT:
moving = "right"
print("Right arrow key has been pressed.")
elif event.key == pygame.K_UP:
moving = "up"
print("Up arrow key has been pressed.")
elif event.key == pygame.K_DOWN:
moving = "down"
print("Down arrow key has been pressed.")
else:
moving = "hello"
if moving == "left":
x -= 5
if moving == "right":
x += 5
if moving == "up":
y -= 5
if moving == "down":
y += 5
# this code here has been left for later --> print(event)
display_screen.blit(bg,[0,0])
display_screen.blit(human, [x,y])
clock.tick(60)
pygame.display.update()
You never update the position of your player and just blit it at [50,87]. If you want it to move, you first have to store the position, e.g. player_pos = [50, 87] and define variables for the velocity velocity_x = 0, then set the velocity in the event loop if a key gets pressed:
if event.key == pygame.K_RIGHT:
velocity_x = 5
and update the position in the while loop:
player_pos[0] += velocity_x
player_pos[1] += velocity_y

I want to move an image on screen while holding down a key. How can i get it?

I made this thinking that it would works, but it doesn't XD
it only moves the image one time per click
Help me please
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
while event.type == pygame.KEYDOWN:
right == K_RIGHT
left == K_LEFT
if right == 1
posX += velocidad
elif lef == 1:
posX -= velocidad
I think you want to used pygame.key.get_pressed() as follows.
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pressed_keys = pygame.key.get_pressed()
if pressed_keys[K_RIGHT]:
posX += velocidad
if pressed_keys[K_LEFT]:
posX -= velocidad
event.type == pygame.KEYDOWN only catches when a key is first pressed down.
If you want to use this you could switch some attribute like your_object.moving_right = True. Then use keyup to turn it off again.
Overall, I think what you want is to check event.key with an if statement.
However there are multiple problems (both structural and syntactic) with your code. event.type doesn't change, so using while doesn't make sense (and this will run forever and make your program hang). I'm not sure what your intent is with the == 1 comparisons, as K_RIGHT and K_LEFT are arbitrary constants for key code values. Not to mention that right == K_RIGHT is an expression that does nothing (did you mean right = K_RIGHT?) and you've got a clear typo with lef. I think the closest working code to the structure you've provided (assuming the other code not shown also works) would look something like this:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
right = K_RIGHT
left = K_LEFT
if event.key == right:
posX += velocidad
elif event.key == left:
posX -= velocidad

Resources