Pygame 等待按键被持有

发布于 2025-01-20 20:18:51 字数 3106 浏览 1 评论 0原文

我正在与Pygame一起制作基本游戏,我不是Python的最大粉丝,所以我决定让自己喜欢它。

现在,对于这个问题。当我检查关键点时,我希望玩家在握住钥匙时继续移动。当我按右箭头时,它会移动一次,然后等待一秒钟,然后继续。我不确定如何描述它。这就是DAS在俄罗斯方块的工作方式。

这是代码,我不会发布所有内容,但我将发布所有重要的内容

player.py

import pygame
from settings import *
from tileset import TileSet
class Player(pygame.sprite.Sprite):
    def __init__(self, pos, group):
        super().__init__(group)
        self.image = TileSet('Assets/Actor/Characters/Princess/SpriteSheet.png', 16, 16).get(0,0)
        self.SCALE_FACTOR = 4
        self.size = self.image.get_size()
        self.image = pygame.transform.scale(self.image, (int(self.size[0] * self.SCALE_FACTOR), int(self.size[0] * self.SCALE_FACTOR)))
        self.rect = self.image.get_rect(topleft = pos)

        self.direction = pygame.math.Vector2()
        self.speed = 10
    def input(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_w]:
            self.direction.y = -1
        elif keys[pygame.K_s]:
            self.direction.y =  1
        else:
            self.direction.y =  0
        if keys[pygame.K_d]:
            self.direction.x =  1
        elif keys[pygame.K_a]:
            self.direction.x = -1
        else:
            self.direction.x =  0
    def move(self, speed):
        self.rect.center += self.direction * speed
    def update(self):
        self.input()
        self.move(self.speed)

level.py

import pygame
from settings import *
from tile import Tile
from player import Player
from debug import debug
class Level:
    def __init__(self):
        self.dsurf = pygame.display.get_surface()
        self.visible_sprites = pygame.sprite.Group()
        self.obstacle_sprites = pygame.sprite.Group()

        self.create_map()
    def create_map(self):
        for row_i, row in enumerate(WORLD_MAP):
            for col_i, col in enumerate(row):
                x = col_i * TILE_SIZE
                y = row_i * TILE_SIZE
                if col == 'x':
                    Tile((x, y), [self.visible_sprites, self.obstacle_sprites])
                if col == 'p':
                    self.player = Player((x, y), [self.visible_sprites])
    def tick(self):
        self.visible_sprites.draw(self.dsurf)
        self.visible_sprites.update()
        debug(f"Player direction: {self.player.direction}")

main.py

import pygame
import pygame.locals
import sys

from settings import *
from level import Level
class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption("Darka")
        self.clock = pygame.time.Clock()
        self.level = Level()
    def run(self):
        while pygame.event.wait().type != pygame.locals.QUIT:
            self.screen.fill('black')
            self.level.tick()
            pygame.display.update()
            self.clock.tick(FPS_CAP)

if __name__ == "__main__":
    game = Game()
    game.run()

I am working on a basic game with pygame, im not the biggest fan of python so i decided to make myself like it.

Now, for the issue. When i am checking for keypresses, i want the player to continue moving when i hold the key. When i press right arrow, it moves once, then waits a second then continues. Im not sure how to describe it. It is how DAS works in tetris.

Here is the code, i wont post all of it but i will post all the important things

player.py

import pygame
from settings import *
from tileset import TileSet
class Player(pygame.sprite.Sprite):
    def __init__(self, pos, group):
        super().__init__(group)
        self.image = TileSet('Assets/Actor/Characters/Princess/SpriteSheet.png', 16, 16).get(0,0)
        self.SCALE_FACTOR = 4
        self.size = self.image.get_size()
        self.image = pygame.transform.scale(self.image, (int(self.size[0] * self.SCALE_FACTOR), int(self.size[0] * self.SCALE_FACTOR)))
        self.rect = self.image.get_rect(topleft = pos)

        self.direction = pygame.math.Vector2()
        self.speed = 10
    def input(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_w]:
            self.direction.y = -1
        elif keys[pygame.K_s]:
            self.direction.y =  1
        else:
            self.direction.y =  0
        if keys[pygame.K_d]:
            self.direction.x =  1
        elif keys[pygame.K_a]:
            self.direction.x = -1
        else:
            self.direction.x =  0
    def move(self, speed):
        self.rect.center += self.direction * speed
    def update(self):
        self.input()
        self.move(self.speed)

