The key events are being registered fine on the console. Also, my paddle is showing up which suggests that my paddle class called from another file works. However, I would like my paddle to move smoothly when the left arrow key or the right arrow key is pressed down so the user does not have to repeatedly click. However, with my current code, the paddle does not move at all. I've tried changing around the position of the if/else statement that changes position to no avail. What am I doing wrong here?
The main game:
import pygame
from pygame.locals import *
from Config import Config
from Paddle import Paddle
pygame.init()
#--Display settings
pygame.display.set_caption(Config['game']['caption'])
game_display = pygame.display.set_mode((Config['game']['display_width'],
Config['game']['display_height']))
clock = pygame.time.Clock()
paddle= Paddle(game_display)
x_change = 0
pressed_left = False
pressed_right = False
def event_handler():
for event in pygame.event.get():
print (event)
if (event.type == QUIT) or (event.type == KEYDOWN and event.key ==
K_ESCAPE):
pygame.quit()
quit()
#To move the paddle to the left and right
if event.type == KEYDOWN:
if event.key == K_LEFT:
pressed_left = True
elif event.key== K_RIGHT:
pressed_right = True
#If the key is up
if event.type == KEYUP:
if event.key == K_LEFT:
pressed_left = False
x_change = 0
elif event.key == K_RIGHT:
pressed_right = False
x_change = 0
#--This changes the position
if pressed_left:
x_change = -5
if pressed_right:
x_change = 5
while True:
event_handler()
game_display.fill(Config['colors']['white'])
paddle.draw()
paddle.movement(x_change)
pygame.display.update()
clock.tick(Config['game']['fps'])
And from my paddle.py that contains the Paddle class:
import pygame
from pygame.locals import *
from Config import Config
class Paddle:
def __init__(self, game_display):
self.x = (Config['game']['display_width'] * 0.45)
self.y = (Config['game']['display_height'] * 0.92)
self.game_display=game_display
def draw(self):
pygame.draw.rect(self.game_display, Config['colors']['red'],
[self.x, self.y, 40, 25])
def movement(self, x_change):
self.x += x_change