Python键盘。侦听器块程序正在运行

2022-05-21 08:29:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,所以我尝试制作简单的游戏来学习它。我有一个index.py文件,它用文件test/game\u cyrcles.py加载模块测试,其中有一些方法可以在画布上移动对象。Main file index.py在具有主循环的模块文件中调用Main方法gameStart()。在我尝试实现键盘之前,一切都很顺利。监听器捕捉到了箭头按键事件。此侦听器完全阻止主循环,只有按键在工作。代码如下:

import tkinter
import time
import random
#import keyboard
#import click
from pynput import keyboard


run = True
speed = 1
playerSize = 75
enemySize = 75

current = set()


def onKeyPress(key):
    print(key)


def onKeyRelease(key):
    print(key)

# This line completely block gameStart() method
with keyboard.Listener(on_press=onKeyPress, on_release=onKeyRelease) as listener:
    listener.join()


def initCanvas(width=900, height=600, bg='light gray'):
    window = tkinter.Tk()
    canvas = tkinter.Canvas(window, width=width, height=height, bg=bg)
    canvas.pack()
    return canvas


def initPlayer(canvas):
    global playerSize
    return canvas.create_oval(800, 0, 800 + playerSize, playerSize, fill="green")


def initCircles(canvas):
    global enemySize
    cyrcles = [canvas.create_oval(-100, -100, -100 + enemySize, -100 + enemySize, fill='red') for c in range(0, 5)]
    for cId in cyrcles:
        setRandomPosition(canvas, cId)
    return cyrcles


def moveCyrcles(canvas, cyrcles, playerId):
    pCoords = canvas.coords(playerId)
    for cId in cyrcles:
        canvas.move(cId, 5, 0)
        coords = canvas.coords(cId)
        checkCollision(coords, pCoords, canvas)
        if coords[0] > 900:
            setRandomPosition(canvas, cId)


def checkCollision(coords, pCoords, canvas):
    if (coords[0] < pCoords[0] < coords[2]) \
            and ((coords[1] < pCoords[1] < coords[3]) or (coords[3] > pCoords[3] > coords[1])):
        gameOver(canvas)


def setRandomPosition(canvas, cId):
    global enemySize
    x = random.randint(-800, 0)
    y = random.randint(0, 800)
    canvas.coords(cId, x, y, x + enemySize, y + enemySize)


def setPlayerPosition(canvas, pId):
    print('key press')
    canvas.move(pId, 0, 20)


def gameOver(canvas):
    global run
    run = False
    canvas.create_text(450, 250, fill="red", text='GAME OVER', font="Arial 50 bold")


def gameStart():
    global run
    global speed
    canvas = initCanvas()
    playerId = initPlayer(canvas)
    cyrcles = initCircles(canvas)

    i = 0
    while run:
        moveCyrcles(canvas, cyrcles, playerId)
        time.sleep(.01 * speed)
        canvas.update()
        i += 1
        if i % 10000 == 0:
            speed = speed / 2
            i = 0

    i = 0
    while i < 5000:  # This is game over moment
        time.sleep(.01)
        i += 1

添加事件侦听器以便gameStart()方法运行的正确方法是什么?谢谢


Tags: 方法keyrunimportdefcoordsglobalcanvasspeedcidplayersizepcoordsgamestartenemysizecyrcles