Минимальный рабочий пример.
Когда игрок не двигается, он начинает дрожать (делать случайные движения вверх и вниз)
Я использую do_something = True/False
, чтобы контролировать, должен ли он дрожать или нет.
Когда я нажимаю клавишу LEFT
или RIGH
, я устанавливаю do_something = False
и сбрасываю таймер time_since_last_action
.
Когда я не нажимаю клавиши, и он ничего не делает, тогда таймер меняет значение.
Когда таймер> 1000, и он не двигается и ничего не делает, тогда я устанавливаю do_something = True
# https://github.com/furas/python-examples/
import pygame
import random
# --- constants --- (UPPER_CASE_NAMES)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 25 # for more than 220 it has no time to update screen
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# --- classes --- (CamelCaseNames)
class Player(pygame.sprite.Sprite):
def __init__(self, x=SCREEN_WIDTH//2, y=SCREEN_HEIGHT//2):
super().__init__()
self.image = pygame.Surface((100,100))
self.image.fill(WHITE)
self.rect = self.image.get_rect(centerx=x, centery=y)
def update(self):
#move_x = random.randint(-5, 5)
#move_y = random.randint(-5, 5)
#self.rect.move_ip(move_x,move_y)
pass
def draw(self, surface):
surface.blit(self.image, self.rect)
# --- functions --- (lower_case_names)
# --- main ---
pygame.init()
screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )
player = Player()
# --- mainloop ---
clock = pygame.time.Clock()
# default values at start
do_something = False
time_since_last_action = 0
running = True
while running:
# --- FPS ---
dt = clock.tick(30)
time_since_last_action += dt
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
running = False
keys = pygame.key.get_pressed()
moved = False
if keys[pygame.K_LEFT]:
player.rect.x -= 10 # player.rect.width
moved = True
# reset other values
do_something = False
time_since_last_action = 0
elif keys[pygame.K_RIGHT]:
player.rect.x += 10 # player.rect.width
moved = True
# reset other values
do_something = False
time_since_last_action = 0
if not do_something and not moved and time_since_last_action > 1000:
do_something = True
# reset other values
time_since_last_action = 0
if do_something:
# - action -
# shaking
player.rect.y -= random.randint(-5, 5)
# --- changes/moves/updates ---
# empty
# --- draws ---
screen.fill(BLACK)
player.draw(screen)
pygame.display.flip()
# --- end ---
pygame.quit()
Я поставил более сложную версию на Github . Это сохраняет положение, меняет изображение и начинает дрожать. Когда вы нажимаете LEFT
или RIGHT
, восстанавливается исходное положение и изображение.