-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnect-4(console).py
87 lines (65 loc) · 2.32 KB
/
Connect-4(console).py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import numpy as np
ROW_COUNT=6
COL_COUNT =7
def create_board():
board = np.zeros((ROW_COUNT,COL_COUNT))
return board
def drop_piece(board, row, col, piece):
board[row][col] = piece
def is_valid_location(board, col):
return board[ROW_COUNT-1][col] == 0
def get_next_open_row(board, col):
for r in range(ROW_COUNT):
if board[r][col] == 0:
return r
def print_board(board):
print(np.flip(board, 0)) # to start placing the piece from bottom
def winning_move(board, piece):
# Check for horizontal win
for c in range(COL_COUNT-3):
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece:
return True
# Check for vertical win
for c in range(COL_COUNT):
for r in range(ROW_COUNT-3):
if board[r][c] == piece and board[r+1][c] == piece and board[r+2][c] == piece and board[r+3][c] == piece:
return True
# Check positively sloped diaganols for win
for c in range(COL_COUNT-3):
for r in range(ROW_COUNT-3):
if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece:
return True
# Check negatively sloped diaganols for win
for c in range(COL_COUNT-3):
for r in range(3, ROW_COUNT):
if board[r][c] == piece and board[r-1][c+1] == piece and board[r-2][c+2] == piece and board[r-3][c+3] == piece:
return True
board = create_board()
print_board(board)
game_over = False
turn=0
Player1=input("Enter Player1 name: ")
Player2=input("Enter Player2 name: ")
while not game_over:
# Ask for Player 1 Input
if turn == 0:
col = int(input(Player1 + " make your selection(0-6):"))
if is_valid_location(board,col):
row = get_next_open_row(board,col)
drop_piece(board,row,col,1)
if winning_move(board, 1):
print(Player1 + " WINs!!!! Congrats!!!!")
game_over = True
# Ask for Player 2 Input
else:
col = int(input(Player2 + " make your selection(0-6):"))
if is_valid_location(board,col):
row = get_next_open_row(board,col)
drop_piece(board,row,col,2)
if winning_move(board, 2):
print(Player2 + " WINs!!!! Congrats!!!!")
game_over = True
print_board(board)
turn += 1
turn = turn % 2