Московский Государственный институт электроники и математики
Курсовая работа
Тема: Игра «Крестики нолики»
Выполнил: | Смирнов Сергей Анатольевич, С-14 |
Руководитель: | Дмитрий Столяров |
Оглавление
Описание игры “Крестики нолики”. 3
Приложение 1. Исходный код программы. 9
Играя в оригинальную игру “Крестики нолики”, там всегда играл компьютер с игроком. Я сделал так, чтобы игрок играл с игроком.
Создание игры
В игре несколько классов.
Класс initBoard. Класс, который инициализирует доску.
В классе есть методы:
· __init__ - Конструктор – инициализирует начальные данные по игре, инициализирует библиотеку pygame.
· drawStatus - Статус который находится внизу доски.
Используемые источники и программы:
1. Python
2. Pygame
Приложение 1. Исходный код программы
# -*- coding: utf-8 -*-
#Krestiki nolki
import pygame #import pygame
import random # importiruem generator slu4aunih 4isel
from pygame.locals import * #is pygame.local importiruem vse
pygame.init() # inisializaciya
screen = pygame.display.set_mode((300,325)) # ustanavlivaem razmer ekrana
pygame.display.set_caption = ("Krestiki i noliki") # ustanavlivaem nazvanie
def initBoard(screen): #inicializaciya doski
background = pygame.Surface (screen.get_size()) #sozdaem poverhnost'
background = background.convert()
background.fill ((250,250,250)) #zapolnyaem ee cvetom
# risuem linii
# vertikal'nie...
pygame.draw.line (background, (0,0,0), (100,0), (100,300), 2)
pygame.draw.line (background, (0,0,0), (200,0), (200,300), 2)
# horizontalnue...
pygame.draw.line (background, (0,0,0), (0,100), (300,100), 2)
pygame.draw.line (background, (0,0,0), (0,200), (300,200), 2)
# vozvrashaem dosku
return background
board = initBoard (screen) # sozdaem dosku s pomosh'u sozdannou funkcii
def drawStatus (board): # pishem status vnizu doski
global XO, winner
# opredelyaem statusoe soobshenie
if (winner is None):
message = XO + " hodyat"
else:
message = winner + " viigral!"
# sozdanie shrifta i texta
font = pygame.font.Font(None, 24)
text = font.render(message, 1, (0,0,0))
# otrisovka texta
board.fill ((250, 250, 250), (0, 300, 300, 25))
board.blit (text, (10, 300))
def showBoard (screen, board): # pokazat' dosku
drawStatus(board)
screen.blit (board, (0,0))
pygame.display.flip()
XO = 'X' # pervie hodyat krestiki
grid = [ [ None, None, None ], #pustaya setka
[ None, None, None ],
[ None, None, None ] ]
def boardPos (mouseX, mouseY):
# opredelyaem ryad kuda najali
if (mouseY < 100):
row = 0
elif (mouseY < 200):
row = 1
else:
row = 2
# opredelyaem stolbec kuda najali
if (mouseX < 100):
col = 0
elif (mouseX < 200):
col = 1
else:
col = 2
# vozvrashaem rayd i stolbec
return (row, col)
def clickBoard (board):
global grid, XO, winner # dostup k globalnim peremennim
(mouseX, mouseY) = pygame.mouse.get_pos() # poziciya mishki
(row, col) = boardPos (mouseX, mouseY) # poly4aem ryad i stolbec
# proverka na zanyatost'
if ((grid[row][col] == 'X') or (grid[row][col] == 'O')):
# esli uge tam 4toto est' to propuskaem
return
if winner != None: # esli viigravshiu uje est' to ni4ego risovat' ne nado
return
drawMove (board, row, col, XO) #risuem sootvetstvuushiu zna4ek
# drawAIMove (board)
if (XO == 'X'): # pereklu4aem hod
XO = 'O'
else:
XO = 'X'
def drawMove (board, boardRow, boardCol, Piece): #risuem krest ili nol'
centerX = boardCol * 100 + 50 #centri kvadratov
centerY = boardRow * 100 + 50 #centri kvadratov
# risuem..
if (Piece == 'O'):
# esli nol' to risuem krug
pygame.draw.circle (board, (0,0,0), (centerX, centerY), 44, 2)
else:
# esli X to dve linii
pygame.draw.line (board, (0,0,0), (centerX - 22, centerY - 22), (centerX + 22, centerY + 22), 2)
pygame.draw.line (board, (0,0,0), (centerX + 22, centerY - 22), (centerX - 22, centerY + 22), 2)
# pome4aem mesto kak zanyatoe
grid[boardRow][boardCol] = Piece
def gameWon(board): #proverka na viigrish
global grid, winner
# proverka viigrashnih ryadov
for row in range (0, 3):
if ((grid [row][0] == grid[row][1] == grid[row][2]) and (grid [row][0] is not None)):
# etot ryad viigral
winner = grid[row][0]
pygame.draw.line (board, (250,0,0), (0, (row + 1)*100 - 50), (300, (row + 1)*100 - 50), 2)
break
# proverka viigrishnih stolbcov
for col in range (0, 3):
if (grid[0][col] == grid[1][col] == grid[2][col]) and (grid[0][col] is not None):
# etot stolbec viigral
winner = grid[0][col]
pygame.draw.line (board, (250,0,0), ((col + 1)* 100 - 50, 0), ((col + 1)* 100 - 50, 300), 2)
break
# proverka na diagonalnie viigrashi
if (grid[0][0] == grid[1][1] == grid[2][2]) and (grid[0][0] is not None):
# viigrish s leva na pravo
winner = grid[0][0]
pygame.draw.line (board, (250,0,0), (50, 50), (250, 250), 2)
if (grid[0][2] == grid[1][1] == grid[2][0]) and (grid[0][2] is not None):
# viigrish s prava na levo
winner = grid[0][2]
pygame.draw.line (board, (250,0,0), (250, 50), (50, 250), 2)
winner = None # ina4e nikto ne viigral
running = 1 #flag raboti programmi
#menu_flag = 1 # risovat' menu v na4ale, 2 kogda konec
while (running == 1):
for event in pygame.event.get():
# drawMenu(board)
if event.type is QUIT:
running = 0
elif event.type is MOUSEBUTTONDOWN:
# esli pol'zovatel' najal to risovat'
clickBoard(board)
# proverka na pobeditelya
gameWon (board)
# obnovlenie displey
showBoard (screen, board)