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
  • Monovertex Monovertex:
    How are you all? :D
    +1
  • Ghan Ghan:
    Howdy
  • Ghan Ghan:
    Still lurking
    +3
  • The Helper The Helper:
    I am great and it is fantastic to see you my friend!
    +1
  • The Helper The Helper:
    If you are new to the site please check out the Recipe and Food Forum https://www.thehelper.net/forums/recipes-and-food.220/
  • Monovertex Monovertex:
    How come you're so into recipes lately? Never saw this much interest in this topic in the old days of TH.net
  • Monovertex Monovertex:
    Hmm, how do I change my signature?
  • tom_mai78101 tom_mai78101:
    Signatures can be edit in your account profile. As for the old stuffs, I'm thinking it's because Blizzard is now under Microsoft, and because of Microsoft Xbox going the way it is, it's dreadful.
  • The Helper The Helper:
    I am not big on the recipes I am just promoting them - I use the site as a practice place promoting stuff
    +2
  • Monovertex Monovertex:
    @tom_mai78101 I must be blind. If I go on my profile I don't see any area to edit the signature; If I go to account details (settings) I don't see any signature area either.
  • The Helper The Helper:
    You can get there if you click the bell icon (alerts) and choose preferences from the bottom, signature will be in the menu on the left there https://www.thehelper.net/account/preferences
  • The Helper The Helper:
    I think I need to split the Sci/Tech news forum into 2 one for Science and one for Tech but I am hating all the moving of posts I would have to do
  • The Helper The Helper:
    What is up Old Mountain Shadow?
  • The Helper The Helper:
    Happy Thursday!
  • Varine Varine:
    Crazy how much 3d printing has come in the last few years. Sad that it's not as easily modifiable though
  • Varine Varine:
    I bought an Ender 3 during the pandemic and tinkered with it all the time. Just bought a Sovol, not as easy. I'm trying to make it use a different nozzle because I have a fuck ton of Volcanos, and they use what is basically a modified volcano that is just a smidge longer, and almost every part on this thing needs to be redone to make it work
  • Varine Varine:
    Luckily I have a 3d printer for that, I guess. But it's ridiculous. The regular volcanos are 21mm, these Sovol versions are about 23.5mm
  • Varine Varine:
    So, 2.5mm longer. But the thing that measures the bed is about 1.5mm above the nozzle, so if I swap it with a volcano then I'm 1mm behind it. So cool, new bracket to swap that, but THEN the fan shroud to direct air at the part is ALSO going to be .5mm to low, and so I need to redo that, but by doing that it is a little bit off where it should be blowing and it's throwing it at the heating block instead of the part, and fuck man
  • Varine Varine:
    I didn't realize they designed this entire thing to NOT be modded. I would have just got a fucking Bambu if I knew that, the whole point was I could fuck with this. And no one else makes shit for Sovol so I have to go through them, and they have... interesting pricing models. So I have a new extruder altogether that I'm taking apart and going to just design a whole new one to use my nozzles. Dumb design.
  • Varine Varine:
    Can't just buy a new heatblock, you need to get a whole hotend - so block, heater cartridge, thermistor, heatbreak, and nozzle. And they put this fucking paste in there so I can't take the thermistor or cartridge out with any ease, that's 30 dollars. Or you can get the whole extrudor with the direct driver AND that heatblock for like 50, but you still can't get any of it to come apart
  • Varine Varine:
    Partsbuilt has individual parts I found but they're expensive. I think I can get bits swapped around and make this work with generic shit though

      The Helper Discord

      Staff online

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top