Skip to content

Instantly share code, notes, and snippets.

@BrettMayson
Created June 15, 2018 08:34
Show Gist options
  • Save BrettMayson/4aa4303c5ab37579ac7a4f517b77bfd5 to your computer and use it in GitHub Desktop.
Save BrettMayson/4aa4303c5ab37579ac7a4f517b77bfd5 to your computer and use it in GitHub Desktop.
import pygame
from pygame.locals import *
import sys
pygame.init()
fps = 60
fpsClock = pygame.time.Clock()
width, height = (1200, 900)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Connect 4")
class Board:
def __init__(self):
self.board = []
column = [0] * 6 #[0, 0, 0, 0, 0, 0]
for c in range(7):
self.board.append(column.copy())
board = Board()
column_spacing = width / 7
row_spacing = height / 6
global player
player = 1
over = False
def findEmptyRow(column):
for row in range(5, -1, -1):
if board.board[column][row] == 0:
return row
return -1
def getColour(player):
if player == 1:
return (255, 0, 0)
elif player == 2:
return (255, 255, 0)
else:
return (255, 255, 255)
def checkWin(player, column, row):
win = str(player) * 4
#Check Column
if win in "".join(str(x) for x in board.board[column]):
return True
#Check Row
check = []
for c in range(7):
check.append(str(board.board[c][row]))
if win in "".join(check):
return True
#Check Diagnol DESC
check = []
for i in range(-6, 6):
x = column + i
y = row + i
if x < 0 or y < 0 or x > 6 or y > 5:
continue
check.append(str(board.board[x][y]))
if win in "".join(check):
return True
#Check Diagnol ASC
check = []
for i in range(-6, 6):
x = column + i
y = row - i
if x < 0 or y < 0 or x > 6 or y > 5:
continue
check.append(str(board.board[x][y]))
if win in "".join(check):
return True
def loop():
global player
global over
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
return False
elif event.type == MOUSEBUTTONUP and not over:
pos = pygame.mouse.get_pos() #pos = [100, 300]
column = int(pos[0] / column_spacing)
row = findEmptyRow(column)
if row == -1:
continue
board.board[column][row] = player
#Check for a win
if checkWin(player, column, row):
over = True
player = 2 if player == 1 else 1
#Draw the board to the screen
for c in range(7):
for r in range(6):
pygame.draw.circle(
screen,
getColour(board.board[c][r]),
(int((c + 0.5) * column_spacing), int((r + 0.5) * row_spacing)),
int(width / 20)
)
return True
while True:
if not loop():
sys.exit(0)
pygame.display.flip()
fpsClock.tick(fps)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment