簡體   English   中英

使用 graphics.py 和鍵盤,如何根據鍵盤輸入使角色移動?

[英]Using graphics.py and the keyboard, how can I make a character move based upon keyboard input?

我是一個非常初學者 python 編碼器,剛開始修改 graphics.py,所以請原諒我可能很糟糕的代碼。 我只想知道如何使用有效的鍵盤/圖形 function。 現在如果我運行它,它不會按照我想要的方式移動角色。 我希望能夠按下 WASD 鍵,並讓屏幕上的方塊移動。

from graphics import *
import keyboard

point1 = Point(680, 420)
point2 = Point(720, 380)


class Player:
    def __init__(self, char, window):
        self.p1 = char
        self.win = window

    def create_Player(self):
        self.p1.setFill(color_rgb(0, 255, 0))
        self.p1.draw(self.win)
        self.win.getMouse()
        self.win.close()

    def movement(self):
        global point1, point2
        if keyboard.is_pressed("d"):
            self.p1.move(10, 0)
        if keyboard.is_pressed("a"):
            self.p1.move(-10, 0)
        if keyboard.is_pressed("s"):
            self.p1.move(0, 10)
        if keyboard.is_pressed("w"):
            self.p1.move(0, -10)



p1 = Player(Rectangle(point1, point2), GraphWin("mini graphic game", 1400, 800))
p1.create_Player()
while True:
    p1.movement()

所有 GUI 都運行事件循環,該循環一直有效,直到您關閉 window 並且它會阻止其他元素,您必須學習如何使用此循環。

在您的代碼中,此循環位於self.win.getMouse()中,因此您的循環在關閉 window 后運行。

使用self.win.getMouse()中的代碼,我創建了自己的循環,它運行相同的元素和p1.movement() ,它使用self.win.lastKey來獲取最后單擊的鍵。 目前的問題是,即使您釋放該值,該值也會保留最后一個鍵,因此即使您不按鍵,object 也會移動。 它使用隱藏_onKey() ,這意味着onKeyPress但代碼也需要_onKeyRelease() 也許后來我做到了。

順便說一句:我檢查了graphics.py 源代碼以獲取這些信息。

from graphics import *
import time

# --- classes ---

class Player:
    def __init__(self, window, char):
        self.p1 = char
        self.win = window

    def create(self):
        self.p1.setFill(color_rgb(0, 255, 0))
        self.p1.draw(self.win)

    def movement(self):
        if self.win.lastKey == "d":
            self.p1.move(10, 0)
        if self.win.lastKey == "a":
            self.p1.move(-10, 0)
        if self.win.lastKey == "s":
            self.p1.move(0, 10)
        if self.win.lastKey == "w":
            self.p1.move(0, -10)

# --- main ---

point1 = Point(680, 420)
point2 = Point(720, 380)

win = GraphWin("mini graphic game", 1400, 800)

p1 = Player(win, Rectangle(point1, point2))
p1.create()

while not win.isClosed():
    p1.movement()

    win.update()
    time.sleep(.1)

win.close()

編輯:當您不按鍵時停止播放器的版本。 我添加了onKeyPressonKeyRelease以在self.keys["d"] = True/False中設置值,可用於運行和停止播放器。

我還添加了隨機移動的敵人。

from graphics import *
import time
import random

# --- classes ---

class Window(GraphWin):

    def __init__(self, title="Graphics Window",
                 width=200, height=200, autoflush=True):
        super().__init__(title, width, height, autoflush)

        self.bind_all("<KeyPress>",   self._onKeyPress)
        self.bind_all("<KeyRelease>", self._onKeyRelease)

        self.keys = dict() # dictionary for `keys[event.keysym] = True/False`

    def _onKeyPress(self, event):
        self.keys[event.keysym] = True

    def _onKeyRelease(self, event):
        self.keys[event.keysym] = False


class Player:
    def __init__(self, window, char, color):
        self.win = window
        self.rect = char
        self.color = color

        self.rect.setFill(self.color)
        self.rect.draw(self.win)

    def movement(self):
        # use `keys.get("d")` instead of `keys["d"]` because `"d"` may not exists in dictionary `key`
        if self.win.keys.get("d"):
            self.rect.move(10, 0)
        if self.win.keys.get("a"):
            self.rect.move(-10, 0)
        if self.win.keys.get("s"):
            self.rect.move(0, 10)
        if self.win.keys.get("w"):
            self.rect.move(0, -10)

class Enemy:
    def __init__(self, window, rect, color):
        self.win = window
        self.rect = rect
        self.color = color

        self.rect.setFill(self.color)
        self.rect.draw(self.win)

    def movement(self):
        dx = random.randint(-30, 30)
        dy = random.randint(-30, 30)
        self.rect.move(dx, dy)

# --- main ---

point1 = Point(680, 420)
point2 = Point(720, 380)

point3 = Point(180, 420)
point4 = Point(220, 380)

win = Window("mini graphic game", 1400, 800)

player = Player(win, Rectangle(point1, point2), color_rgb(0, 255, 0))
enemies = [Enemy(win, Rectangle(point3, point4), color_rgb(255, 0, 0)) for _ in range(10)]

while not win.isClosed():
    player.movement()
    for e in enemies:
        e.movement()

    win.update()
    time.sleep(.1)

win.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM