Найти тему
Broud

Как создать игру на python крестики-нолики с помощью библиотеки библиотеки pygame.

Всем привет, сейчас я покажу как легко написать крестики-нолики с помощью библиотеки pygame. Пишем в Python .

Начнём:

Импортируем библиотеку

import pygame

Создаём игровое окно:

pygame.init()

SIZE = (600, 600)

SCREEN = pygame.display.set_mode(SIZE)

pygame.display.set_caption("Tic Tac Toe")

Создаем параметры для игры:

BOARD_SIZE = 3

TILE_SIZE = int(SIZE[0] / BOARD_SIZE)

LINE_WIDTH = 5

CROSS_WIDTH = 25

CIRCLE_WIDTH = 15

FONT_SIZE = 50

Устанавливаем цвета(---можете взять любые---):

BLACK = (0, 0, 0)

WHITE = (255, 255, 255)

Создаем игровое поле:

board = [[None] * BOARD_SIZE for _ in range(BOARD_SIZE)]

Пишем функцию отрисовки игрового поля:

def draw_board():

   SCREEN.fill(WHITE)

   for i in range(1, BOARD_SIZE):

       pygame.draw.line(SCREEN, BLACK, (0, i * TILE_SIZE), (SIZE[0], i * TILE_SIZE), LINE_WIDTH)

       pygame.draw.line(SCREEN, BLACK, (i * TILE_SIZE, 0), (i * TILE_SIZE, SIZE[0]), LINE_WIDTH)

   for i in range(BOARD_SIZE):

       for j in range(BOARD_SIZE):

           if board[i][j] == 'X':

               pygame.draw.line(SCREEN, BLACK, (i * TILE_SIZE + CROSS_WIDTH, j * TILE_SIZE + CROSS_WIDTH),

                                ((i + 1) * TILE_SIZE - CROSS_WIDTH, (j + 1) * TILE_SIZE - CROSS_WIDTH), CROSS_WIDTH)

               pygame.draw.line(SCREEN, BLACK, ((i + 1) * TILE_SIZE - CROSS_WIDTH, j * TILE_SIZE + CROSS_WIDTH),

                                (i * TILE_SIZE + CROSS_WIDTH, (j + 1) * TILE_SIZE - CROSS_WIDTH), CROSS_WIDTH)

           elif board[i][j] == 'O':

               pygame.draw.circle(SCREEN, BLACK, (int(i * TILE_SIZE + TILE_SIZE / 2), int(j * TILE_SIZE + TILE_SIZE / 2)),

                                  int(TILE_SIZE / 2 - CIRCLE_WIDTH), CIRCLE_WIDTH)

Теперь самое главное функция проверки победителя:

def check_winner():

   for i in range(BOARD_SIZE):

       if (board[i][0] == board[i][1] == board[i][2]) and (board[i][0] is not None):

           return board[i][0]

       if (board[0][i] == board[1][i] == board[2][i]) and (board[0][i] is not None):

           return board[0][i]

   if (board[0][0] == board[1][1] == board[2][2]) and (board[0][0] is not None):

       return board[0][0]

   if (board[0][2] == board[1][1] == board[2][0]) and (board[0][2] is not None):

       return board[0][2]

   return None

Теперь создаем основной цикл игры:

def main():

   turn = 'X'

   font = pygame.font.SysFont("Arial", FONT_SIZE)

   while True:

       for event in pygame.event.get():

           if event.type == pygame.QUIT:

               pygame.quit()

               return

           elif event.type == pygame.MOUSEBUTTONDOWN:

               x, y = event.pos

               tile_x = x // TILE_SIZE

               tile_y = y // TILE_SIZE

               if board[tile_x][tile_y] is None:

                   board[tile_x][tile_y] = turn

                   if turn == 'X':

                       turn = 'O'

                   else:

                       turn = 'X'

       draw_board()

       winner = check_winner()

       if winner is not None:

           SCREEN.blit(font.render("{0} wins!".format(winner), True, BLACK), (SIZE[0] / 2 - FONT_SIZE, SIZE[1] / 2 - FONT_SIZE))

           pygame.display.update()

           pygame.time.wait(2000)

           return

       elif all([all(row) for row in board]) and (winner is None):

           SCREEN.blit(font.render("Tie game!", True, BLACK), (SIZE[0] / 2 - FONT_SIZE, SIZE[1] / 2 - FONT_SIZE))

           pygame.display.update()

           pygame.time.wait(2000)

           return

       pygame.display.update()

if __name__ == "__main__":

   main()

Ну вот и всё.

Надеюсь, это поможет вам создать игру крестики-нолики.

Тут больше