Python问题,试图成为一个简单的死亡计数器

时间:2014-10-27 10:11:53

标签: python pygame

新进入python / pygame。试图为我的抽搐流做一个死亡计数器。

我最终会让它使用GUI,但是现在我只想让它在后台运行,并且从1键的按键输入为文件中的数字添加+1。 2将该数字重置为0。

在第19行获取错误。

  File "C:/Python27/Deathcounter.py", line 19, in <module>
    if event.key == pygame.K_1:
AttributeError: event member not defined

另外,我确定我一如既往地过度复杂化了这个过程。我

# Death Counter
import pygame, sys
import pygame.locals

# Variables
deathcount = float(0)

pygame.init()
BLACK = (0,0,0)
WIDTH = 320
HEIGHT = 260
windowSurface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)

windowSurface.fill(BLACK)

while True:
    events = pygame.event.get()
    for event in events:
        if event.key == pygame.K_1:
            with open("deathcounter.txt", "rt") as in_file:
                deathcount = in_file.read()
                deathcount = deathcount + 1
            with open("deathcounter.txt", "wt") as out_file:
                out_file.write(deathcount)
        if event.key == pygame.K_2:
            deathcount = 0
            with open("deathcounter.txt", "wt") as out_file:
                out_file.write(deathcount)

pass
if event.type == QUIT:
    pygame.quit()
    sys.exit()

感谢您的建议/帮助。

1 个答案:

答案 0 :(得分:0)

并非所有事件都有关键属性,这就是您收到此错误的原因。

同样第一次打开文件进行阅读时,这个文件不存在,所以会引发异常。

# Death Counter
import pygame
import sys
import pygame.locals

# Variables
deathcount = float(0)

pygame.init()
BLACK = (0, 0, 0)
WIDTH = 320
HEIGHT = 260
windowSurface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)

windowSurface.fill(BLACK)

while True:
    events = pygame.event.get()
    for event in events:
        if hasattr(event, 'key'):
            if event.key == pygame.K_1:
                try:
                    with open("deathcounter.txt", "r") as in_file:
                        deathcount = int(in_file.read())
                        deathcount = deathcount + 1
                except (IOError, ValueError), err:
                    print err
                    deathcount = 0
                with open("deathcounter.txt", "w") as out_file:
                    out_file.write(str(deathcount))
            if event.key == pygame.K_2:
                deathcount = 0
                with open("deathcounter.txt", "w") as out_file:
                    out_file.write(str(deathcount))

pass
if event.type == pygame.event.QUIT:
    pygame.quit()
    sys.exit()

对于信息,使用PyGame来捕获背景中的键并不是一个好用的fw,因为它要求pygame窗口具有活动焦点。所以如果你正在使用windows,我建议你看看这个使用PyHook的例子:https://www.daniweb.com/software-development/python/threads/229564/python-keylogger,否则在linux上,看看python x11库