A
A
Azamgl2021-12-05 18:10:16
Python
Azamgl, 2021-12-05 18:10:16

How to humanly find the desired element in the list?

import random

a1,a2,a3,b1,b2,b3,c1,c2,c3 = ' ',' ',' ',' ', ' ',' ',' ',' ',' '
search=[a1,a2,a3,b1,b2,b3,c1,c2,c3]

def Board():
    print(a3 + '|' + b3 + '|' + c3)
    print('-+-+-')
    print(a2 + '|' + b2 + '|' + c2)
    print('-+-+-')
    print(a1 + '|' + b1 + '|' + c1)
    print('-+-+-')

#кто ходит первым
if random.randint(1,2)== 1:
    print('Крестики в этом раунде у первого игрока.')
else:
    print('Крестики в этом раунде у второго игрока.')

m1 = input('Введите поле, куда вы ставите свой знак: ')


In my game of tic-tac-toe, I assigned a space to each cell. However, when the player actually needs to choose where to put a cross or a zero, he selects a cell by its number, and when and when I do something like search.index('a1') of course this is wrong because a1=' '. How to find this element and change its space to x. I feel like the answer is going to be super easy, but oh my god I can't find it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-12-05
@Azamgl

Do you want to specify a cell like in a naval battle, a1-b3?
Then work separately for rows and columns, it will be easier.

field = [
  [' ', ' ', ' '],
  [' ', ' ', ' '],
  [' ', ' ', ' '],
]
#обращение к ячейке будет таким: field[1][1] 

columns = ['1', '2', '3'] #обозначения столбцов
rows = ['a', 'b', 'c'] #обозначения строк

def cell2index(cell):
  # превращаем строку вида b1 в индексы в списке
  row = rows.index(cell[0].lower()) #если номера строки нет, вылетит исключение ValueError
  col = columns.index(cell[1]) #если номера столбца нет, вылетит исключение ValueError
  return row, col #возвращаем кортеж - пару значений

# пример работы - ход крестиков
while True: #повторяем, пока пользователь не введет правильный номер
  cell = input('Введите ячейку для хода: ')
  try:
    r, c = cell2index(cell) #если номер неверный, тут вылетит исключение ValueError
    if field[r][c] != ' ': #ячейка уже занята?
      print('Ячейка уже занята!')
    else:
      break #если исключения не было, выходим из цикла
  except ValueError:
    print('Номер ячейки неправильный')
#сюда попадём только если номер ячейки правильный и она свободна
field[r][c] = 'x'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question