python中的个别按键错误

时间:2016-02-17 15:33:48

标签: python python-3.x tkinter

以下代码是一个python短跑游戏。它是作为我上一篇文章的答案发布的, @mango 你必须尽可能快地点击'a'和'd'来跑100米。但是,有一些错误......

1)如果您同时按住“a”和“d”,游戏将尽快完成并击败游戏点。

2)就像我在上一篇文章中一样,我想在这段代码中加入一个评分系统,但是,由于我的技能和python经验,不幸的是,我无法做到所以,并希望和建议。

非常感谢

上一个代码:

import msvcrt
import time
high_score = 50
name = "no-one"
while True:
    distance = int(0)
    print("\n--------------------------------------------------------------")
    print('\n\nWelcome to the 100m sprint, tap a and d rapidly to move!')    
    print('* = 10m')
    print("\n**Current record: " + str(high_score) + "s, by: " + name)
    print('\nPress enter to start')
    input()
    print('Ready...')
    time.sleep(1)
    print('GO!')
start_time = time.time()
while distance < 100:           
    k1 = msvcrt.getch().decode('ASCII')
    if k1 == 'a':
        k2 = msvcrt.getch().decode('ASCII')
        if k2 == 'd':
            distance += 1
            if distance == 50:
                print("* You're halfway there!")
                elif distance % 10 == 0:
                    print('*')
fin_time = time.time() - start_time
fin_time = round(fin_time,2)
print('Well done you did it in...'+str(fin_time))
if fin_time < high_score:
    print("Well done you've got a new high score ")
    name = input("Please enter your name : ")

这是我收到的反馈代码,我做了一些更改,但我正在努力解决之前列出的错误。

1)如果您同时按住“a”和“d”,游戏将尽快完成并击败游戏点。

2)就像我在上一篇文章中一样,我想在这段代码中加入一个评分系统,但是,由于我的技能和python经验,不幸的是,我无法做到所以,并希望和建议。

非常感谢

# these are the modules we'll need
import sys
import tkinter as tk

class SprintGame(object):
    # this represents the distance we'll allow our player to run
    # NOTE: the distance is in meters
    distance = 100
    # this represents the stride length of the players legs
    # NOTE: basically how far the player can travel in one footstep
    stride = 1.5
    # this represents the last key the user has pressed
    lastKey = ""
    # this represents wether or not the race has been completed
    completed = False
    # this function initiates as soon as the "sprint" variable is defined
    def __init__(self):
        # create the tk window
        self.root = tk.Tk()
        # set the tk window size
        self.root.geometry('600x400')
        # set the tk window title
        self.root.title("Sprinting Game")
        # bind the keypress event to the self.keypress handler
        self.root.bind('<KeyPress>', self.keypress)
        # center the window
        self.centerWindow(self.root)
        # insert the components
        self.insertComponents()
        # initial distance notice
        self.output("{0}m left to go!".format(self.distance))
        # start out wonderful game
        self.start()

    # this function centers the window
    def centerWindow(self, window):
        window.update_idletasks()
        # get the screen width
        width = window.winfo_screenwidth()
        # get the screen height
        height = window.winfo_screenheight()
        # get the screen size
        size = tuple(int(_) for _ in window.geometry().split('+')    [0].split('x'))
        # get the screen's dimensions
        x = (width / 2) - (size[0] / 2)
        y = (height / 2) - (size[1] / 2)
        # set the geometry
        window.geometry("%dx%d+%d+%d" % (size + (x, y)))

    # this function replaces the old text in the textbox with new text
    def output(self, text = ""):
        self.text.delete('1.0', tk.END)
        self.text.insert("end", text)

    # this function handles key presses inside the tkinter window
    def keypress(self, event):
        # get the key and pass it over to self.logic
        self.logic(event.char)

    # this function handles game logic
    def logic(self, key):
        # convert key to a lower case string
        key = str(key).lower()
        # let us know how far we've got left
        if key == "l":
            self.output("{0}m left to go!".format(self.distance))
        # restart the race
        if key == "r":
            # clear the output box
            self.text.delete('1.0', tk.END)
            # reset the distance
            self.distance = 100
            # reset the stride
            self.stride = 1.5
            # reset the last key
            self.lastKey = ""
            # set race completed to false
            self.completed = False
            # output restart notice
            self.output("The Race Has Been Restarted.")
        # don't bother with logic if race is completed
        if self.completed == True:
            return False
        # check if distance is less than or equal to zero (meaning the race is over)
        if self.distance <= 0:
            # set the "self.completed" variable to True
            self.completed = True
            # let us know we've completed the race
            self.output("Well done, you've completed the race!")
            # return true to stop the rest of the logic
            return True
        # convert the key to lower case
        key = key.lower()
        # this is the quit function
        if key == "q":
            # lights out...
            sys.exit(0)
        # check if the key is a
        if key == "a":
            # set the last key to a so that we can decrement the "distance"
            # variable if it is pressed next
            self.lastKey = "a"
        # only bother with "d" keypresses if the last key was "a"
        if self.lastKey == "a":
            # capture the "d" keypress
            if key == "d":
                # decrement the "distance" variable
                self.distance -= self.stride
                # let us know how far into the game we are
                self.output("{0}m left to go!".format(self.distance))

    # this function inserts the components into the window
    def insertComponents(self):
        # this component contains all of our output
        self.text = tk.Text(self.root, background='#d6d167',         foreground='#222222', font=('Comic Sans MS', 12))
        # lets insert out text component
        self.text.pack()

    # this function opens the window and starts the game
    def start(self):
        self.root.mainloop()

# create a new instance of the game
Game = SprintGame()

0 个答案:

没有答案