Python - drawing a game board

master maste

New Member
Reaction score
32
Ok, I'm trying to draw a game board in python, here is my current code:

Code:
def draw_board(n_rows, n_cols):
    '''function to draw the board'''

    n_cols = int(n_cols)
    n_rows = int(n_rows)
    
    matrix = [[0 for x in range(n_cols)] for y in range(n_rows)]
    print matrix  #for testing purposes
    
    print "+-" *(n_cols) + "+"
    
    for x in matrix:
        print "|",
        print x,
        print "|"
        
    print "+-" *(n_cols) + "+"
    print "",
    
    for x in xrange(n_cols):
        print x,

draw_board(5, 3)

but at the moment it prints out like this:

Code:
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
+-+-+-+
| [0, 0, 0] |
| [0, 0, 0] |
| [0, 0, 0] |
| [0, 0, 0] |
| [0, 0, 0] |
+-+-+-+
  0 1 2
I want to have the 0's in their respective columns but can't for the life of me figure out/remember how to strip a list...

Heres the outcome I want:

+-+-+-+
| 0 0 0 |
| 0 0 0 |
| 0 0 0 |
| 0 0 0 |
| 0 0 0 |
+-+-+-+
0 1 2

(These should be lined up properly but the
Code:
 blocks refuse to do so, and so does the normal formatting, I'm sure you get the idea though :))

Would be awesome if anyone could give me a hint or something, I'm really lost for where to go next.

Thanks :eek: (long post)
 

Artificial

Without Intelligence
Reaction score
326
Instead of printing the list, you could print the elements of the list:
Code:
    for x in matrix:
        print "|",
[COLOR="Blue"][B]        for y in x:
            print y,[/B][/COLOR]
        print "|"

That'd give you "0 0 0 " instead of "[0, 0, 0] ".
 

master maste

New Member
Reaction score
32
Wow thankyou so much, you wouldn't guess what was in my comments that I removed from this post...:

Code:
#try out "for x in matrix: for y in x: print x" or something similar.

I was soo close, but after looking at the code for soo long it just left my head.

Ok, now a row on the board shows as:
Code:
| 0 0 0 |

should be:
|000|

so I've tried modifying it to run a for loop in the print statement or something similar, heres what I've got so far:

Code:
print "|" + "%s" % (y for y in x:print y) + "|"
It's spitting out errors but I'm unsure on how to run a for loop (if its even possible) inside a print statement (yes, I tried googling)
 

Artificial

Without Intelligence
Reaction score
326
I'm not sure if there's some cool way of doing this such as what you tried, but some other simple (and not so cool :p) ways come into my mind.

Instead of directly printing the strings, you could append them into one string and then print that so you wouldn't get the spaces in between (like print , does):
Code:
    for x in matrix:
        s = '|'
        for y in x:
            s += str(y)
        print s + '|'

Or you could use sys.stdout.write instead of print:
Code:
from sys import stdout
...
    for x in matrix:
        stdout.write("|")
        for y in x:
            stdout.write(str(y))
        print "|" # This one still uses print so a new line char will be appended.

Or if you were using python 3 (which I know you ain't, though, but just wanted to mention this because I think it's the nicest solution of these three):
Code:
    for x in matrix:
        print("|", end='')
        for y in x:
            print(y, end='')
        print("|")

Edit: Oh, one more way (rather nice IMO, especially since you want spaces between the numbers):
Code:
    for x in matrix:
        print '|' + ' '.join(map(str, x)) + '|'
 

master maste

New Member
Reaction score
32
Thanks, yea I'm using python 2.6 for studies, and I'm trying to stay away from things like stdout at the moment.

After a little bit of fixing its producing the correct output:
Code:
for x in matrix:
        s = "|"
        for y in x:
            s += str(y) + " "
       
        print s[:-1] + "|" #gets rid of the last space in the row

Thanks +rep
 

master maste

New Member
Reaction score
32
Ok, now I'm trying to iterate through my board to place a piece(number) for the users turn.

so far I have:
Code:
def turn(player):
    place_piece = raw_input("Enter your column for player %s: " % (player))
    place_piece = int(place_piece)
    
    giant_list = len(matrix)
    
    for i in matrix[::-1]:
        print i
        if i[place_piece] == 0:
            i[place_piece] = player
            
        else:
            print "Full column"

    draw_board(row_length, col_length)

But so far its putting the number in the right column but its filling up every row. Now I understand why this is happening but I'm having difficulty implementing it, also having the same problems with the "Full column" message printing for every single row instead of just once.

Basically its late and I need a fresh set of eyes :nuts:.

edit: just thinking wildly here would a for loop outside of the current for loop work? To check if there is.... mind just went blank
 

Artificial

Without Intelligence
Reaction score
326
> its filling up every row
Add a break statement after the row i[place_piece] = player.

> "Full column" message printing for every single row instead of just once.
Make the else cause an else cause for the for loop instead of for the if. An else cause for a for loop "is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement." (source)

So this'd be the for loop part:
Code:
    for i in matrix[::-1]:
        print i
        if i[place_piece] == 0:
            i[place_piece] = player
            break
    else:
        print "Full column"
 

master maste

New Member
Reaction score
32
Ok, trying to check some inputs for errors and have come across some problems

Code:
def num_rows():
    row_len = raw_input("num rows: ")
    error_checker(row_len)
    return row_len



def error_checker(prompt):
    if prompt.isdigit():
        return prompt
            
    else:
        num_rows()
            

            
testing_rows = num_rows()
print "final outcome is: %s" % testing_rows

I've rewritten this 3 times today and this is the best its been.
Heres the output:
Code:
num rows: hello
num rows: test
num rows: hmmm?
num rows: 5
final outcome is: hello

final outcome should be 5, the only digit, if its not a digit then it keeps asking till you enter one.

When debugging for some reason once it hits the return statement it goes back to:
Code:
else:
        num_rows()
and then proceeds to return the original prompt, which completely baffles me.

Any ideas? I feel soo noobish atm.
 

Artificial

Without Intelligence
Reaction score
326
You ought to set the return value or error_checker to row_len, otherwise row_len's value ain't gonna change. ^_^ And similarily in error_checker you should return num_rows()'s value or it ain't gonna get returned.

Code:
def num_rows():
    row_len = raw_input("num rows: ")
    [color=red]row_len =[/color] error_checker(row_len)
    return row_len

def error_checker(prompt):
    if prompt.isdigit():
        return prompt
    else:
        [color=red]return[/color] num_rows()
 

master maste

New Member
Reaction score
32
Ok, after testing I can see it works. No idea why though surely when you set row_len to error_checker its going to overwrite the original.

Now that I think about it, its starting to make more and more sense, I originally tried to return error_checker in num_rows :p

Thanks for that.
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top