Is there a way that while running pygame, I can also run the console too?

泪湿孤枕 提交于 2019-12-01 21:25:02

问题


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.


回答1:


Yes, have a look at the following example:

import pygame
import threading
import Queue

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

commands = Queue.Queue()

pos = 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 = raw_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(pos)
    pos = map(sum, zip(pos, m[command]))

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

  pygame.event.poll()

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

i.join()

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




回答2:


The thing is about that is if you do something like raw_input it will stop the program until that input is entered so that will stop the program every loop to take input but you can do things like print but they will print every loop

if you want to take input use InputBox Module this will make a little input box pop up on the screen thats in the loop

if you want to do it from the console you could try Threading it which im not to familiar with but you can check it out Multi-threading Tutorial

here is a questions that might help you out

Pygame writing to terminal

Good Luck! :)



来源:https://stackoverflow.com/questions/17597233/is-there-a-way-that-while-running-pygame-i-can-also-run-the-console-too

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!