Python 在pygame中可以移动精灵吗
我想使用终端的原始用户输入来使用pygame移动精灵,而不是使用关键事件侦听器。最终,我希望能够通过终端发出“向上移动”、“向左移动”等命令来控制精灵。我正在尝试制作一个交互式终端应用程序,当你在提示符中键入命令时,它会创建一个pygame窗口,这样你就可以看到一切是如何工作的。可能吗?这就是我所尝试的:Python 在pygame中可以移动精灵吗,python,pygame,sprite,raw-input,Python,Pygame,Sprite,Raw Input,我想使用终端的原始用户输入来使用pygame移动精灵,而不是使用关键事件侦听器。最终,我希望能够通过终端发出“向上移动”、“向左移动”等命令来控制精灵。我正在尝试制作一个交互式终端应用程序,当你在提示符中键入命令时,它会创建一个pygame窗口,这样你就可以看到一切是如何工作的。可能吗?这就是我所尝试的: #!/usr/bin/env python3 # draw a world # add a player and player control # add player movement #
#!/usr/bin/env python3
# draw a world
# add a player and player control
# add player movement
# GNU All-Permissive License
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved. This file is offered as-is,
# without any warranty.
import pygame
import sys
import os
import time
'''
Objects
'''
class Player(pygame.sprite.Sprite):
'''
Spawn a player
'''
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.movex = 0
self.movey = 0
self.frame = 0
self.image = pygame.image.load(os.path.join('Images','character_sized.png'))
self.rect = self.image.get_rect()
def control(self,x,y):
'''
control player movement
'''
self.movex += x
self.movey += y
def update(self):
'''
Update sprite position
'''
self.rect.x = self.rect.x + self.movex
self.rect.y = self.rect.y + self.movey
'''
Setup
'''
worldx = 960
worldy = 720
fps = 40 # frame rate
ani = 4 # animation cycles
clock = pygame.time.Clock()
pygame.init()
main = True
BLUE = (25,25,200)
BLACK = (23,23,23 )
WHITE = (254,254,254)
ALPHA = (0,255,0)
world = pygame.display.set_mode([worldx,worldy])
backdrop = pygame.image.load('Images/grass-pattern.png')
backdropbox = world.get_rect()
player = Player() # spawn player
player.rect.x = 0
player.rect.y = 0
player_list = pygame.sprite.Group()
player_list.add(player)
steps = 10 # how fast to move
userInput = " "
'''
Main loop
'''
while main == True:
userInput = raw_input(">>>")
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit()
main = False
# Cuando aprietas la tecla
if userInput == 'l':
player.control(-steps,0)
time.sleep(2) # Esto es lo que hace que se mueva el character a la izquierda.
if userInput == 'r':
player.control(steps*2,0) # Esto es lo que hace que se mueva el character a la derecha.
time.sleep(2)
if userInput == 'u':
print('jump')
time.sleep(2)
# # Cuando levantas la tecla.
# if event.key == pygame.K_LEFT or event.key == ord('a'):
# player.control(steps,0)
# if event.key == pygame.K_RIGHT or event.key == ord('d'):
# player.control(-steps,0)
# if event.key == ord('q'):
# pygame.quit()
# sys.exit()
# main = False
# world.fill(BLACK)
world.blit(backdrop, backdropbox)
player.rect.clamp_ip(backdropbox)
player.update()
player_list.draw(world) #refresh player position
pygame.display.flip()
clock.tick(fps)
该模块有一个方法,您可以使用该方法。Windows用户必须安装诅咒
首先输入stdscr.nodelay(1)
,使getch
方法不会阻塞,然后在主while循环中使用它来获取按下的键并将其与字符串变量(此处称为command
)连接,然后使用stdscr.addstr
来显示它
当用户按enter键时,检查输入的命令是否等于'move left'
或'move right'
,并按相应方向移动游戏对象
import curses
import pygame as pg
def main(stdscr):
stdscr.nodelay(1) # Makes the `getch` method non-blocking.
# Use `addstr` instead of `print`.
stdscr.addstr('Press "Esc" to exit...\n')
command = '' # Add the entered characters to this string.
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
rect = pg.Rect(300, 100, 30, 50)
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return
inpt = stdscr.getch() # Here we get the pressed key.
if inpt == 27: # Esc
return
elif inpt in (ord('\n'), ord('\r')): # Enter pressed.
# Check which command was entered and move the rect.
if command == 'move right':
rect.x += 20
elif command == 'move left':
rect.x -= 20
command = '' # Reset the command string.
stdscr.addstr(2, 0, '{}\n'.format(command)) # Write in the second line.
elif inpt == 8: # Backspace
command = command[:-1]
stdscr.addstr(2, 0, '{}\n'.format(command))
elif inpt not in (-1, 0): # ValueErrors if inpt is -1 or 0.
command += chr(inpt) # Concatenate the strings.
stdscr.addstr(2, 0, '{}\n'.format(command))
screen.fill((30, 30, 30))
pg.draw.rect(screen, (0, 120, 250), rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
# Use the curses.wrapper to start the program. It handles
# exceptions and resets the terminal after the game ends.
curses.wrapper(main)
pg.quit()
我对诅咒没有太多经验,所以不能保证一切都正常
该模块(Windows)也有一个getch函数,我认为可以用于Linux和MacOS。这个跨平台的解决方案似乎有效,但我从未测试过:我认为您不能使用
raw\u input()
来实现它,因为它会一直阻塞,直到用户按下Enter
键,这将阻止程序的pygame部分运行,直到它返回。