logo
down
shadow

Keydown event for Pygame


Keydown event for Pygame

By : user2956571
Date : November 22 2020, 10:56 AM
Any of those help this is because updated tankX values do not affect the tank object. there are many ways to make it work. for example, inserting a re-initialization of tank in the while True loop:
code :
import pygame, sys
from pygame.locals import *

WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
TANK_SIZE = 20

BLACK = (0  ,0  ,0  )
WHITE = (255,255,255)

def drawArena():
    DISPLAYSURF.fill(BLACK)

def drawTank(tank):
    pygame.draw.rect(DISPLAYSURF, WHITE, tank)

def main():
    pygame.init()
    global DISPLAYSURF
    DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    pygame.display.set_caption('Tanks')

    tankX = 200
    tankY = 200

    tank = pygame.Rect(tankX, tankY, TANK_SIZE, TANK_SIZE)

    drawArena()
    drawTank(tank)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    tankX -= 20
                if event.key == pygame.K_RIGHT:
                    tankX += 20

        tank = pygame.Rect(tankX, tankY, TANK_SIZE, TANK_SIZE)

        drawArena()
        drawTank(tank)

        pygame.display.update()

if __name__ == '__main__':
    main()


Share : facebook icon twitter icon
Python/Pygame: How to break a while loop initiated by KEYDOWN event with a KEYUP event?

Python/Pygame: How to break a while loop initiated by KEYDOWN event with a KEYUP event?


By : user2181182
Date : March 29 2020, 07:55 AM
Hope this helps You don't need to start a second loop for this. In your main loop, just check if keypressed is still true and apply the changes to your variables. The color change effect should be repeated again and again until a KEYUP event is registered.
So, your main loop would look something like this:
code :
while True:

    for event in pygame.event.get():

        if event.type == KEYDOWN:
            keypressed = True

            #Set your changetype and color variables

        if event.type == KEYUP:

            keypressed = False;

    if keypressed:

        Color_Update(changeType, color)                
        Color_Draw(red, green, blue)

    pygame.display.update()
Pygame if event.type == pygame.KEYDOWN() TypeError: 'int' object is not callable

Pygame if event.type == pygame.KEYDOWN() TypeError: 'int' object is not callable


By : Aman Mangal
Date : March 29 2020, 07:55 AM
it helps some times The code is meant to quickly exit pygame by tapping escape. , Your problem is in the line
code :
if event.type == pygame.KEYDOWN():
if event.type == pygame.KEYDOWN:
Pygame - Issue Altering x Value While event.type == pygame.KEYDOWN

Pygame - Issue Altering x Value While event.type == pygame.KEYDOWN


By : Dragonchicken
Date : March 29 2020, 07:55 AM
hope this fix your issue It seems you have put the games loop code inside the event handler. Remove an indent from each line between lead_x += lead_x_change and clock.tick(15) inclusive
I would also remove the lines
code :
if event.type == pygame.MOUSEMOTION:
    lead_y_change = 0
    lead_x_change = 0
Error while using pygame keyDown event with pygame mixer

Error while using pygame keyDown event with pygame mixer


By : Diego Fernando Soler
Date : March 29 2020, 07:55 AM
To fix this issue There are a number of reasons why your code doesn't work, see mine below.
code :
import pygame, sys

pygame.init()

window = pygame.display.set_mode((600,400))

kick = pygame.mixer.Sound("kick.wav")
clap = pygame.mixer.Sound("clap.wav")

while True:
   for event in pygame.event.get():
      if event.type == pygame.KEYDOWN:
         if event.key == pygame.K_a:
            kick.play()
         if event.key == pygame.K_d:
            clap.play()
      if event.type == pygame.QUIT:
         pygame.quit()
         quit()
window = pygame.display.set_mode((600,400))
kick.play()
   for event in pygame.event.get():
       if event.type == pygame.KEYDOWN:
           if event.key == pygame.K_a:
pygame KEYDOWN event and key events

