Pygame movement causes the object to duplicate [duplicate] - python

This question already has answers here:
How can I move the ball instead of leaving a trail all over the screen in pygame?
(1 answer)
How can I make a sprite move when key is held down
(6 answers)
Closed 4 months ago.
So i programmed a block which should move in pygame
But when i press any of the movement buttons it doesnt move the block it just duplicates it and moves it and the old square doesnt do anything
Yeah im probably really retarded and the answer is really obviousä
here is the script:
import pygame
from sys import exit
pygame.init()
width=800
height=800
screen = pygame.display.set_mode((width,height))
posy=500
posx=500
clock = pygame.time.Clock()
pygame.display.set_caption("Block")
while True:
for event in pygame.event.get():
pygame.draw.rect(screen, "red", pygame.Rect(posy, posx, 60, 60))
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
posx=posx-10
elif event.key == pygame.K_s:
posx=posx+10
elif event.key == pygame.K_a:
posy=posy-10
elif event.key == pygame.K_d:
posy=posy+10
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(exit()))
pygame.display.update()
clock.tick(60)

It looks like you're creating a new object every time, so you need to adjust your code like this:
rect = pygame.Rect(posy, posx, 60, 60)
for event in pygame.event.get():
pygame.draw.rect(screen, "red", rect)
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
rect.move_ip(0, -10)
elif event.key == pygame.K_s:
rect.move_ip(0, 10)
elif event.key == pygame.K_a:
rect.move_ip(-10, 0)
elif event.key == pygame.K_d:
rect.move_ip(10, 0)

Related

Pygame Key Board Input [duplicate]

This question already has answers here:
How can I make a sprite move when key is held down
(6 answers)
How to get keyboard input in pygame?
(11 answers)
Closed 8 months ago.
I have the following code for an application I am developing in pygame. When I click the down key or any key for that matter, "here" is not being printed. The code is as follows:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
print("here")
if event.key == pygame.K_DOWN:
player_speed += 7
if event.key == pygame.K_UP:
player_speed -= 7
if event.type == pygame.KEYUP:
print("here")
if event.key == pygame.K_DOWN:
player_speed -= 7
if event.key == pygame.K_UP:
player_speed += 7
Where is the error here (it is not a syntax one as the code runs fine - it is just indented weirdly on this post)? Is there another requisite prior to taking in keyboard input.
It's not clear what the error is without more of your code, preferably a Minimal, Reproducible Example.
Here's what such an example could look like:
import pygame
import random
screen = pygame.display.set_mode((480, 320))
pygame.init()
player_speed = 0
run = True
clock = pygame.time.Clock()
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
print(f"Key {pygame.key.name(event.key)} pressed")
if event.key == pygame.K_DOWN:
player_speed += 7
elif event.key == pygame.K_UP:
player_speed -= 7
elif event.type == pygame.KEYUP:
print(f"Key {pygame.key.name(event.key)} released")
if event.key == pygame.K_DOWN:
player_speed -= 7
if event.key == pygame.K_UP:
player_speed += 7
screen.fill(pygame.Color("grey"))
pygame.display.update()
pygame.display.set_caption(f"Player Speed {player_speed}")
clock.tick(60) # limit to 60 FPS
pygame.quit()
This produces the following:
I've expanded your debug print statements to provide more context and added an update to the title bar to display the current value of the player_speed variable.

pygame.display.update(); pygame.error: video system not initialized [duplicate]

This question already has answers here:
pygame.error: video system not initialized
(5 answers)
why is the exit window button work but the exit button in the game does not work?
(1 answer)
Closed 1 year ago.
Here is my underdeveloped pygame ping-pong game, but my sprites(player&opponent) ain't moving, on giving a keyboard input. And when I quit the program, it yells an error pygame.error: video system not initialized. My pygame is the latest 1.9.6 version with all the files up-to-daee. However, I am certain that pygame.display is generating this error, but I even tried pygame.display.init() and that too didn't worked :(
import pygame
# Initialization
pygame.init()
# Screen, Caption and Icon
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('PyGame')
icon = pygame.image.load('ping-pong.png')
pygame.display.set_icon(icon)
# Create Rects
player = pygame.Rect((5, 230), (10, 120))
opponent = pygame.Rect((785, 230), (10, 120))
# Game Variables
playerY_change = 0
opponentY_change = 0
game_over = False
while not game_over:
# Coloring the Screen
screen.fill((27, 35, 43))
# Draw Rects
pygame.draw.rect(screen, (255,255,255), player)
pygame.draw.rect(screen, (255,255,255), opponent)
# Managing Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
pygame.quit()
if event.type == pygame.KEYUP:
if event.type == pygame.K_UP:
opponentY_change -= 3
if event.type == pygame.K_DOWN:
opponentY_change += 3
if event.type == pygame.K_w:
playerY_change -= 3
if event.type == pygame.K_s:
playerY_change += 3
if event.type == pygame.KEYDOWN:
if (event.type == pygame.K_UP) or (event.type == pygame.K_DOWN):
opponentY_change = 0
if (event.type == pygame.K_w) or (event.type == pygame.K_s):
playerY_change = 0
# Moving my sprites
player.y += playerY_change
opponent.y += opponentY_change
# Updating the screen on every iter of loop
pygame.display.update()
Here, you have two different problems :
First the movement is not working because to differentiate the keys, you use event.type to compare where it should be event.key. Try with for example :
if event.key == pygame.K_UP:
opponentY_change -= 3
The other problem is that when the game is over, you use pygame.quit() but later on the loop, you use pygame.display.update(). You should put the display update at the beginning of the loop.

Pygame keyboard input issue

I am trying to get user keyboard input using pygame. However, the problem is that after I run my code on IDLE, the keyboard input is never read by the program, and whatever I type is shown on the shell. Same issue if I run my code on PyCharm. Any idea? Below is my code:
pygame.init()
screen = pygame.display.set_mode((800, 600))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == KEYDOWN and event.key == pygame.K_w:
print("Yup!")
pygame.display.flip()
I'm having the exact same issue, also on a Mac using Pycharm and python 3.6. I'm printing the events and only MouseMotion events are recorded, rather than KeyDown.
Edit: apparently it's a known issue: Window does not get focus on OS X with Python 3
This is my code, and it also should work:
while not crashed:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
crashed = True
# get current list
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]:
print("UP")
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
print('this DOES work! :)')
elif event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
elif pressed[pygame.K_UP]:
print("UP")
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
pygame.display.flip()
x += x_change
gameDisplay.fill(black)
ship(x, y)
pygame.display.update()
clock.tick(60)
This code works perfectly for me
import pygame
pygame.init()
windowSize = width,height = 800,600
screen = pygame.display.set_mode(windowSize)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
print("Yup!")
pygame.display.flip()

Pygame holding down key

I am trying to make a fun program with a guy who opens his mouth whenever a press space. The problem is he only opens it for .1 seconds and then it closes again. I want to make it so that the mouth is open whenever i hold space.
Code:
import pygame
pygame.init()
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Open The Mouth")
clock = pygame.time.Clock()
faceImg = pygame.image.load("face_shut.png")
faceOpenImg = pygame.image.load("face_open.png")
def face(x,y):
gameDisplay.blit(faceImg,(face_x,face_y))
def faceOpen(x,y):
gameDisplay.blit(faceOpenImg,(faceOpen_x,faceOpen_y))
faceOpen_x = (1)
faceOpen_y = (1)
face_x = (1)
face_y = (1)
programRunning = True
while programRunning:
for event in pygame.event.get():
if event.type == pygame.QUIT:
programRunning = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
faceOpen(faceOpen_x,faceOpen_y)
pygame.display.update()
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
face(face_x,face_y)
pygame.display.update()
face(face_x,face_y)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
The issue appears to be here:
while programRunning:
for event in pygame.event.get():
if event.type == pygame.QUIT:
programRunning = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
faceOpen(faceOpen_x,faceOpen_y)
pygame.display.update()
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
face(face_x,face_y)
pygame.display.update()
# Here, always drawn closed at the end of the while
face(face_x,face_y)
pygame.display.update()
clock.tick(60)
Regardless of what's being set in the while, you are redrawing the face as closed at the end.
How about this instead:
# Drawn before the loop starts
face(face_x,face_y)
pygame.display.update()
while programRunning:
for event in pygame.event.get():
event_occurred = True
if event.type == pygame.QUIT:
programRunning = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
faceOpen(faceOpen_x,faceOpen_y)
pygame.display.update()
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
face(face_x,face_y)
pygame.display.update()
clock.tick(60)

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