magic_square.py

Created by valmontechno

Created on June 09, 2024

2.26 KB


import kandinsky as kd
import ion

order = 5
colored = True

def magicSquare():
    square = [[None] * order for _ in range(order)]

    x = order // 2
    y = x + 1

    for i in range(1, order ** 2 + 1):
        square[y][x] = i
        x = (x + 1) % order
        y = (y + 1) % order
        if square[y][x] != None:
            x = (x - 1) % order
            y = (y + 1) % order

    return square

def drawSquare(square):
    offsetX = 160 - order*15
    offsetY = 111 - order*15
    squareMax = order ** 2
    kd.fill_rect(0, 0, 320, 222, '#ffffff')
    kd.fill_rect(offsetX -1, offsetY -1, order*30 +1, order*30 +1, '#555555')
    for i in range(order):
        for j in range(order):
            text = str(square[i][j])
            if colored:
                q = square[i][j] / squareMax
                color = (255*q, 181*q, 49*q)
            else:
                color = '#ffffff'
            kd.fill_rect(offsetX + j*30, offsetY + i*30, 30, 30, '#555555')
            kd.fill_rect(offsetX + j*30, offsetY + i*30, 29, 29, color)
            kd.draw_string(text, offsetX + j*30 + 15 - len(text)*5, offsetY + i*30 +6, '#ffffff' if colored else '#000000', color)

def drawMenuOrderLabel():
    kd.draw_string('<    >', 130, 100, '#555555')
    text = str(order)
    kd.draw_string(text, 160 - len(text)*5, 100)
    text = str(order * (order**2 +1) //2)
    text = 'Sum: ' + ' ' * (3 - len(text)) + text
    kd.draw_string(text, 160 - len(text)*5, 135, '#555555')

def drawMenuColorLabel():
    kd.draw_string(' on' if colored else 'off', 170, 160, '#ffb531' if colored else '#555555')

kd.draw_string('Magic Square', 100 , 70, '#ffffff', '#ffb531')
drawMenuOrderLabel()
kd.draw_string('color:', 100, 160, '#555555')
drawMenuColorLabel()

while ion.keydown(ion.KEY_OK): pass
while True:
    if ion.keydown(ion.KEY_LEFT):
        order = max(order -2, 3)
        drawMenuOrderLabel()
        while ion.keydown(ion.KEY_LEFT): pass
    if ion.keydown(ion.KEY_RIGHT):
        order = min(order +2, 9)
        drawMenuOrderLabel()
        while ion.keydown(ion.KEY_RIGHT): pass
    if ion.keydown(ion.KEY_SHIFT):
        colored = not colored
        drawMenuColorLabel()
        while ion.keydown(ion.KEY_SHIFT): pass
    if ion.keydown(ion.KEY_OK):
        break

drawSquare(magicSquare())

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.