Just starting out in pygame and trying to get a simple dot to move around the screen when you hold down the arrow keys. Currently, it only moves when you press the key, but you'd have to repeatedly press it.
import random
import pygame
import keyboard
import time
from pygame.locals import *
class Player:
def __init__(self):
self.x = 150
self.y = 150
pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Smile, you're beautiful!")
player = Player()
while True:
pygame.time.Clock().tick(60)
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
player.x += 5
if event.key == pygame.K_DOWN:
player.y += 5
if event.key == pygame.K_LEFT:
player.x -= 5
if event.key == pygame.K_UP:
player.y -= 5
pygame.event.pump()
pygame.display.flip()
pygame.display.update()
screen.fill((0,0,0))
pygame.draw.circle(screen, (180, 180, 180), (player.x, player.y), 5)
Also, I'd appreciate any tips you might have regarding my current code that may be improved upon or changed to make more efficient.
You need to usepygame.key.get_pressed
rather than the key down events. This way you know which keys are currently being pressed on every tick
while True:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_RIGHT]:
player.x += 5
if pressed[pygame.K_DOWN]:
player.y += 5
if pressed[pygame.K_LEFT]:
player.x -= 5
if pressed[pygame.K_UP]:
player.y -= 5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.