안타깝게도 시스템의 기본 자동 반복 메커니즘이 다소 유용합니다. 예를 들어, "w"를 길게 누르는 순간 사용중인 Mac에서 언론 및 출시 이벤트가 발생합니다. 눌렀을 때, "o"를 누르면 "o"에 대한 프레스 및 릴리스 스트림을 얻지 만 "w"에 대한 이벤트는 더 이상 발생하지 않습니다.
미니 상태 시스템을 설정하고 키 누르기 및 키 릴리스 이벤트에 바인딩해야합니다. 이것은 어떤 키가 눌려 졌는지 아닌지를 추적 할 수있게합니다. 그런 다음 프레임을 그릴 때마다 기계를 조회하여 어떤 키가 눌려 있는지 확인하고 그에 따라 조치 할 수 있습니다.
다음은 내가 함께 던진 간단한 해킹입니다. 난 단지 내 맥에서, 그리고 파이썬 2.5에서만 테스트했습니다. 나는 "pythonic"또는 능률적 인 시도에 진짜 시도를 만들지 않았다. 이 코드는 그 기술을 설명하기위한 것일뿐입니다. 이 코드를 사용하면 "w"또는 "s"와 "o"또는 "l"을 동시에 눌러 두 개의 패들을 위아래로 움직일 수 있습니다.
'''Example that demonstrates keeping track of multiple key events'''
from Tkinter import *
class Playfield:
def __init__(self):
# this dict keeps track of keys that have been pressed but not
# released
self.pressed = {}
self._create_ui()
def start(self):
self._animate()
self.root.mainloop()
def _create_ui(self):
self.root = Tk()
self.p1label = Label(text="press w, s to move player 1 up, down",
anchor="w")
self.p2label = Label(text="press o, l to move player 2 up, down",
anchor="w")
self.canvas = Canvas(width=440, height=440)
self.canvas.config(scrollregion=(-20, -20, 420, 420))
self.p1label.pack(side="top", fill="x")
self.p2label.pack(side="top", fill="x")
self.canvas.pack(side="top", fill="both", expand="true")
self.p1 = Paddle(self.canvas, tag="p1", color="red", x=0, y=0)
self.p2 = Paddle(self.canvas, tag="p2", color="blue", x=400, y=0)
self._set_bindings()
def _animate(self):
if self.pressed["w"]: self.p1.move_up()
if self.pressed["s"]: self.p1.move_down()
if self.pressed["o"]: self.p2.move_up()
if self.pressed["l"]: self.p2.move_down()
self.p1.redraw()
self.p2.redraw()
self.root.after(10, self._animate)
def _set_bindings(self):
for char in ["w","s","o", "l"]:
self.root.bind("<KeyPress-%s>" % char, self._pressed)
self.root.bind("<KeyRelease-%s>" % char, self._released)
self.pressed[char] = False
def _pressed(self, event):
self.pressed[event.char] = True
def _released(self, event):
self.pressed[event.char] = False
class Paddle():
def __init__(self, canvas, tag, color="red", x=0, y=0):
self.canvas = canvas
self.tag = tag
self.x = x
self.y = y
self.color = color
self.redraw()
def move_up(self):
self.y = max(self.y -2, 0)
def move_down(self):
self.y = min(self.y + 2, 400)
def redraw(self):
x0 = self.x - 10
x1 = self.x + 10
y0 = self.y - 20
y1 = self.y + 20
self.canvas.delete(self.tag)
self.canvas.create_rectangle(x0,y0,x1,y1,tags=self.tag, fill=self.color)
if __name__ == "__main__":
p = Playfield()
p.start()
Tkinter는 게임 환경이 좋지 않을 수 있습니다. 파이 게임을 보셨나요? –
PyGame은 아직 Python 3.x에서는 작동하지 않습니다. 따라서 일반적인 Python 솔루션은 아니며 현재는 Python 3.x +로 이식하지 않는 한 장래에 많은 옵션이 없을 것입니다. 2.x에서 잘 작동합니다. – Shule