vendredi 7 septembre 2018

Python check if number is already in list which is a value inside of a dictionary and if it is regenerate until it is different - syntax error

I am trying to generate unique coordinates for ships in a battleships game. I tried a lot of things but either I get a syntax error or a out of range. I realised that:

my_dict = {key : [1, 2, 3], key2 : [4, 5, 6]
x = 2
print(mydict['key'][x - 1]

Will not give me no1 index. My code snippet is here:

from random import *
board = []

for x in range(0, 10):
  board.append(["O"] * 10)


ships = {
'shiprows': [0],
'shipcols' : [0]
}

def random_row1(board):
  return randint(0, len(board) - 1)

def random_col1(board):
 return randint(0, len(board) - 1)

vars = 0
temp = 0
for vars in range(0, 5):
  print(vars)
  if len(ships['shiprows']) >= 2 and len(ships['shipcols']) >= 2:
    temp = vars - 1
    if ships['shiprows'][temp] in ships['shiprows'] and ships['shipcols'[temp] in ships['shipcols']:
      print("if loop")

    ships['shiprows'].append(random_row1(board))
    ships['shipcols'].append(random_col1(board))
  else:
    ships['shiprows'].append(random_row1(board))
    ships['shipcols'].append(random_col1(board))
    vars = vars + 1
  print(ships)

The code is just in debugging state - I am trying to get the numbers to go into said dodgy if loop and be re-generated until they are unique to their lists.

I am a beginner, so if I have made an obvious slip up please don't judge. Thanks

Aucun commentaire:

Enregistrer un commentaire