简体   繁体   English

如何从another.py调用Python代码? (当我按空格键时 both.py 在同一个文件中)

[英]How to call Python code from another .py? (when I press space bar both .py are in the same file)

How to call a code from one.py to run in another.py when I press space bar both.py are in the same file.当我按空格键时如何从 one.py 调用代码以在 another.py 中运行 both.py 都在同一个文件中。

I have a code called solve that I want to call by pressing space when running my sudoku code.我有一个名为 solve 的代码,我想在运行我的数独代码时按空格键调用它。 This is solver.py they are both in a folder called Sudoku solver.这是 solver.py 它们都在一个名为 Sudoku solver 的文件夹中。 I apologize if this is simple;如果这很简单,我深表歉意; I don't know pygame very well.我不太了解pygame

def solve(bo):

    find = find_empty(bo)
    if not find:
        return True
    else:
        row, col = find

    for i in range(1,10):
        if valid(bo, i, (row, col)):
            bo[row][col] = i

            if solve(bo):
                return True

            bo[row][col] = 0

    



def valid(bo, num, pos):
    # check row
    for i in range(len(bo[0])):
        if bo[pos[0]][i] == num and pos[1] !=i:
            return False

    # check column
    for i in range(len(bo)):
        if bo[i][pos[1]] == num and pos[0] !=i:
            return False

    # check box
    box_x = pos[1] // 3
    box_y = pos[0] // 3


    for i in range(box_y * 3, box_y * 3):
        for j in range(box_x * 3, box_x * 3):
            if bo[i][j] == num and(i, j) != pos:
                return False
    return True

def print_board(bo):
    
    for i in range(len(bo)):
        if i % 3 == 0 and i !=0:
            print("- - - - - - - - - - - - -")

        for j in range(len(bo[0])):
            if j % 3 == 0 and j != 0:
                print(" | ", end="")

            if j == 8:
                print(bo[i][j])
            else:
                print(str(bo[i][j]) + " ", end="")

def find_empty(bo):
    for i in range (len(bo)):
        for j in range(len(bo[0])):
            if bo[i][j] == 0:
                return (i, j) #(row,column)

    return None

this is sudoku这是数独

# GUI.py
import pygame
from solver import solve, valid
import time
import solver
pygame.font.init()


class Grid:
    board = [
        [7, 8, 0, 4, 0, 0, 1, 2, 0],
        [6, 0, 0, 0, 7, 5, 0, 0, 9],
        [0, 0, 0, 6, 0, 1, 0, 7, 8],
        [0, 0, 7, 0, 4, 0, 2, 6, 0],
        [0, 0, 1, 0, 5, 0, 9, 3, 0],
        [9, 0, 4, 0, 6, 0, 0, 0, 5],
        [0, 7, 0, 3, 0, 0, 0, 1, 2],
        [1, 2, 0, 0, 0, 7, 4, 0, 0],
        [0, 4, 9, 2, 0, 6, 0, 0, 7]
    ]

    def __init__(self, rows, cols, width, height):
        self.rows = rows
        self.cols = cols
        self.cubes = [[Cube(self.board[i][j], i, j, width, height) for j in range(cols)] for i in range(rows)]
        self.width = width
        self.height = height
        self.model = None
        self.selected = None

    def update_model(self):
        self.model = [[self.cubes[i][j].value for j in range(self.cols)] for i in range(self.rows)]

    def place(self, val):
        row, col = self.selected
        if self.cubes[row][col].value == 0:
            self.cubes[row][col].set(val)
            self.update_model()

            if valid(self.model, val, (row,col)) and solve(self.model):
                return True
            else:
                self.cubes[row][col].set(0)
                self.cubes[row][col].set_temp(0)
                self.update_model()
                return False

    def sketch(self, val):
        row, col = self.selected
        self.cubes[row][col].set_temp(val)

    def draw(self, win):
        # Draw Grid Lines
        gap = self.width / 9
        for i in range(self.rows+1):
            if i % 3 == 0 and i != 0:
                thick = 4
            else:
                thick = 1
            pygame.draw.line(win, (0,0,0), (0, i*gap), (self.width, i*gap), thick)
            pygame.draw.line(win, (0, 0, 0), (i * gap, 0), (i * gap, self.height), thick)

        # Draw Cubes
        for i in range(self.rows):
            for j in range(self.cols):
                self.cubes[i][j].draw(win)

    def select(self, row, col):
        # Reset all other
        for i in range(self.rows):
            for j in range(self.cols):
                self.cubes[i][j].selected = False

        self.cubes[row][col].selected = True
        self.selected = (row, col)

    def clear(self):
        row, col = self.selected
        if self.cubes[row][col].value == 0:
            self.cubes[row][col].set_temp(0)

    def click(self, pos):
        """
        :param: pos
        :return: (row, col)
        """
        if pos[0] < self.width and pos[1] < self.height:
            gap = self.width / 9
            x = pos[0] // gap
            y = pos[1] // gap
            return (int(y),int(x))
        else:
            return None

    def is_finished(self):
        for i in range(self.rows):
            for j in range(self.cols):
                if self.cubes[i][j].value == 0:
                    return False
        return True


