vojislav
vojislav

Reputation: 3

How to randomly choose between options without choosing the same option again?

I'm making a Battleship knock-off in Python and I writing a part where the game, based on the length, tells you the name of the ship. The problem is that when the length of the ship is 3, according to traditional Battleship rules, it can be either a Submarine or a Cruiser. I thought I could just use random.choice(), but I run the risk of getting the same choice twice. My question is what is the best way to do this. Like maybe a way to get one choice the first time and the other one the second. Or a way like something in the title. Any help would be appreciated.

This is the code. The above-mentioned problem begins at line 39. You probably didn't need the entire code, but better safe than sorry. Btw sorry if the code is an eye-sore, I'm just starting out with Python.

Upvotes: 0

Views: 101

Answers (1)

JoshG79
JoshG79

Reputation: 1687

Create a list with all the unique possible options, then use random.shuffle to put it in a random order. Then you can pop one element off the top as needed.

import random
ships = ['sub','cruiser']
random.shuffle(ships)
first = ships[0]
second = ships[1]

Upvotes: 4

Related Questions