これは、現在動作しているPythonブラックジャックゲーム(または少なくともブラックジャックのようなゲーム)のコードのほとんどです。時間制限を実装する必要があると言われました(ユーザーは何かを入力するように求められ、与えるのに3秒ほどしかありません応答)。
def deck():
cards = range(1, 12)
return choice(cards)
def dealer():
total = deck() + deck()
if total <= 15:
totalf = total + deck()
while totalf <= 21:
return totalf
if total > 15:
return total
def player():
card1 = deck()
card2 = deck()
hand = card1 + card2
print "Cards dealt: %d and %d" % (card1, card2)
while hand <= 21:
choice = raw_input("Would you like to hit or stand?: ")
print choice
if choice == "hit":
hand = hand + deck()
print "Current Total: %d" % hand
elif choice == "stand":
return hand
money = 100
highscore = 0
while money > 0:
opp = dealer()
me = player()
if me > opp:
highscore = highscore + 10
money = money + 10
print "Winner, winner, chicken dinner! You have $%d!" % money
print "********************************************"
elif opp > 21:
highscore = highscore + 10
money = money + 10
print "Winner, winner, chicken dinner! You have $%d!" % money
print "********************************************"
elif me > 21:
money = money - 20
print "Bust! Dealer wins with %d. You have $%d reamaining." % (opp, money)
print "********************************************"
elif opp > me:
money = money - 20
print "Dealer wins with %d. You have $%d reamaining." % (opp, money)
print "********************************************"
elif me == 21:
highscore = highscore + 10
money = money + 10
print "Blackjack! You have $%d!" % money
print "********************************************"
sleep(1)
print "Thank you for playing! Your highscore was $%d." % highscore
これは私の教授がこれを行うために私たちに提供したコードです:
import sys, time
from select import select
import platform
if platform.system() == "Windows":
import msvcrt
def input_with_timeout_sane(prompt, timeout, default):
"""Read an input from the user or timeout"""
print prompt,
sys.stdout.flush()
rlist, _, _ = select([sys.stdin], [], [], timeout)
if rlist:
s = sys.stdin.readline().replace('\n','')
else:
s = default
print s
return s
def input_with_timeout_windows(prompt, timeout, default):
start_time = time.time()
print prompt,
sys.stdout.flush()
input = ''
while True:
if msvcrt.kbhit():
chr = msvcrt.getche()
if ord(chr) == 13: # enter_key
break
elif ord(chr) >= 32: #space_char
input += chr
if len(input) == 0 and (time.time() - start_time) > timeout:
break
if len(input) > 0:
return input
else:
return default
def input_with_timeout(prompt, timeout, default=''):
if platform.system() == "Windows":
return input_with_timeout_windows(prompt, timeout, default)
else:
return input_with_timeout_sane(prompt, timeout, default)
これら 2 つのコードをマージする方法が完全にわかりません。過去数時間、機能させるために試しましたが、何らかの理由で機能しません。どんな助けでも素晴らしいでしょう。(コードの壁についてお詫び申し上げます)。