gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
generate a connect 4 game
- User
generate a connect 4 game
- Assistant
generate a connect 4 game
Absolutely, I can help you create a simple text-based Connect 4 game in Python. Below is a basic implementation:
import numpy as np
# Constants
ROWS = 6
COLUMNS = 7
PLAYER_ONE = 1
PLAYER_TWO = 2
def create_board():
return np.zeros((ROWS, COLUMNS))
def drop_piece(board, row, col, piece):
board[row][col] = piece
def is_valid_location(board, col):
return board[ROWS-1][col] == 0
def get_next_open_row(board, col):
for r in range(ROWS):
if board[r][col] == 0:
return r
def print_board(board):
print(np.flip(board, 0))
def winning_move(board, piece):
# Check horizontal locations for win
for c in range(COLUMNS-3):
for r in range(ROWS):
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(COLUMNS):
for r in range(ROWS-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 c in range(COLUMNS-3):
for r in range(ROWS-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 c in range(COLUMNS-3):
for r in range(3, ROWS):
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
while not game_over:
# Ask for Player 1 Input
if turn == 0:
col = int(input("Player 1 Make your Selection (0-6):"))
if is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, PLAYER_ONE)
if winning_move(board, PLAYER_ONE):
print("PLAYER 1 WINS!!")
game_over = True
# Ask for Player 2 Input
else:
col = int(input("Player 2 Make your Selection (0-6):"))
if is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, PLAYER_TWO)
if winning_move(board, PLAYER_TWO):
print("PLAYER 2 WINS!!")
game_over = True
print_board(board)
turn += 1
turn = turn % 2
create_board() initializes the board with zeros.drop_piece() places a player's piece in the correct row and column.is_valid_location() checks if the selected column has space for a new piece.get_next_open_row() finds the next available row for a piece.print_board() prints the board (flipped to show the correct orientation).winning_move() checks all possible ways to win the game (horizontal, vertical, positive and negative diagonals).connect4.py).python connect4.py.Feel free to modify and enhance this code!
Not yet included in a published release.