在 Turtle Graphics 中綁定多個按鍵
在遊戲開發中,協調使用者輸入需要可靠的按鍵綁定技術。本文介紹如何在海龜圖形中將多個按鍵綁定在一起,從而在按下某些組合時啟用複雜的操作。
問題陳述:
建立一個連接-點 Python 遊戲,其中:
初始方法:
以下程式碼代表初步嘗試:
import turtle flynn = turtle.Turtle() win = turtle.Screen() win.bgcolor("LightBlue") flynn.pensize(7) flynn.pencolor("lightBlue") win.listen() def Up(): flynn.setheading(90) flynn.forward(25) def Down(): flynn.setheading(270) flynn.forward(20) def Left(): flynn.setheading(180) flynn.forward(20) def Right(): flynn.setheading(0) flynn.forward(20) def upright(): flynn.setheading(45) flynn.forward(20) win.onkey(Up, "Up") win.onkey(Down,"Down") win.onkey(Left,"Left") win.onkey(Right,"Right")
挑戰:
上面的程式碼不會同時註冊多個按鍵。例如,按向上和向右只會執行按下的第二個鍵的操作。
替代方案:
由於 onkeypress() 的限制,替代方案需要採取方法。在此解決方案中,按鍵記錄在清單中,計時器會定期檢查註冊的組合併執行適當的操作。
from turtle import Turtle, Screen win = Screen() flynn = Turtle('turtle') def process_events(): events = tuple(sorted(key_events)) if events and events in key_event_handlers: (key_event_handlers[events])() key_events.clear() win.ontimer(process_events, 200) def Up(): key_events.add('UP') def Down(): key_events.add('DOWN') def Left(): key_events.add('LEFT') def Right(): key_events.add('RIGHT') def move_up(): flynn.setheading(90) flynn.forward(25) def move_down(): flynn.setheading(270) flynn.forward(20) def move_left(): flynn.setheading(180) flynn.forward(20) def move_right(): flynn.setheading(0) flynn.forward(20) def move_up_right(): flynn.setheading(45) flynn.forward(20) def move_down_right(): flynn.setheading(-45) flynn.forward(20) def move_up_left(): flynn.setheading(135) flynn.forward(20) def move_down_left(): flynn.setheading(225) flynn.forward(20) key_event_handlers = { \ ('UP',): move_up, \ ('DOWN',): move_down, \ ('LEFT',): move_left, \ ('RIGHT',): move_right, \ ('RIGHT', 'UP'): move_up_right, \ ('DOWN', 'RIGHT'): move_down_right, \ ('LEFT', 'UP'): move_up_left, \ ('DOWN', 'LEFT'): move_down_left, \ } key_events = set() win.onkey(Up, "Up") win.onkey(Down, "Down") win.onkey(Left, "Left") win.onkey(Right, "Right") win.listen() process_events() win.mainloop()
此解決方案有效解決了該問題,允許同時註冊多個按鍵.
以上是如何在 Turtle Graphics 中綁定多個按鍵以執行複雜的操作?的詳細內容。更多資訊請關注PHP中文網其他相關文章!