本文介绍了有没有办法在运行pygame的同时也可以运行控制台?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在python中是否有一种方法可以在我的games.screen.mainloop()内部的图形部分运行时,是否可以执行一些操作,例如从控制台通过raw_input()获取用户输入./p>

I was wondering if there is a way, in python, that while my graphical piece inside my games.screen.mainloop() is running, if I can do something like get user input through raw_input() from the console.

推荐答案

是的,请看以下示例:

import pygame
import threading
import queue

pygame.init()
screen = pygame.display.set_mode((300, 300))
quit_game = False

commands = queue.Queue()

pos = pygame.Vector2(10, 10)

m = {'w': (0, -10),
     'a': (-10, 0),
     's': (0, 10),
     'd': (10, 0)}

class Input(threading.Thread):
  def run(self):
    while not quit_game:
      command = input()
      commands.put(command)

i = Input()
i.start()

old_pos = []

while not quit_game:
  try:
    command = commands.get(False)
  except queue.Empty:
    command = None

  if command in m:
    old_pos.append((int(pos.x), int(pos.y)))
    pos += m[command]

  for e in pygame.event.get():
    if e.type == pygame.QUIT:
      print("press enter to exit")
      quit_game = True

  screen.fill((0, 0, 0))
  for p in old_pos:
      pygame.draw.circle(screen, (75, 0, 0), p, 10, 2)
  pygame.draw.circle(screen, (200, 0, 0), (int(pos.x), int(pos.y)), 10, 2)
  pygame.display.flip()

i.join()

它会创建一个红色小圆圈.您可以通过在控制台中输入,,或来移动它.

It creates a little red circle. You can move it around with entering , , or into the console.

这篇关于有没有办法在运行pygame的同时也可以运行控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 09:58