class Cube:
    rows = 9
    cols = 9

    def __init__(self, value, row, col, width ,height):
        self.value = value
        self.temp = 0
        self.row = row
        self.col = col
        self.width = width
        self.height = height
        self.selected = False

    def draw(self, win):
        fnt = pygame.font.SysFont("comicsans", 40)

        gap = self.width / 9
        x = self.col * gap
        y = self.row * gap

        if self.temp != 0 and self.value == 0:
            text = fnt.render(str(self.temp), 1, (128,128,128))
            win.blit(text, (x+5, y+5))
        elif not(self.value == 0):
            text = fnt.render(str(self.value), 1, (0, 0, 0))
            win.blit(text, (x + (gap/2 - text.get_width()/2), y + (gap/2 - text.get_height()/2)))

        if self.selected:
            pygame.draw.rect(win, (255,0,0), (x,y, gap ,gap), 3)

    def set(self, val):
        self.value = val

    def set_temp(self, val):
        self.temp = val


def redraw_window(win, board, time, strikes):
    win.fill((255,255,255))
    # Draw time
    fnt = pygame.font.SysFont("comicsans", 40)
    text = fnt.render("Time: " + format_time(time), 1, (0,0,0))
    win.blit(text, (540 - 160, 560))
    # Draw Strikes
    text = fnt.render("X " * strikes, 1, (255, 0, 0))
    win.blit(text, (20, 560))
    # Draw grid and board
    board.draw(win)


def format_time(secs):
    sec = secs%60
    minute = secs//60
    hour = minute//60

    mat = " " + str(minute) + ":" + str(sec)
    return mat


def main():
    win = pygame.display.set_mode((540,600))
    pygame.display.set_caption("Sudoku")
    board = Grid(9, 9, 540, 540)
    key = None
    run = True
    start = time.time()
    strikes = 0
    while run:

        play_time = round(time.time() - start)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_1:
                    key = 1
                if event.key == pygame.K_2:
                    key = 2
                if event.key == pygame.K_3:
                    key = 3
                if event.key == pygame.K_4:
                    key = 4
                if event.key == pygame.K_5:
                    key = 5
                if event.key == pygame.K_6:
                    key = 6
                if event.key == pygame.K_7:
                    key = 7
                if event.key == pygame.K_8:
                    key = 8
                if event.key == pygame.K_9:
                    key = 9
                if event.key == pygame.K_SPACE:
                    solver.solve(bo)
                if event.key == pygame.K_DELETE:
                    board.clear()
                    key = None
                if event.key == pygame.K_RETURN:
                    i, j = board.selected
                    if board.cubes[i][j].temp != 0:
                        if board.place(board.cubes[i][j].temp):
                            print("Success")
                        else:
                            print("Wrong")
                            strikes += 1
                        key = None

                        if board.is_finished():
                            print("Game over")
                            run = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                clicked = board.click(pos)
                if clicked:
                    board.select(clicked[0], clicked[1])
                    key = None

        if board.selected and key != None:
            board.sketch(key)

        redraw_window(win, board, play_time, strikes)
        pygame.display.update()


main()
pygame.quit()

It looks to me like you've already handled the event where space is pressed, you will call solve from the other file.在我看来,您已经处理了按下空格的事件,您将从另一个文件调用 solve 。 I think you've done it right.我认为你做对了。 However, I think you misdefinied the input parameter for solver.solve().但是,我认为您错误定义了 solver.solve() 的输入参数。 Looking through your code in GUI.py, there seems to be no variable called bo .查看 GUI.py 中的代码,似乎没有名为bo的变量。 By looking at it, I assume the right input parameter should be board .通过查看它,我假设正确的输入参数应该是board

Could you try changing line 197 from:您可以尝试更改第 197 行:

solver.solve(bo)

to:到:

solver.solve(board)

Just an additional comment:只是一个额外的评论:

As you used from solver import solve, valid in line 3, you do not need to use solver.solve(bo) in line 197. Instead you can simply use solve(bo) .正如您在第 3 行中使用from solver import solve, valid ,您不需要在第 197 行中使用solver.solve(bo) 。相反,您可以简单地使用solve(bo) This is not a problem though, the way you used also works as you've used import solver on line 5.但这不是问题,您使用的方式也适用于您在第 5 行使用import solver的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用另一个.py文件中的类方法将两个文件放在同一个程序包中,并且两个文件都放在不同的文件夹中? - How to use class methods from another .py file both files in same package and when both are in different folders? 如何从相同的python脚本运行.py和.exe文件 - how to run both a .py and a .exe file from the same python script 如何从python中的另一个.py文件调用函数? - How to call function from another .py file in python? 如何从新 window 中的 .py 文件调用另一个 python 脚本 - How to call another python script from a .py file in a new window 如何从 another.py 文件中调用模块 - How to call modules from another .py file 对于Python 3,如何从另一个目录导入.py文件? - For Python 3, how do I import a .py file from another directory? 来自另一个py文件的maya python调用函数 - maya python call function from another py file 如何编写用于处理py2和py3的URLError异常的python代码 - How do I write python code that handles URLError Exception for both py2 and py3 有没有办法在 python 中调用 .py 文件。 我不想复制和粘贴 .py 文件代码 - is there a way to call a .py file in python. I do not want to copy and paste the .py file code 如何调用另一个 python 文件,运行它,并将 main.py 替换为 new.py 文件? - How to call another python file, run it, and replace main.py with the new .py file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM