Hello

This is like my 4th week using Python and I'm still not familiar with it so I might need some help from you guys.

I gotta write a little Connect 4 game in Python, I just got started and boom - I'm stuck!

I tried to create a board for the game using two lists. Here is how far I got:

def board():
        fielda = []
        fieldb = []
        rows = int(raw_input('Height '))
        columns = int(raw_input('Width '))

        if rows < 4:
                rows = 4
        if columns < 4:
                columns = 4

        for i in range(columns):
                fieldb.append('-')
        for i in range(rows):
                fielda.append(fieldb)

        print fielda

board()

It gives out the following if you type in 5 for 'Height' and 4 for 'Width'
[['-', '-', '-', '-'], ['-', '-', '-', '-'], ['-', '-', '-', '-'], ['-', '-', '-', '-'], ['-', '-', '-', '-']]

but I want it to be like this

[,
,
,
,
]

Is there any way to handle this?
I'll appreciate any help.

Thanks in advance

Dani AI

Generated

Nice start, . One subtle bug in your board builder: each row points at the same list object. Because you append the same fieldb multiple times, changing one cell will appear in every row. Create a new row each time instead (or rows will be aliases of one another).

def make_board(rows, cols, fill='-'):
    rows = max(4, rows)
    cols = max(4, cols)
    # fresh list per row
    return [[fill for _ in range(cols)] for _ in range(rows)]

’s print approach is fine. If you want a compact display, join the characters per row. This also makes it easy to swap '-' for 'X'/'O'. The standard Connect 4 grid is 6 rows by 7 columns.

def show(board):
    for row in board:
        print ' '.join(row)

b = make_board(6, 7)
show(b)

Next step is "gravity": dropping a piece into a column from the bottom up. This lets you test your board before writing win detection.

def drop(board, col, token):
    if not (0 <= col < len(board[0])):  # bad column
        return False
    for r in range(len(board) - 1, -1, -1):  # bottom to top
        if board[r][col] == '-':
            board[r][col] = token
            return True
    return False  # column is full

Tip: avoid [['-']*cols]*rows for the same aliasing reason. And if you later move to Python 3, use input() and print(...) instead of raw_input and bare print.

Recommended Answers

All 5 Replies

The best solution I know of is to print out each thing manually. Example:

for row in fielda:
	for spot in row:
		print spot,
	print

Wow, that was fast, thanks. It works perfectly but umm ... what does your code actually do? I don't get through it - any comments maybe?

Member Avatar for Member #562630

Wow, that was fast, thanks. It works perfectly but umm ... what does your code actually do? I don't get through it - any comments maybe?

well best way to understand it is to hand-execute it :)

for row in fielda:
    for spot in row:
	print spot,
    print

so, the first row in fielda is row = [ "-", "-", "-", "-", "-" ]
going in the second loop: the first spot in it is "-", therefore it prints "-" and remains on the same line because of the ","( comma ) after the print statement. So if loops over every "-" in the row and prints it. When it gets to the point that no more elements are left, exits the loop and uses 'print' to go to the next line of the output. Since there are no other statements in the body of the outer for loop, it continues to the second row and so on...

Hope this makes it clearer :)

I'm sorry, I didn't comment it because I saw you use some of the code in your project and just assumed things, but here's what it does.

Whenever you have for obj in container: , python does the for loop once for each obj that's in container.

someList = [1,2,3]
for i in range(3):
	print someList[i]

...is the same as...

someList = [1,2,3]
for num in someList:
	print num

When I did for row in fielda: , that did the for loop once for each list inside the list fielda, and referred to that inner list as row. When I did for spot in field: , that did the for loop once for each character inside the list row, and referred to that character as spot. Notice my names are intuitive. Row refers to a row on your board, and spot refers to a spot on your board. print spot, prints out the character spot, then doesn't end the line because of the comma. print on the next line makes sure to start a new line for each new row.

Alrighty then - I got it.

Thank you very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.