level.py

import pygame
from settings import *
from tile import Tile
from player import Player
from debug import debug
class Level:
    def __init__(self):
        self.dsurf = pygame.display.get_surface()
        self.visible_sprites = pygame.sprite.Group()
        self.obstacle_sprites = pygame.sprite.Group()

        self.create_map()
    def create_map(self):
        for row_i, row in enumerate(WORLD_MAP):
            for col_i, col in enumerate(row):
                x = col_i * TILE_SIZE
                y = row_i * TILE_SIZE
                if col == 'x':
                    Tile((x, y), [self.visible_sprites, self.obstacle_sprites])
                if col == 'p':
                    self.player = Player((x, y), [self.visible_sprites])
    def tick(self):
        self.visible_sprites.draw(self.dsurf)
        self.visible_sprites.update()
        debug(f"Player direction: {self.player.direction}")

main.py

import pygame
import pygame.locals
import sys

from settings import *
from level import Level
class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption("Darka")
        self.clock = pygame.time.Clock()
        self.level = Level()
    def run(self):
        while pygame.event.wait().type != pygame.locals.QUIT:
            self.screen.fill('black')
            self.level.tick()
            pygame.display.update()
            self.clock.tick(FPS_CAP)

if __name__ == "__main__":
    game = Game()
    game.run()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挽手叙旧 2025-01-27 20:18:51

我会将您的主循环更改为将事件传递到播放器精灵,并调用其更新功能

def run(self):
    finished = False
    while not finished:
            for event in pygame.event.get():            
                if event.type == pygame.QUIT:
                    finished = True
                elif event.type in (pygame.KEYDOWN, pygame.KEYUP):
                    #send all keys to player sprite
                    self.level.player.move(event)

            self.screen.fill('black')
            self.level.player.move()  # or add to level.tick()
            self.level.tick()
            pygame.display.update()
            self.clock.tick(FPS_CAP)
        

更改为player Sprite input()函数,

def input(self, event):
    if event.type == pygame.KEYDOWN
        if event_key == pygame.K_w:
            self.direction.y = -1
        elif event_key ==pygame.K_s:
            self.direction.y =  1
        elif event_key == pygame.K_d:
            self.direction.x =  1
        elif event_key == pygame.K_a]:
            self.direction.x = -1
    elif event.type == pygame.KEYUP:
        if event_key in (pygame.K_w, pygame.K_s):
            self.direction.y =  0
        elif event_key in (pygame.K_d, pygame.K_a):
            self.direction.x =  0

当您按下方向键并停止发布时,Sprite应该开始移动。

注意:未经测试的代码。

I would change your main loop to relay events to the player sprite and call its update function

def run(self):
    finished = False
    while not finished:
            for event in pygame.event.get():            
                if event.type == pygame.QUIT:
                    finished = True
                elif event.type in (pygame.KEYDOWN, pygame.KEYUP):
                    #send all keys to player sprite
                    self.level.player.move(event)

            self.screen.fill('black')
            self.level.player.move()  # or add to level.tick()
            self.level.tick()
            pygame.display.update()
            self.clock.tick(FPS_CAP)
        

Changes to Player sprite input() function

def input(self, event):
    if event.type == pygame.KEYDOWN
        if event_key == pygame.K_w:
            self.direction.y = -1
        elif event_key ==pygame.K_s:
            self.direction.y =  1
        elif event_key == pygame.K_d:
            self.direction.x =  1
        elif event_key == pygame.K_a]:
            self.direction.x = -1
    elif event.type == pygame.KEYUP:
        if event_key in (pygame.K_w, pygame.K_s):
            self.direction.y =  0
        elif event_key in (pygame.K_d, pygame.K_a):
            self.direction.x =  0

This way your sprite should start moving when you press a direction key and stop on release.

Note: untested code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文