2

I have a homework assignment to do and I really need a solution. I have been trying to do this since yesterday but I do not know how.

Program has to generate and print a letter or a number and then a user has to type it as quickly as possible and press ENTER. The game is over after 30 secs.

Well I do not know how to put time limit to a game. I was searching through stackoverflow and I did not find anything useful. Please help me.

**Here it is what I have done so far. I tried code from the answer by SYSS.STDER, but it does not quite work because when the 30 secs are over, the game should also be over, but here in this code the game is over when I type last character.

LOOP WILL NOT STOP UNTIL IT FINISHES AND WE DISCOVER THAT WE ARE PAST OUR DEADLINE. THE TASK NEEDS TO BE INTERRUPTED IN PROGRESS AS SOON AS THE TIME ELAPSES.

max_time =30
start_time = time.time()  # remember when we started
while (time.time() - start_time) < max_time:

    response = "a"      # the variable that will hold the user's response
    c = "b"             #the variable that will hold the character the user should type
    score = 0
    number = 0

    c = random.choice(string.ascii_lowercase + string.digits)
    print(c)
    number = number + 1

    response = input("Type a letter or a number: ") #get the user's response

    if response == c and (time.time() - start_time) < max_time:
         # if the response from the previous loop matches the character
         # from the previous loop, increase the score.
         score = score + 1
SunSparc
  • 1,812
  • 2
  • 23
  • 47
Miki
  • 65
  • 1
  • 2
  • 7
  • This is now better phrased than [the original](http://stackoverflow.com/q/13893099/923794). Still, since you already brought up the suggestion to try looping, the question remains: What have you tried so far to that regard? – cfi Dec 15 '12 at 15:37
  • Can anyone look at my code and help me please? – Miki Dec 16 '12 at 13:13
  • 1
    So apart from a tiny bit of re-factoring sys.stderr's answer - in the last 21 hours - what have you tried yourself to solve this? – Jon Clements Dec 16 '12 at 13:15
  • @ Jon Clements. I am new at python and I need quite a bit of help. Please can you solve this problem I have. I would really apreciate it. – Miki Dec 16 '12 at 13:24
  • Keep with this code base. The game will end only when there's a last character because `input` is blocking, that means it won't return until something is entered - so you could run it and not do anything for a few hours... Don't worry about that (short of using threading/polling you're stuck with it (and that's not homework level techniques). To kludge it - check at the time of incrementing the score that you're still below `max_time` – Jon Clements Dec 16 '12 at 13:33
  • @ Jon Clements. Well I corrected condition. But is there away that program ends and you do not have to input something? – Miki Dec 16 '12 at 13:49
  • @Miki: as @Jon Clements noted, getting around this problem requires a little more Python than you've probably covered. If you aren't already familiar with the `signal` module, then I wouldn't worry about it. This is what the "(After 30 seconds program should still offer to user to write a last letter/number but it can not be counted in results)" line was trying to tell you -- you don't have to interrupt `input()`, you simply have to make sure that if the user hits enter after 30 s the score doesn't count. I would instead start working on the parts of the question involving files. – DSM Dec 16 '12 at 14:13
  • @DSM not too sure about the file thing - I'd probably work on the statistics required next (while this bit of it is still fresh for the OP) and then at least if it's an incomplete assignment, it'll be self-contained and functional in one respect... – Jon Clements Dec 16 '12 at 14:22
  • @JonClements: sure, that'll work too, and you're probably right in that it has a better failure mode. – DSM Dec 16 '12 at 14:32
  • What OS are you using. A way to solve this is to be able to detect if the user has pressed a key or not, and doing that is OS dependent. – martineau Dec 16 '12 at 16:43
  • @martineau I am using Windows 7. Thank you very much! – Miki Dec 16 '12 at 19:00

4 Answers4

4

Here's my way to do it:

import string
import random 
import time   

response = "a"              # the variable that will hold the user's response
c = "b"                     #the variable that will hold the character the user should type
score = 0                   #the variable that will hold the user's score
start = time.time()         #the variable that holds the starting time
elapsed = 0                 #the variable that holds the number of seconds elapsed.
while elapsed < 30:         #while less than 30 seconds have elapsed  

    if response == c:       #if the response from the previous loop matches the character
        score += 1          #from the previous loop, increase the score.

    #c is a random character
    c = random.choice(string.ascii_lowercase + string.digits)
    print(c)               

    response = input("Type a letter or a number: ") #get the user's response

    elapsed = time.time() - start #update the time elapsed
Hoppo
  • 1,130
  • 1
  • 13
  • 32
bigblind
  • 12,539
  • 14
  • 68
  • 123
  • The OP's homework assignment is using Python 3, so `raw_input` has to be `input` instead, I think. – DSM Dec 15 '12 at 15:37
  • I'd have to check that, I'm curently using python 2.7, in which `ìnput` will evaluate the input whereas `raw_input` will give you the exact string the user entered. looking that up now. – bigblind Dec 15 '12 at 15:39
  • You're right, there's no `raw_input` in python 3. (http://docs.python.org/release/3.2.3/library/functions.html) – bigblind Dec 15 '12 at 15:43
0

Since you're using Windows you can use the msvcrt.kbhit function to check for keypresses inside timing loops:

import msvcrt #### windows only ####
import os
import random
import string
import time

max_time = 15

def readch(echo=True):
    "Get a single character on Windows"
    ch = msvcrt.getch()
    while ch in b'\x00\xe0': # special function key?
        msvcrt.getch()       # get keycode & ignore
        ch = msvcrt.getch()
    if echo:
        msvcrt.putch(ch)
    return ch.decode()

def elapsed_time():
    global start_time
    return time.time() - start_time

number = 0
score = 0
start_time = time.time()  # initialize timer

while elapsed_time() < max_time:
    c = random.choice(string.ascii_lowercase + string.digits)
    print(c, end='')
    number += 1
    print("Type a letter or a number: ", end='')

    while elapsed_time() < max_time:
        if not msvcrt.kbhit():
            time.sleep(0.1) # don't hog processor
        else:
            response = readch(echo=False) # get the user's response
            if response == c:
                print(response) # only print if correct
                score += 1
                break
    else:
        print()

print()
print("Time's up")
print("You go  {} out of {}:".format(score, number))
martineau
  • 119,623
  • 25
  • 170
  • 301
0

A sample program to exit prime number function when Time limit has exceeded.

import math

from time import time

start_time = time() max_time = 2

def prime(n):

    for i in range(2, int(math.sqrt(n))):
        if(time() - start_time) > max_time:
            return "TLE"
        if n % i == 0:
            return False
    return True

print(prime(3900000076541747077))

Sri436
  • 91
  • 1
  • 1
-4

use "timeit" module available in python for better result.