Generate random non repeating samples from an array of numbers

2024/10/5 14:51:57

I made a battleships game and I now need to make sure that the computer doesn't attack at the same spot twice.

My idea of it is storing each shot's co-ordinates in a variable which gets added to whenever there is a new shot and then I just have to check and make it check if the current shot is in the variable.

This is the code I have for shooting:

if playerNumber == "1":eg.msgbox("Player " + str(playerNumber) + " your shot.")hit=FalseshotX=eg.enterbox("Enter the x-coordinate for your shot (1-5): ")shotY=eg.enterbox("Enter the y-coordinate for your shot (1-5): ")else:eg.msgbox("The computer will now attack!")hit=FalseshotX=str(random.randint(1,5))shotY=str(random.randint(1,5))eg.msgbox ("The computer shot at " + str(shotX) + ", " + str(shotY) + "")

My idea of making sure the computer chooses something that isn't in the list is using a loop where it keeps choosing a shot until the one it chooses hasn't been chosen already.

The actual code that makes the computer fire his shot is:

hit = haveShot("2", p1ship1, p1ship2 , player2Board)if hit:p2 = p2 + 1eg.msgbox("The Computer has " + str(p2) + " points and Player 1 has " + str(p1) + " points")if p2 == 2:    eg.msgbox("Unlucky, The computer won. Press enter to continue")if platform.system() == "Windows": # ONLY PLAY SOUNDS IF ON WINDOWS OSfinish()break

Thanks!

Answer

I first answer in a language agnostic way.

A very efficient way would be to keep a sequential list of all the possible positions (in your case 5x5=25 positions), use a single random choice in that list and then removes the position from the list. This saves you from the what to do when I hit a position I've already hitted

Python implementation :

First generate the list of positions :

positions = [ (i, j) for i in range(1,6) for j in range(1,6) ]

Then get a random position and remove it from the list

index = random.randrange(len(positions))
shotX, shotY = positions[index]
del positions[index]

Edit :

As a prove it should fork :

>>> import random
>>> positions = [ (i, j) for i in range(1,6) for j in range(1,6)]
>>> for i in range(25):index = random.randrange(len(positions))print positions[index]del positions[index](5, 5)
(5, 4)
(1, 4)
(1, 2)
(3, 3)
(1, 1)
(4, 1)
(4, 4)
(5, 1)
(4, 2)
(2, 2)
(2, 4)
(2, 3)
(2, 1)
(3, 2)
(3, 5)
(1, 5)
(5, 3)
(5, 2)
(4, 3)
(4, 5)
(1, 3)
(3, 4)
(2, 5)
(3, 1)
>>> print positions
[]
https://en.xdnf.cn/q/120501.html

Related Q&A

How to get back fo first element in list after reaching the end? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 5 years ago.Improve…

Collision detection on the y-axis does not work (pygame)

I am trying to get the collision detection in my code to work. I am using vectors and I want the player sprite to collide and stop when it collides with a sprite group called walls. The problem is that…

Search for string within files of a directory

I need help writing a light weight Python (v3.6.4) script to search for a single keyword within a directory of files and folders. Currently, I am using Notepad++ to search the directory of files, altho…

Extract parent and child node from python tree

I am using nltks Tree data structure.Below is the sample nltk.Tree.(S(S(ADVP (RB recently))(NP (NN someone))(VP(VBD mentioned)(NP (DT the) (NN word) (NN malaria))(PP (TO to) (NP (PRP me)))))(, ,)(CC an…

Click button with selenium and python

Im trying to do web scraping with python on and Im having trouble clicking buttons. Ive tried 3 different youtube videos using Xpath, driver.find_element_by_link_text, and driver.find_element. What am …

Combinations of DataFrames from list

I have this:dfs_in_list = [df1, df2, df3, df4, df5]I want to concatenate all combinations of them one after the other (in a loop), like:pd.concat([df1, df2], axis=1) pd.concat([df1, df3], axis=1) p…

Python: iterate through dictionary and create list with results

I would like to iterate through a dictionary in Python in the form of:dictionary = {company: {0: apple,1: berry,2: pear},country: {0:GB,1:US,2:US} }To grab for example: every [company, country] if coun…

Jira Python: Syntax error appears when trying to print

from jira.client import jiraoptions = {server: https://URL.com} jira = JIRA(options, basic_auth=(username, password))issues = jira.search_issues(jqlquery) for issue in issues:print issueI want to print…

Matplotlib plt.xlim([x_min,x_max]), list object not callable

I want to plot a scatterplot, but set the x-label limits.axScatter = plt.subplot(111) axScatter.scatter(x=mean_var_r["Variance"],y=mean_var_r["Mean"]) xlim = [-0.003, 0.003] plt.xli…

Map column birthdates in python pandas df to astrology signs

I have a dataframe with a column that includes individuals birthdays. I would like to map that column to the individuals astrology sign using code I found (below). I am having trouble writing the code …