I was trying to make a simple Sudoku game. Then, I tried to create some cells by using pygame.draw.rect() so when you click one I the programme know which one you touched. But there are 81 and I can't write each variable so I tried to use exec() but it just didn't work. The programme is not ended.
If you find another problem please notify me.
Here is my programme:
Problematic lines are showed with this: ***
import pygame, sys
from pygame.locals import *
pygame.init()
screen_high = 512
screen_width = 512
screen = pygame.display.set_mode((screen_width, screen_high))
pygame.display.set_caption("Sudoku")
board = pygame.transform.scale(pygame.image.load('board.png'), (screen_high, screen_width))
A = [0, 0, 0, 0, 0, 0, 0, 0, 0]
B = [0, 0, 0, 0, 0, 0, 0, 0, 0]
C = [0, 0, 0, 0, 0, 0, 0, 0, 0]
D = [0, 0, 0, 0, 0, 0, 0, 0, 0]
E = [0, 0, 0, 0, 0, 0, 0, 0, 0]
F = [0, 0, 0, 0, 0, 0, 0, 0, 0]
G = [0, 0, 0, 0, 0, 0, 0, 0, 0]
H = [0, 0, 0, 0, 0, 0, 0, 0, 0]
I = [0, 0, 0, 0, 0, 0, 0, 0, 0]
columns = [A, B, C, D, F, G, H, I]
columstr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
c_num = ''
r_num = ''
cells = []
xx = 0
yy = 0
def create():
global n, A, B, C, D, E, F, G, H, I
n = random.randint(1, 7)
if n == 1:
A = [5, 6, 0, 8, 4, 7, 0, 0, 0]
B = [3, 0, 9, 0, 0, 0, 6, 0, 0]
C = [0, 0, 0, 0, 0, 0, 0, 0, 0]
D = [0, 0, 0, 0, 0, 0, 0, 0, 0]
E = [0, 0, 0, 0, 0, 0, 0, 0, 0]
F = [0, 0, 0, 0, 0, 0, 0, 0, 0]
G = [0, 0, 0, 0, 0, 0, 0, 0, 0]
H = [0, 0, 0, 0, 0, 0, 0, 0, 0]
I = [0, 0, 0, 0, 0, 0, 0, 0, 0]
def put_numb(whr1, whr2, wht):
global columns, c_num, r_num
for i in range(len(columns)):
if whr1 == columstr[i]:
c_num = i
r_num = whr2 - 1
columns[c_num].pop(r_num)
columns[c_num].insert(r_num, wht)
def put_all():
global columns, columstr, A, B, C, D, E, F, G, H, I
def check_touch():
for i in range(len(cells)):
*** if pygame.Rect.colliderect( cells[i], mouse ) == True:
print(cells)
value = ''
var = ''
def make_rectBoard():
global cells, xx, yy, value, var
for i in range(81):
*** value = pygame.draw.rect(screen, (0, 0, 0), (xx + 52, yy + 52, 50, 50))
*** var = 'cell' + str(i)
*** print(cells.append(exec(f"{var} = pygame.draw.rect(screen, (120, 0, 0), (xx + 52, yy ***+ 52, 50, 50))")))
while True:
mouse_pos = pygame.mouse.get_pos()
mouse_click = pygame.mouse.get_pressed()
pygame.display.update()
screen.fill((0, 0, 0))
screen.blit(board, (0, 0))
make_rectBoard()
mouse = pygame.draw.rect(screen, (204, 180, 20), (mouse_pos[0] + 1, mouse_pos[1] + 1, 10, 10))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
check_touch()
Thank you, I tried all I could with that method but nothing happened. That you see is the latest thing I tried. Probably it's easy. I'm not sure, thanks for all.