pygame KEYDOWN event and key events


By : JesseR
Date : March 29 2020, 07:55 AM
it should still fix some issue Not every event has all possbile attributes. that's why you have to check the type of the event first.
Here's a list of all attributes for each event type:
code :
QUIT             none
ACTIVEEVENT      gain, state
KEYDOWN          unicode, key, mod
KEYUP            key, mod
MOUSEMOTION      pos, rel, buttons
MOUSEBUTTONUP    pos, button
MOUSEBUTTONDOWN  pos, button
JOYAXISMOTION    joy, axis, value
JOYBALLMOTION    joy, ball, rel
JOYHATMOTION     joy, hat, value
JOYBUTTONUP      joy, button
JOYBUTTONDOWN    joy, button
VIDEORESIZE      size, w, h
VIDEOEXPOSE      none
USEREVENT        code
Related Posts Related Posts :
  • Return new instance of subclass when using methods inherited from parent class in Python
  • Which function in django.contrib.auth creates the default model permissions?
  • Formatting text in tabular form with Python
  • How to determine the first day of a month in Python
  • Error while converting date to timestamp in python
  • Python string iterations
  • Is there any file number limitation when you select multiple files with wxFileDialog?
  • Errors with Matplotlib when making an executable with Py2exe (Python)
  • Django Haystack - Indexing single field
  • Go Pro Hero 3 - Streaming video over wifi
  • Appending a column in .csv with Python/Pandas
  • How to change my result directory in Robot framework using RIDE?
  • problem with using pandas to manipulate a big text file in python
  • python-magic module' object has no attribute 'open'
  • Where goes wrong for this High Pass Filter in Python?
  • Why inserting keys in order into a python dict is faster than doint it unordered
  • flann index saving in python
  • Create new instance of list or dictionary without class
  • How can I easily convert FORTRAN code to Python code (real code, not wrappers)
  • Address of lambda function in python
  • Python adding space between characters in string. Most efficient way
  • python http server, multiple simultaneous requests
  • Disguising username & password on distributed python scripts
  • Post GraphQL mutation with Python Requests
  • Why doesnt pandas create an excel file?
  • Rolling comparison between a value and a past window, with percentile/quantile
  • How to avoid repetitive code when defining a new type in python with signature verification
  • How to configure uWSGI in order to debug with pdb (--honour-stdin configuration issue)
  • In Python, how do you execute objects that are functions from a list?
  • Python- Variable Won't Subtract?
  • Processing Power In Python
  • Python 2.7.2 - Cannot import name _random or random from sys
  • Why doesn't the Python sorted function take keyword order instead of reverse?
  • Make a function redirect to other functions depending on a variable
  • get_absolute_url in django-categories
  • Monitoring non-Celery background task with New Relic in Python
  • Feature selection with LinearSVC
  • LSTM - Predicting the same constant values after a while
  • Test the length of elements in a list
  • Django: render radiobutton with 3 columns, cost column must change according to size & quantity selected
  • Python class attributes vs global variable
  • sys.stdout.writelines("hello") and sys.stdout.write("hello")
  • is ndarray faster than recarray access?
  • Python - search through directory trees, rename certain files
  • GAE: How to build a query where a string begins with a value
  • TypeError: __init__() takes at least 2 arguments (1 given)
  • Overriding and customizing "django.contrib.auth.views.login"
  • Django : Redirect to a particular page after login
  • Python search and copy files in directory
  • pretty printing numpy ndarrays using unicode characters
  • Frequent pattern mining in Python
  • How can I make a set of functions that can be used synchronously as well as asynchronously?
  • Convert one dice roll to two dice roll
  • count occourrence in a list
  • Writing an If condition to filter out the first word
  • to read file and compare column in python
  • Install python-numpy in the Virtualenv environment
  • `.select_by_visible_text()` is failed to select element?
  • Unable to send data multiple requests in a single connection — socket error
  • Pandas HDFStore unload dataframe from memory
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org