I followed a Youtube tutorial for creating a Chess engine in Python code for code but it will not work in Pycharm? I can see that the correct chess board has been created but only when I close the pop-up window. Initially it shows as a black screen, then when I close the window it briefly appears before shutting as well. So I know that the code is working as intended, but there is some other issue at hand.
Here is the code just in case it is helpful:
import pygame as p from Chess import engine WIDTH = HEIGHT = 800 DIMENSION = 8 SQ_SIZE = HEIGHT // DIMENSION MAX_FPS = 15 IMAGES = {} def loadImages(): pieces = ['wp', 'wR', 'wN', 'wB', 'wK', 'wQ', 'bp', 'bR', 'bN', 'bB', 'bK', 'bQ'] for piece in pieces: IMAGES[piece] = p.transform.scale(p.image.load("images/" + piece + ".png"), (SQ_SIZE, SQ_SIZE)) # any icon image can be accessed using ICONS['__'] def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = engine.State() loadImages() running = True while running: for e in p.event.get(): if e.type == p.QUIT: running = False visualise(screen, gs) clock.tick(MAX_FPS) p.display.flip() def visualise(screen, gs): drawBoard(screen) drawPieces(screen, gs.board) def drawBoard(screen): colours = [p.Color("white"), p.Color("gray")] for row in range(DIMENSION): for column in range(DIMENSION): tile = colours[((row + column) % 2)] p.draw.rect(screen, tile, p.Rect(column * SQ_SIZE, row * SQ_SIZE, SQ_SIZE, SQ_SIZE)) def drawPieces(screen, board): for row in range(DIMENSION): for column in range(DIMENSION): piece = board[row][column] if piece != "--": screen.blit(IMAGES[piece], p.Rect(column * SQ_SIZE, row * SQ_SIZE, SQ_SIZE, SQ_SIZE)) if __name__ == "__main__": main() // engine.py file class State(): def __init__(self): self.board = [ ["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"], ["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["wp", "wp", "wp", "wp", "wp", "wp", "wp", "wp"], ["wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR"]] self.whiteToMove = True self.moveLog = []
Advertisement
Answer
It is a matter of Indentation. You have to draw the scene and update the display in the application loop, not after the application loop:
def main(): p.init() screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = engine.State() loadImages() running = True while running: for e in p.event.get(): if e.type == p.QUIT: running = False # INDENTATION #-->| visualise(screen, gs) clock.tick(MAX_FPS) p.display.flip()