Created
November 8, 2018 23:37
-
-
Save nicka/43b1a1a2cd014e81c2452833c7711634 to your computer and use it in GitHub Desktop.
Four in a row example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
# print(np.__version__) | |
ROW_COUNT = 6 | |
COLUMN_COUNT = 7 | |
WINNG_PIECE_COUNT = 4 | |
def create_board(): | |
board = np.zeros((ROW_COUNT, COLUMN_COUNT)) | |
return board | |
def drop_piece(board, col, row, 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 winning_move(board, piece): | |
# Check horizontal locations for win | |
for c in range(WINNG_PIECE_COUNT): | |
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 vertical locations for win | |
for c in range(COLUMN_COUNT): | |
for r in range(WINNG_PIECE_COUNT-1): | |
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 c in range(WINNG_PIECE_COUNT): | |
for r in range(WINNG_PIECE_COUNT-1): | |
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 c in range(WINNG_PIECE_COUNT): | |
for r in range(1, WINNG_PIECE_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 | |
def print_board(board): | |
# TODO: Flip board doesn't work on my Laptop because of the numpy version | |
# print(np.flip(board, 0)) | |
print(board) | |
board = create_board() | |
game_over = False | |
current_player = 1 | |
print_board(board) | |
while not game_over: | |
# Ask for player input | |
col = int(input('Player ' + str(current_player) + ' drop die munt (0-6):')) | |
# Check if we can drop the piece | |
if is_valid_location(board, col): | |
row = get_next_open_row(board, col) | |
drop_piece(board, col, row, current_player) | |
if winning_move(board, current_player): | |
print('Player ' + str(current_player) + ' wins!!!') | |
game_over = True | |
# Update current player for next round | |
current_player = 2 if current_player == 1 else 1 | |
print('Selection: ' + str(col)) | |
print_board(board) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment