从Chess导入ChessEngine:Chess引擎出错

2024-04-18 20:06:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经复习了很多遍教程,但是仍然有这个错误。在该系列的第一个视频之后,他能够显示电路板。该错误在我的导入语句中突出显示ChessEngine

这是我的主要资源:https://www.youtube.com/watch?v=EnYui0e73Rs&t=2095s

这就是错误: ImportError:无法从“Chess”(未知位置)导入名称“ChessEngine”

请暂停

我的代码如下

***import pygame as p
from Chess import ChessEngine
WIDTH = HEIGHT = 512  # optional 400
DIMENSIONS = 8  # dimensions are 8x8
SQ_SIZE = HEIGHT // DIMENSIONS
MAX_FPS = 15  # For animation
IMAGES = {}
'''
Initialize global dictionary of images. this will be called once in the main
'''
def load_images():
    pieces = ["wp", "wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR", "bp", "bR", "bN", "bB", "bQ", "bK", "bB", "bN",
              "bR"]
    for piece in pieces:
        IMAGES[piece] = p.transform.scale(p.image.load("images/" + piece + "wp.png"), (SQ_SIZE, SQ_SIZE))
#         note: we can access an image by saying 'IMAGES['wp']
'''
main driver for our code  handles user input and updating graphics 
'''
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    print(gs.board)
    load_images()  # only operated once
    running = True
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            drawGameState((screen, gs))
            clock.tick(MAX_FPS)
            p.display.flip()
def drawGameState(screen, gs):
    drawBoard(screen) #draw squares on board
    drawPieces(screen, gs.board)
def drawBoard(screen):
    colors = [p.Color("white", p.Color("grey"))]
    for r in range(DIMENSIONS):
        for c in range(DIMENSIONS):
            color = colors[((r+c) % 2)]
            p.draw.rect(screen, color, p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE))
def drawPieces(screen, board):
    '''
    draws the pieces on the board using current gameState.board
    '''
if __name__ == "__main__":
    main()***

Tags: inboardgsforsizemaindef错误
1条回答
网友
1楼 · 发布于 2024-04-18 20:06:04

如果您看到youtube视频的文件夹结构,他有一个名为Chess的根文件夹:

| Chess
| |  > images
| |  > ChessEngine.py
| |  > __init__.py 
| ...

当您声明import时,如果存在具有导入名称的模块(文件夹或文件),python将搜索调用文件夹(根文件夹)。如果文件夹包含__init__.py文件,它将被视为一个模块

对于您的使用,您有两个选项:

  1. 有一个名为Chess.py的文件,其中有一个导出的成员ChessEngine
  2. 有一个名为Chess的文件夹,其中有一个公开ChessEngine成员的__init__.py文件

我想,如果您遵循链接的整个教程,他们会告诉您如何从__init__.py文件中公开成员

如果您想更好地了解the import system (Docs Python)的工作原理,可以查看文档

相关问题 更多 >