def walk():
x = 0
y = 0
dist = 5
frame = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
key = pygame.key.get_pressed()
if key[pygame.K_UP]:
x = x - 5
This is part of some code to make my sprite move. But it tried to get it to print it while i was pressing the button for some reason it only print "yay" once until i press the key again. Someone please help.
You have to dedent the line key = pygame.key.get_pressed(): and the two lines below. They are executed only once per event in the event queue because they are in the event loop (for event in pygame.event.get():), but they should be executed in the while loop every frame.
def walk():
x = 0
y = 0
dist = 5
frame = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
key = pygame.key.get_pressed()
if key[pygame.K_UP]:
x = x - 5
Related
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'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
I'm creating a game with pygame for my CompSci course. The game is working well, but now I'm trying to make a restart function and I'm getting alot of errors.
The basic outline of what I'm trying to do is:
first = True
def check(count):
if count == 1000:
return True
else:
return False
def start():
# MAIN MENU
print ("start")
count = 0
while True:
count += 1
if check(count) == True:
Game()
def Game():
count = 0
print("Game")
while True:
# GAMELOOP
count += 1
if check(count) == True:
restart()
def restart():
count = 0
print ("Restart")
while True:
# RESTART
count += 1
if check(count) == True:
start()
if first == True:
first = False
start()
However, whenever I run this, python ultimately crashes with:
RecursionError: maximum recursion depth exceeded while calling a Python object
I'm not sure about how to get around this. I was hoping that someone could suggest another method to do the same thing or something that I've done wrong.
The actual restart and menu functions:
def rest(): #Main Menu
while True:
pygame.display.update()
menu.draw()
if pygame.mouse.get_pressed()[0]:
x, y = pygame.mouse.get_pos()
if x >= 255 and x <= 355 and y >= 400 and y <= 450:
game()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
def game(): #Gameloop
while True:
if bottom.time == 0 or bottom.time < 0 :
game_screen.fill((0, 0, 0))
restart()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
def restart():
while True:
pygame.display.update()
menu.restart()
if pygame.mouse.get_pressed()[0]:
x, y = pygame.mouse.get_pos()
if x >= 255 and x <= 355 and y >= 400 and y <= 450:
game_screen.fill((0, 0, 0))
rest()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
Do you have a sequence of functions calling each other creating a indirect recursion.
start() counts to 1000 and then calls Game(), which counts to 1000 again and then calls restart(), whichs also counts to 1000 an then calls start(), closing the recursion loop. Once you do not have a stop condition, your recursion goes until reach the depth limit of python's recursion stack, then you get the exception.
As solution, you need to create a stop condition inside of one those functions.
Edit
I don't know pygame exactly but, as far as I get from the additional code, to the for in rest() function (which checks the events) be executed, it needs that the game() function returns, which are never happening. You can test this hyphotesis printing something just in the line before the for line. Same applies to the restart function.
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 have the following code:
while OS_ON:
for event in pygame.event.get():
if event.type == pygame.QUIT:
OS_ON = False
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
if x > 63 and x < 143 and y > 298 and y < 378:
Calculator = True
while Calculator:
for event in pygame.event.get():
if event.type == pygame.QUIT:
OS_ON = False
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
if x > 180 and x < 218 and y > 670 and y < 708:
Calculator = False
In my first loop the for event in pygame.event.get(): works but when I use it again in my second loop I does not work anymore. Do you know how to fix it so it works in booth loops.
In python 3.x, pygame.event.get() was made a generator, so once you retrieve a value from it, it's gone for good. You can try saving its content into a list first:
while OS_ON:
events = list(pygame.event.get())
for event in events:
if event.type == pygame.QUIT:
OS_ON = False
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
if x > 63 and x < 143 and y > 298 and y < 378:
Calculator = True
while Calculator:
for event2 in events: # 'event' is used in the outer loop
if event2.type == pygame.QUIT:
OS_ON = False
if event2.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
if x > 180 and x < 218 and y > 670 and y < 708:
Calculator = False
But if you really need to do something like this, then you really need to redesign your code such that it makes use of only one pygame.event.get() every frame.