[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Simple board game GUI framework

On 11 September 2017 at 14:52, Christopher Reimer
<christopher_reimer at icloud.com> wrote:
>> On Sep 11, 2017, at 3:58 AM, Paul Moore <p.f.moore at gmail.com> wrote:
>> I'm doing some training for a colleague on Python, and I want to look
>> at a bit of object orientation. For that, I'm thinking of a small
>> project to write a series of classes simulating objects moving round
>> on a chess-style board of squares.
> I started something similar to this and didn't get far. I wrote a base class called Piece that had common attributes (I.e., color and position) and abstract methods (i.e., move). From the base class I derived all the piece types. That's the easy part.
> The board is a bit tricky, depending on how you set it up. The board of 64 squares could be a list, a dictionary or a class. I went with a Board class that used a coordinate system (i.e., bottom row first square was (0, 0) and top row last square (7, 7)) and kept track of everything on the board.

Thanks for the information. That's more or less the sort of thing I
was thinking of. In fact, from a bit more browsing, I found another
way of approaching the problem - rather than using pygame, it turns
out to be pretty easy to do this in tkinter.

The following code is basically the core of what I need:

import tkinter as tk

def create_board(root):
    board = {}
    for r in range(8):
        for c in range(8):
            lbl = tk.Button(bg="white", text="   ", font=("Consolas", 12))
            lbl.grid(row=r, column=c)
            board[r,c] = lbl
    return board

root = tk.Tk()
board = create_board(root)

That creates an 8x8 grid of white buttons. With this, I can make a
button red simply by doing

board[3,2]["bg"] = "red"

That's really all I need. With that I can place objects on the grid by
asking them for their colour and x/y co-ordinates. Add a bit of driver
logic, and I have a display system. We can then spend the time working
on how we add business logic to the classes (movement, collision
detection, etc...)

I really need to spend some time looking into tkinter. I very rarely
think of it when developing code, and yet whenever I do it's amazingly
easy to put together a solution quickly and easily.