0

I am creating Connect 4 in Python. I am new to programming. I have created a board using the below code

row = 6

col = 7

board = [[' ']*col for i in range(row)]

for x in board:
    print(x)

How can I place a counter in one of the columns and have it goes to the last row? For example, placing it in column 1 will go to x:y index [5:1].

I will be doing this game in OOP, but for now I just want to get a working game.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Sam
  • 1
  • 4
  • 2
    Well, forget lists of lists for a moment. Given a list (that's not empty), how do you get at its last element? –  Dec 30 '16 at 19:07
  • 1
    You may find it easier to represent the state of a Connect 4 board as a list of columns, rather than a list of rows. – Chris Martin Dec 30 '16 at 19:19
  • Thanks for the response! I'm pretty new to programming, how would i represent the list as columns @ChrisMartin – Sam Dec 30 '16 at 19:32
  • `board = [[' ']*row for i in range(col)]`. You can also [transpose](https://stackoverflow.com/questions/6473679/transpose-list-of-lists) the structure when you want it the other way (such as for printing it). – Chris Martin Dec 30 '16 at 19:35

3 Answers3

0

If you use the function len(mylist) it will return the length of mylist. Thus use len(mylist)-1 to get the index for the last element because lists are 0 index.

Saxman13
  • 3
  • 2
0

The following will put an X in the third position of the last row:

row = 6

col = 7

board = [[' ']*col for i in range(row)]

for x in board:
    print(x)
print(board)

board[-1][2] = 'X'
print(board)

In Python, the list[-1] syntax identifies the last element in a list. list[-2] the second to last, etcetera. The position in the list is referred to as the index.

Also, remember that Python considers the first element to be list[0], so that in this case, board[-1] is the index of the last list in board, and board[-1][2] is the index of 3rd element of that list.

So what we're doing here is placing an X in the element with index 2, in the list with index -1.

Hope this helps.

Chris Larson
  • 1,684
  • 1
  • 11
  • 19
0

You can access and change the last row [-1] and first column [1] this way:

board[-1][1] = counter

You might want to try the module numpy and change counter to an int value if required. A move by player two would be:

import numpy as np
board =  np.zeros((6, 7))
board[-1][1] = 2
petruz
  • 545
  • 3
  • 13