Reputation: 11
I'm currently doing a random card game project, the program should show 5random cards to the user, (first question): I dont get how to random a list of letters and heres my code:
def play():
hand = ["A","2","3","4","5","6","7","8","9","T","J","Q","K"]
for i in range(len(hand)):
card = random.choice[{hand},4]
print "User >>>> ",card
return card
Second question: If the user wants to change the position of the card . the user should type in the no. of position change, then the program should change the card randomly. for example : AJ891, user typed: 1 , --> A2891. what should I do? Here's my original code but it doesn't work out
def ask_pos():
pos_change = raw_input("From which position (and on) would you want to change? (0 to 4)? ")
while not (pos_change.isdigit()):
print "Your input must be an integer number"
pos_change = raw_input("From which position (and on) would you want to change? (0 to 4)? ")
if (pos_change > 4) :
print "Sorry the value has to be between 0 and 4, please re-type"
pos_change = raw_input("From which position (and on) would you want to change? (0 to 4)? ")
return pos_change
hand = ["A","2","3","4","5","6","7","8","9","T","J","Q","K"]
for i in range(len(hand)):
card = random.choice[{hand},4]
new = random.choice[{hand},1]
for i in range(len(card)):
if (card[i] == pos_change):
card = card + new
return card
Upvotes: 0
Views: 952
Reputation: 5276
1)
random.choice[{hand},4]
That won't work, bad syntax error. Also choice won't do the trick, sample is what you want:
random.sample(hand, 5)
2)
pick = random.sample(hand, 5)
change = 2 # Entered by the user
pick[change] = random.choice([x for x in hand if x not in pick])
Upvotes: 2
Reputation: 60014
To answer your first question:
import random
hands = ["A","2","3","4","5","6","7","8","9","T","J","Q","K"]
def play():
cards = random.sample(hands,5)
print "User >>>> ", cards
return cards
random.choice[{hand},4]
should result in a syntax error. Firstly, calling functions you use parenthesis ()
and not brackets []
. Also, I don't see why you need to put braces {}
around hand, as it's already a list so nothing needs to be done.
I re-wrote your second question:
def ask_pos(hand):
while 1:
pos_change = raw_input("From which position (and on) would you want to change? (0 to 4)? ")
if int(pos_change) < 0 or int(pos_change) > 4:
continue
else:
break
hand[int(pos_change)] = random.choice(hands)
return hand
When run:
>>> myhand = play()
User >>>> ['6', '8', 'A', '9', '4']
>>> ask_pos(myhand)
From which position (and on) would you want to change? (0 to 4)? 0
['Q', '8', 'A', '9', '4']
Upvotes: 1
Reputation: 21
You could use random.randrange(number), and then pull out the index at that position.
Upvotes: 0