pygame的键盘输入功能不起作用

问题描述 投票:-1回答:2

我正在寻找大约3个小时的原因,但我找不到任何解决方案。

没有错误,但程序似乎没有检测到我的键输入。另外,我没有看到我的代码有什么问题。

另外,我不认为我理解event.key和pygame.event.get()是如何运作的。如果有人向我解释,我将非常感激。

这是我的Ascii游戏中的代码,它只是代码的开头,到目前为止我已经完成了。

    class maingame:

    def __init__(self):
        exit = False

    def processkey(self):
        global hotkey,crazy

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == K_SPACE:
                    crazy = 1
                if event.key == K_DOWN:
                    dir = 's'
                    y_option -= 1
                    hotkey  = 2
                if event.key == pygame.K_w:
                    dir = 'w'
                    y_option += 1
                    hotkey = 1
                if event.key == K_LEFT:
                    dir = 'a'

                if event.key == K_RIGHT:
                    dir = 'd'
            else:
                    hotkey = 1
                    y_option = 0
                    crazy = 0

    def displaymanu(self,hotkey):
        print(">" if hotkey == 1 else " ","play")
        print(">" if hotkey == 2 else " ","quit")
        if hotkey == 1 and crazy == 1:
            self.play()     
        elif hotkey == 2 and crazy == 1:
            exit = True
if __name__ == '__main__':
        while not quit:
            displayee = maingame()
            os.system('cls')
            displayee.processkey()
            displayee.processkey()
            displayee.displaymanu(hotkey)
python input keyboard pygame
2个回答
1
投票

PyGame将not work without a screen/window。因此,您的代码需要首先初始化PyGame,然后打开一个窗口(或全屏显示)。

根据我对您的代码的理解,它看起来应该显示一个菜单:

> Play
  Quit

按↑/↓(或w / s)移动选项之间的>光标,然后空格运行该选项。

你的代码的一个问题是你试图解释displaymanu()函数中的键击。最好保持一个函数做一个单一的事情,所以processkey()中的所有键处理和displaymanu()中的屏幕绘制。

我修改了你的代码到它工作的地步。这涉及修改类,以便初始化PyGame显示。菜单需要显示在窗口中,因此添加了一个新函数drawTextAt()来代替print()。类Maingame的许多成员变量都有范围问题,但只是指定self.variable-name(使它们成为类的成员)修复了这些问题。

我还添加了一个游戏状态,以显示键处理需要根据游戏当前所处的阶段进行更改。它从菜单开始,其中向上/向下只是更改菜单选项。但是后来在游戏过程中,Up / Down需要做一些完全不同的事情。

import pygame
import os

# Window size
WINDOW_WIDTH  = 400
WINDOW_HEIGHT = 400
# colours
DARK    = (  50, 50, 50 )
RED     = ( 255, 50, 50 )


class Maingame:

    def __init__(self):
        # Initialise PyGame
        pygame.init()
        pygame.font.init()
        # Initialise a window
        pygame.display.set_caption("Main Game")
        self.screen = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), pygame.DOUBLEBUF )
        # menu font
        self.font   = pygame.font.SysFont(None, 20)

        self.hotkey     = 1
        self.crazy      = 0
        self.y_option   = 0
        self.game_state = 0  # state=0 -> show menu, 1 => Game, 2-> Game Over

    def processkey(self):
        # no key pressed yet
        self.crazy = 0
        dir_code   = ''  
        exit       = False

        # Detect keys pressed
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    dir_code = ' '
                    self.crazy = 1
                elif event.key == pygame.K_s or event.key == pygame.K_DOWN:
                    dir_code = 's'
                    self.y_option -= 1
                    self.hotkey  = 2
                elif event.key == pygame.K_w or event.key == pygame.K_UP:
                    dir_code = 'w'
                    self.y_option += 1
                    self.hotkey = 1
                elif event.key == pygame.K_LEFT:
                    dir_code = 'a'
                elif event.key == pygame.K_RIGHT:
                    dir_code = 'd'
                else:
                    self.hotkey = 1
                    self.y_option = 0
                    self.crazy = 0
                print( "DEBUG - game_state=[%d], dir_code is [%s], hotkey is [%d], crazy=[%d]" % ( self.game_state, dir_code, self.hotkey, self.crazy ) )

                # Act on the keys pressed (if any)
                if self.game_state == 0:  # menu mode
                    if self.hotkey == 1 and self.crazy == 1:
                        self.game_state = 1 # start the game
                    elif self.hotkey == 2 and self.crazy == 1:
                        exit = True
                elif self.game_state == 1:  # game mode
                    pass  # TODO
                elif self.game_state == 2:  # game-over mode
                    pass  # TODO

        return exit

    def drawTextAt( self, text, coord, foreground_colour=(255,255,255) ):
        """ Convert the specified text into a font-bitmap, and draw it
            onto the screen at the given co-ordinates """
        text_bitmap = self.font.render( text, True, foreground_colour )
        self.screen.blit( text_bitmap, coord )

    def displaymanu( self ):
        """ Draw the Menu """
        # MENU
        self.screen.fill( DARK )
        # Draw the menu options
        prefix = [ "  ", "  " ]
        prefix[ self.hotkey-1 ] = "> "
        self.drawTextAt( prefix[0] + "Play", ( 30, 100 ) )
        self.drawTextAt( prefix[1] + "Quit", ( 30, 150 ) )


    def displaygame( self ):
        """ Draw the Game Screen """
        # GAME SCREEN
        self.screen.fill( RED )
        self.drawTextAt( "GAME - #TODO", ( 30, 180 ) )

    def displaygameover( self ):
        """ Draw the Game-Over Screen """
        # GAME OVER SCREEN
        self.screen.fill( RED )
        self.drawTextAt( "* GAME OVER *", ( 30, 180 ) )

if __name__ == '__main__':
    # Initialise PyGame and the window

    displayee = Maingame()
    quit = False
    while not quit:
        #os.system('cls')
        # Draw the correct display for the state
        if displayee.game_state == 0:
            displayee.displaymanu()
        elif displayee.game_state == 1:
            displayee.displaygame()
        elif displayee.game_state == 2:
            displayee.displaygameover()
        # Push all drawing to the screen
        pygame.display.flip()
        # Handle keys
        quit = displayee.processkey()

0
投票

看起来你没有把pygame.放在这里的一些变量之前:

if event.key == K_SPACE: # Does not have pygame prefix
    crazy = 1
if event.key == K_DOWN: # Does not have pygame prefix
    dir = 's'
    y_option -= 1
    hotkey  = 2
if event.key == pygame.K_w: # Does have pygame prefix
    dir = 'w'
    y_option += 1
    hotkey = 1
if event.key == K_LEFT: # Does not have pygame prefix
    dir = 'a'

if event.key == K_RIGHT: # Does not have pygame prefix
    dir = 'd'

pygame.添加到那些,它应该在那之后检测。奇怪的是它在运行时没有拉出NameError异常。

© www.soinside.com 2019 - 2024. All rights reserved.