vendredi 27 octobre 2017

Python index of a random number in a list?

So I've looked for help elsewhere but couldn't find any solution. I've created a list with 51 elements and would like to pick 10 random, different positions within that list and be able to change the value at those positions(you can see this under the assignCard(person) function). Since I am using the index of the numbers I can't use methods such as random.sample or put the random numbers into a set() because I get an error message. Ive posted my code below, feel free to copy and run it to view the output, everything works except for the repeating numbers so if possible please do not change the code drastically in your answer. Thanks.

""" cardGame.py
    basic card game framework
    keeps track of card locations for as many hands as needed
"""
from random import *
import random

NUMCARDS = 52
DECK = 0
PLAYER = 1
COMP = 2

cardLoc = [0] * NUMCARDS
suitName = ("hearts", "diamonds", "spades", "clubs")
rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", 
            "Eight", "Nine", "Ten", "Jack", "Queen", "King")
playerName = ("deck", "player", "computer")

def main():
  clearDeck()

  for i in range(5):
    assignCard(PLAYER)
    assignCard(COMP)

  print(cardLoc)

  print("#  " + " card      " + " location")
  showDeck()
  print("\nDisplaying player hand:")
  showHand(PLAYER)
  print("\nDisplaying computer hand:")
  showHand(COMP)

def clearDeck():
    cardLoc = [0] * NUMCARDS

def assignCard(person):
  x = random.randint(0, 51)
  cardLoc[x] = person

def showDeck():
  for i in range(NUMCARDS):
    y = rankName[i % 13]
    z = suitName[int(i / 13)]
    a = cardLoc[i]
    b = playerName[a]
    print("{:<4}{:<4} of {:<14}{:<7}".format(str(i), y, z, b))

def showHand(person):
  for i in range(NUMCARDS):
    if cardLoc[i] == person:
      print(rankName[i % 13] + suitName[int(i / 13)])

main()




Aucun commentaire:

Enregistrer un commentaire