Я сделал игру Реверси, используя модуль pygame. Этот скрипт работает, но есть небольшая проблема. Эффект, которого я хочу добиться, - отобразить результаты этого хода после перемещения игрока, сделать паузу на некоторое время (например, 2 секунды), а затем отобразить компьютерные движения и результаты. Но после запуска моего скрипта ходы и результаты компьютера отображаются сразу после хода игрока. Я попытался time.sleep (), но это не сработало. После тестирования я нашел причину проблемы. Pygame.display.update () может отображать только один кадр экрана. Если нет события l oop, экран не может отображаться непрерывно. Как решить эту проблему?
Я новичок в программировании и знаю, что код, который я пишу, не является гладким и эффективным. Вот мой код Я думаю, что проблема заключается в последних нескольких строках кода.
import pygame, os, time, random
from pygame.locals import *
def initBoardList():
boardList = []
for x in range(8):
boardList.append([])
for y in range(8):
boardList[x].append(' ')
boardList[3][3] = 'X'
boardList[3][4] = 'O'
boardList[4][3] = 'O'
boardList[4][4] = 'X'
return boardList
def move(boardList, coordinate, symbol):
if isValidMove(boardList, coordinate, symbol):
x = coordinate[0] - 1
y = coordinate[1] - 1
boardList[x][y] = symbol
flipableTiles = detectaAll(boardList, coordinate, symbol)
flipTile(boardList, flipableTiles)
def drawBoard(boardList, boardSurface, tileColour1, tileColour2):
for x in range(8):
for y in range(8):
if boardList[x][y] == 'O':
pygame.draw.circle(boardSurface, tileColour1, (80 * x + 120, 80 * y + 120), 30, 0)
if boardList[x][y] == 'X':
pygame.draw.circle(boardSurface, tileColour2, (80 * x + 120, 80 * y + 120), 30, 0)
def isFree(boardList, coodinate):
x = coodinate[0] - 1
y = coodinate[1] - 1
return boardList[x][y] == ' '
def isFull(boardList):
for x in range(8):
for y in range(8):
if boardList[x][y] == ' ':
return False
return True
def flipTile(boardList, flipableTiles):
for coordinate in flipableTiles:
x = coordinate[0] - 1
y = coordinate[1] - 1
if boardList[x][y] == 'X':
boardList[x][y] = 'O'
elif boardList[x][y] == 'O':
boardList[x][y] = 'X'
def reverseTile(symbol):
if symbol == 'O':
return 'X'
if symbol == 'X':
return 'O'
def detectOnedirection(boardList, coordinate, symbol, delta):
flipableTiles = []
deltaX = delta[0]
deltaY = delta[1]
x = coordinate[0] -1
y = coordinate[1] -1
while True:
x += deltaX
y += deltaY
if x < 0 or x > 7 or y < 0 or y > 7 or boardList[x][y] == ' ':
return []
elif boardList[x][y] == reverseTile(symbol):
flipableTiles.append((x+1, y+1))
elif boardList[x][y] == symbol:
return flipableTiles
def detectaAll(boardList, coordinate, symbol):
deltas = [(0, 1),(0, -1),(1, 1),(1, -1),(1, 0),(-1, 0),(-1, 1),(-1, -1)]
flipableTiles = []
for delta in deltas:
flipableTiles += detectOnedirection(boardList, coordinate, symbol, delta)
return flipableTiles
def getComputerMove(boardList,symbol):
bestMove = None
highestScore = 0
cMoveable = moveable(boardList, symbol)
for coordinate in cMoveable:
if coordinate in [(1,1),(1,8),(8,1),(8,8)]:
return coordinate
else:
score = len(detectaAll(boardList, coordinate, symbol))
if score > highestScore:
bestMove = coordinate
highestScore = score
return bestMove
def isValidMove(boardList, coordinate, symbol):
x = coordinate[0] -1
y = coordinate[1] -1
return 0 < coordinate[0] < 9 and 0 < coordinate[1] < 9 and \
isFree(boardList, coordinate) and len(detectaAll(boardList, coordinate, symbol)) != 0
def countScore(boardList, symbol):
score = 0
for x in range(8):
for y in range(8):
if boardList[x][y] == symbol:
score += 1
return score
def moveable(boardList, symbol):
moveable = []
for y in range(1,9):
for x in range(1,9):
if detectaAll(boardList, (x, y), symbol) != [] and isFree(boardList, (x,y)):
moveable.append((x, y))
random.shuffle(moveable)
return moveable
boardList = initBoardList()
black = (0, 0, 0)
white = (255, 255, 255)
blue = (0, 0, 255)
turn = 'player'
pygame.init()
boardSurface = pygame.display.set_mode((800,800), 0, 32)
boardSurface.fill(blue)
pygame.display.set_caption('Reversi')
for i in range(9):
pygame.draw.line(boardSurface, black, (80, 80 + 80*i), (720, 80 + 80*i), 2)
pygame.draw.line(boardSurface, black, (80 + 80*i, 80), (80 + 80*i, 720), 2)
drawBoard(boardList, boardSurface, black, white)
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
os._exit(1)
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
os._exit(1)
if event.type == MOUSEBUTTONUP and turn == 'player':
x = (event.pos[0] - 80)// 80 + 1
y = (event.pos[1] - 80)// 80 + 1
if isValidMove(boardList, (x, y), 'O'):
move(boardList, (x, y), 'O')
turn = 'computer'
drawBoard(boardList, boardSurface, black, white)
pygame.display.update()
if turn == 'computer':
cm = getComputerMove(boardList, 'X')
move(boardList, cm, 'X')
turn = 'player'
drawBoard(boardList, boardSurface, black, white)
pygame.display.update()