Python数独游戏源代码

Python数独游戏源代码、源程序共包括两个程序文件:main.py及build.py
main.py
Python数独游戏源代码_第1张图片


import sys


import pygame
from pygame.color import THECOLORS as COLORS


from ShuDu.build import *




def draw_background():
    # white background
    BG_COLOR = (40, 40, 60)  # 背景色
    screen.fill(BG_COLOR)
    pygame.display.set_caption('数独游戏')
    # draw game board
    pygame.draw.rect(screen, COLORS['black'], (0, 0, 300, 900), 5)
    pygame.draw.rect(screen, COLORS['black'], (300, 0, 300, 900), 5)
    pygame.draw.rect(screen, COLORS['black'], (600, 0, 300, 900), 5)


    pygame.draw.rect(screen, COLORS['black'], (0, 0, 900, 300), 5)
    pygame.draw.rect(screen, COLORS['black'], (0, 300, 900, 300), 5)
    pygame.draw.rect(screen, COLORS['black'], (0, 600, 900, 300), 5)




def draw_choose():
    BLOCK_COLOR = (20, 128, 200)  #
    pygame.draw.rect(screen, BLOCK_COLOR, (cur_j * 100 + 5, cur_i * 100 + 5, 100 - 10, 100 - 10), 0)




def check_win(matrix_all, matrix):
    if matrix_all == matrix:
        return True
    return False




def check_color(matrix, i, j):
    _matrix = [[col for col in row] for row in matrix]
    _matrix[i][j] = 0
    if check(_matrix, i, j, matrix[i][j]):
        return COLORS['green']
    return COLORS['red']




def draw_number():
    for i in range(len(MATRIX)):
        for j in range(len(MATRIX[0])):
            _color = check_color(MATRIX, i, j) if (i, j) in BLANK_IJ else COLORS['gray']
            txt = font80.render(str(MATRIX[i][j] if MATRIX[i][j] not in [0, '0'] else ''), True, _color)
            x, y = j * 100 + 30, i * 100 + 10
            screen.blit(txt, (x, y))




def draw_context():
    txt = font100.render('Blank:' + str(cur_blank_size) + '   Change:' + str(cur_change_size), True, COLORS['black'])
    x, y = 10, 900
    screen.blit(txt, (x, y))




if __name__ == "__main__":
    # init pygame
    pygame.init()


    # contant
    SIZE = [900, 1000]
    font80 = pygame.font.SysFont('Times', 80)
    font100 = pygame.font.SysFont('Times', 90)


    # create screen 500*500
    screen = pygame.display.set_mode(SIZE)


    # variable parameter
    cur_i, cur_j = 0, 0
    cur_blank_size = 5 #int(sys.argv[1])
    cur_change_size = 0


    # matrix abount
    MATRIX_ANSWER, MATRIX, BLANK_IJ = give_me_a_game(blank_size=cur_blank_size)
    print(BLANK_IJ)
    print_matrix(MATRIX)


    # main loop
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                break
            elif event.type == pygame.MOUSEBUTTONDOWN:
                cur_j, cur_i = int(event.pos[0] / 100), int(event.pos[1] / 100)
            elif event.type == event.type == pygame.KEYUP:
                if chr(event.key) in ['1', '2', '3', '4', '5', '6', '7', '8', '9'] and (cur_i, cur_j) in BLANK_IJ:
                    MATRIX[cur_i][cur_j] = int(chr(event.key))
                    cur_blank_size = sum([1 if col == 0 or col == '0' else 0 for row in MATRIX for col in row])
                    cur_change_size += 1
        # background
        draw_background()
        # choose item
        draw_choose()
        # numbers
        draw_number()
        # point
        draw_context()
        # flip
        pygame.display.flip()


        # check win or not
        if check_win(MATRIX_ANSWER, MATRIX):
            print('You win, smarty ass!!!')
            break


    pygame.quit()

build.py

import random


def print_matrix(matrix):
    print('—'*19)
    for row in matrix:
        print('|'+' '.join([str(col) for col in row])+'|')
    print('—'*19)


def shuffle_number(_list):
    random.shuffle(_list)
    return _list


def check(matrix,i,j,number):
    if number in matrix[i]:
        return False
    if number in [row[j] for row in matrix]:
        return False
    group_i,group_j = int(i/3),int(j/3)
    if number in [matrix[i][j] for i in range(group_i*3,(group_i+1)*3) for j in range(group_j*3,(group_j+1)*3)]:
        return False
    return True


def build_game(matrix,i,j,number):
    if i>8 or j>8:
        return matrix
    if check(matrix,i,j,number):
        _matrix = [[col for col in row] for row in matrix]
        _matrix[i][j] = number
        next_i,next_j = (i+1,0) if j==8 else (i,j+1)
        for _number in shuffle_number(number_list):
            #_matrixs.append(build_game(_matrix,next_i,next_j,_number))
            __matrix = build_game(_matrix,next_i,next_j,_number)
            if __matrix and sum([sum(row) for row in __matrix])==(sum(range(1,10))*9):
                return __matrix
    #return _matrixs
    return None


def give_me_a_game(blank_size=9):
    matrix_all = build_game(matrix,0,0,random.choice(number_list))
    set_ij = set()
    while len(list(set_ij))<blank_size:
        set_ij.add(str(random.choice([0,1,2,3,4,5,6,7,8]))+','+str(random.choice([0,1,2,3,4,5,6,7,8])))
    matrix_blank = [[col for col in row] for row in matrix_all]
    blank_ij = []
    for ij in list(set_ij):
        i,j = int(ij.split(',')[0]),int(ij.split(',')[1])
        blank_ij.append((i,j))
        matrix_blank[i][j] = 0
    return matrix_all,matrix_blank,blank_ij


number_list = [1,2,3,4,5,6,7,8,9]
matrix = [([0]*9) for i in range(9)]
if __name__ == "__main__":
    print_matrix(build_game(matrix,0,0,random.choice(number_list)))

更多Python源代码、源程序请关注公众号:Python代码大全。Python数独游戏源代码_第2张图片

你可能感兴趣的:(Python数独游戏源代码)