【问题标题】:[Python 2.7]In-window input shell using pygame?[Python 2.7]使用pygame的窗口输入shell?
【发布时间】:2017-09-06 14:20:52
【问题描述】:

我有一个 pygame 窗口(例如 mainWindow),
是否有可能拥有一个游戏终端,用户可以在其中为程序提供文本输入?
例如,坐标 x = 100 y = 300 处有一个圆,当用户键入

Left

圆圈向左移动到 x = 150 y = 300。
我已经知道可以使用 pygame.event.get() 来处理键盘输入,但我需要一个命令行控制的应用程序。
但终端应与 mainWindow 集成。 是否可以?如果是,怎么做?

P.s:在有人问之前,我正在使用 Linux 版本的 pygame for python 2.7,抱歉英语不好。

【问题讨论】:

  • 如果您只需要一个文本输入框,我刚刚发布了一个示例here。这也允许您添加大写字母。
  • 我去看看,谢谢!!!

标签: python python-2.7 user-interface terminal pygame


【解决方案1】:

这里需要 pygame.key,here 是文档

我给你做了个demo,另外pygame.key好像不支持大写,所以你想要的'Left',这里只能显示'left'

import pygame
from pygame.locals import *
from sys import exit

#initializing variables
pygame.init()
screen=pygame.display.set_mode((640,480),0,24)

FONT=pygame.font.SysFont("comicsansms",24)

# 26 letters, pygame_key not support for caps
LETTERS = [chr(i) for i in range(97,123)]

#text input in terminal
text = ""

start_input = False
#just use color for show if the input start or end
terminal_color = (240,240,240)
circle_position = [100,300]

def on_event(event):
    global text, terminal_color, start_input,circle_position
    if event.type==QUIT:
        exit()
    elif event.type == pygame.MOUSEBUTTONUP:
        pos = pygame.mouse.get_pos()
        if mouse_in_terminal_window(pos):
            # input start
            start_input = True
            terminal_color = (0,0,0)

    if start_input and pygame.key.get_focused():

        press=pygame.key.get_pressed()

        for i in xrange(0,len(press)): 
            if press[i]==1:
                name=pygame.key.name(i)

                if name == 'return':

                    if text == "left":
                        #change the circle postion from (100, 300) to (150, 300)
                        circle_position[0] += 50

                    #input end
                    start_input = False
                    terminal_color = (240,240,240)
                    text= ""

                elif name in LETTERS:
                    text += name

                elif name == 'backspace':
                    text = text[:-1] if len(text)>0 else text

def on_render():
    screen.fill((255,255,255))
    render_terminal()
    render_circle()
    pygame.display.update()

def render_terminal():
    pygame.draw.rect(screen, terminal_color,(0,50,640,50),0)
    t=FONT.render(text,True,(255,255,255))
    screen.blit(t,(10,60))
def render_circle():
    pygame.draw.circle(screen, (0,0,0), circle_position, 20, 0)

def mouse_in_terminal_window(pos):
    if 0<=pos[0]<=640 and 50<=pos[1]<=100:
        return True
    return False


while True:
    for event in pygame.event.get():
        on_event(event)
    on_render()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多