Connect Four Game Python Matrix Again Random Play
Before starting off, permit us first understand what connect Four game actually is.
Connect4 game is also known asFour Up, Plot Four, Notice Four, Captain'southward Mistress, Iv in a Row, Driblet Four, and Gravitrips in the Soviet Union.
It is a two-player connection board game, in which the players choose a colour and then take turns dropping colored discs into a seven-column, six-row vertically suspended grid.
The pieces fall straight downwards, occupying the lowest available space within the column.
The objective of the game is to exist the first to form a horizontal, vertical, or diagonal line of iv of one'south own discs. Connect Four is a solved game.
The start role player can always win by playing the correct moves. Sounds fun right?
Let united states sympathize how to code this game in python programming language.
Import the necessary Libraries for the Connect Four Game
1. NumPy module
NumPy Library: NumPy stands for Numerical Python. NumPy is a Python library used for working with arrays. It also has functions for working in domain of linear algebra, fourier transform, and matrices. It is an open up source project and you can utilise it freely. NumPy is a Python library that provides a elementary however powerful data structure: the n-dimensional array.
If you don't have NumPy already pre-installed on your system, type the following command in your window's cmd:
C:\Users\Admin> pip install numpy
When you call the statement import numpy as np , you lot are shortening the phrase "numpy" to "np" to make your code easier to read. Information technology also helps to avoid namespace issues.
2. Pygame module
Pygame is a free and open up-source cross-platform library for the evolution of multimedia applications similar video games using Python.
Information technology uses the Simple DirectMedia Layer library and several other popular libraries to abstract the most common functions, making writing these programs a more intuitive job.
If you don't accept Pygame already pre-installed on your system, type the following command in your window's cmd:
C:\Users\Admin> pip install numpy
3. Python sys module
Thepython sys module provides functions and variables which are used to dispense different parts of thePython Runtime Surround. It lets united states access organisation-specific parameters and functions.import sys. First, nosotros take toimport thesys module in our program before running any functions.sys.modules.
4. Python math module
Some of the well-nigh popular mathematical functions are defined in the math module. These include trigonometric functions, representation functions, logarithmic functions, angle conversion functions, etc. In addition, 2 mathematical constants are also defined in this module.
If you don't take math already pre-installed on your organisation, type the following command in your window's cmd:
C:\Users\Admin> pip install maths
Implementing Connect Four Game in Python
Stride 01
Import the NumPy bundle equally np. So nosotros volition create a python function named create_board( ).
np.zeros( ) office is used to create a matrix total of zeroes. This role in Python tin can be used when you initialize the weights during the first iteration in TensorFlow and other statistic tasks. ((6,seven)) are the dimensions. vi rows and vii columns. Then we merely return that board.
We will begin writing the main game loop now. We're going to create a loop every bit while not game_over. A while not loop repeatedly executes the trunk of the loop until the condition for loop termination is met. Our loop is going to run equally long every bit this game_over variable is fake. We will initialize the game_over equally Imitation. The but fourth dimension its going to switch to truthful is if someone gets 4 circles in a row.
To increment the plough by i nosotros will apply turn += ane. To go far switch betwixt role player 1 and 2 alternatively, we use turn = turn % 2.
import numpy equally np def create_board(): board = np.zeros((6,7)) return lath #initialize board board = create_board() #We will initialize the game_over as Faux. game_over = False turn = 0 while not game_over: #Inquire for player 1 input if turn == 0: selection = int(input("Player i, Make your Pick(0-half-dozen):")) #Enquire for actor 2 input else: selection = int(input("Player ii, Brand your Selection(0-6):")) plow += 1 turn = turn % 2
Step 02
In the stride 02, we make a few alterations and updates to the previous code.
We want the selection variable to really drop a piece on the lath. For that, the first thing nosotros will do is create another iii functions called def drop_piece( ), def is_valid_location( ), def get_next_open_row( ).
How these functions are going to Piece of work together is equally follows, the role player will make a selection. The (0-six) in the code represents the cavalcade where they want to drop their piece. Hence nosotros update the name of selection variable to column variable (col).
Now we volition have this col in the electric current lath that we accept and pass it as parameters in all the 3 functions with board.
We will initialize global variables called ROW_COUNT and COLUMN_COUNT. In Python, a variable alleged exterior of the function or in global scope is known as a global variable. This ways that a global variable can be accessed inside or outside of the function.
The np.flip( ) part reverses the gild of array elements along the specified axis, preserving the shape of the array.
Syntax: np.flip(array, centrality)
import numpy as np ROW_COUNT = vi COLUMN_COUNT = seven def create_board(): board = np.zeros((6,7)) return board def drop_piece(board,row,col,piece): board[row][col]= piece def is_valid_location(board,col): #if this condition is true we will let the utilize drib piece here. #if non truthful that ways the col is not vacant render board[five][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)) board = create_board() print_board(board) game_over = Fake turn = 0 while not game_over: #Ask for player 1 input if turn == 0: col = int(input("Histrion 1, Brand your Selection(0-6):")) #Thespian i will drop a piece on the board if is_valid_location(board,col): row = get_next_open_row(board,col) drop_piece(board,row,col,i) #Ask for player 2 input else: col = int(input("Actor 2, Make your Pick(0-6):")) #Player 2 will drib a piece on the lath if is_valid_location(lath,col): row = get_next_open_row(lath,col) drop_piece(board,row,col,2) print_board(board) turn += 1 plow = turn % 2
Stride 03: Complete Lawmaking Walkthrough
In step 03, we will create a game with a GUI and not just the one with the matrices. The in a higher place code forth with the new modifications that we do volition make the game look similar an actual board game.
First we volition import all the necessary libraries.
Next we volition define the colours blue, black, ruby and yellow as global static variables. These values are going to be rgb values.
We will initialize global variables called ROW_COUNT and COLUMN_COUNT. Number of rows are 6 and number of columns are 7.
And then nosotros create five functions named create_board( ), drop_piece( ), is_valid_location( ), get_next_open_row( ) and print_board( ).
Then we create a function called winning_move() and we cheque for horizontal locations to win, vertical locations to win, positively and negatively sloped diagonals to win.
In horizontal and vertical locations, we create a nested for loop for the rows and columns and check an if condition statement to meet if the piece has been dropped to that location on the board. If the if condition is satisfied, information technology will return True. Nosotros volition repeat the same procedure for vertical locations, positively and negatively sloped diagonals as well.
In the part def draw_board( ), pygame.draw is a module for drawing shapes.
pygame.draw.rect is used to draw a rectangle. Now we volition define the triangle. Define the height and width and the position.
So the position is going to be, c*SQUARESIZE and the position of the y-axis is going to be r*SQUARESIZE+SQUARESIZE.
Height and width are going to be the other two parameters and thats only going to be SQUARESIZE, SQUARESIZE. Repeat the same procedure for circles as well.
import numpy as np import pygame import sys import math Bluish = (0,0,255) BLACK = (0,0,0) RED = (255,0,0) YELLOW = (255,255,0) ROW_COUNT = 6 COLUMN_COUNT = 7 def create_board(): board = np.zeros((ROW_COUNT,COLUMN_COUNT)) return board def drop_piece(lath, row, col, piece): board[row][col] = slice 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)) def winning_move(board, piece): # Check horizontal locations for win for c in range(COLUMN_COUNT-3): for r in range(ROW_COUNT): if board[r][c] == piece and board[r][c+1] == piece and lath[r][c+2] == slice and lath[r][c+iii] == piece: return True # Check vertical locations for win for c in range(COLUMN_COUNT): for r in range(ROW_COUNT-3): if board[r][c] == slice and board[r+1][c] == piece and lath[r+ii][c] == piece and board[r+3][c] == slice: return True # Check positively sloped diaganols for c in range(COLUMN_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] == slice and board[r+iii][c+three] == piece: return True # Bank check negatively sloped diaganols for c in range(COLUMN_COUNT-3): for r in range(3, ROW_COUNT): if lath[r][c] == piece and board[r-1][c+1] == piece and board[r-2][c+2] == piece and lath[r-3][c+iii] == piece: return True def draw_board(lath): for c in range(COLUMN_COUNT): for r in range(ROW_COUNT): pygame.draw.rect(screen, BLUE, (c*SQUARESIZE, r*SQUARESIZE+SQUARESIZE, SQUARESIZE, SQUARESIZE)) pygame.depict.circle(screen, Black, (int(c*SQUARESIZE+SQUARESIZE/ii), int(r*SQUARESIZE+SQUARESIZE+SQUARESIZE/two)), RADIUS) for c in range(COLUMN_COUNT): for r in range(ROW_COUNT): if board[r][c] == 1: pygame.describe.circumvolve(screen, RED, (int(c*SQUARESIZE+SQUARESIZE/ii), height-int(r*SQUARESIZE+SQUARESIZE/ii)), RADIUS) elif lath[r][c] == 2: pygame.depict.circumvolve(screen, Xanthous, (int(c*SQUARESIZE+SQUARESIZE/ii), superlative-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS) pygame.display.update() board = create_board() print_board(board) game_over = False turn = 0 #initalize pygame pygame.init() #define our screen size SQUARESIZE = 100 #define width and summit of board width = COLUMN_COUNT * SQUARESIZE height = (ROW_COUNT+1) * SQUARESIZE size = (width, height) RADIUS = int(SQUARESIZE/2 - five) screen = pygame.display.set_mode(size) #Calling part draw_board once again draw_board(board) pygame.display.update() myfont = pygame.font.SysFont("monospace", 75) while not game_over: for event in pygame.issue.get(): if issue.type == pygame.QUIT: sys.go out() if event.blazon == pygame.MOUSEMOTION: pygame.describe.rect(screen, Blackness, (0,0, width, SQUARESIZE)) posx = event.pos[0] if turn == 0: pygame.depict.circle(screen, RED, (posx, int(SQUARESIZE/2)), RADIUS) else: pygame.draw.circumvolve(screen, Xanthous, (posx, int(SQUARESIZE/ii)), RADIUS) pygame.display.update() if event.type == pygame.MOUSEBUTTONDOWN: pygame.draw.rect(screen, BLACK, (0,0, width, SQUARESIZE)) #print(event.pos) # Ask for Actor 1 Input if turn == 0: posx = event.pos[0] col = int(math.flooring(posx/SQUARESIZE)) if is_valid_location(board, col): row = get_next_open_row(board, col) drop_piece(board, row, col, i) if winning_move(lath, 1): label = myfont.render("Player 1 wins!!", 1, RED) screen.blit(label, (forty,10)) game_over = Truthful # # Ask for Thespian 2 Input else: posx = effect.pos[0] col = int(math.floor(posx/SQUARESIZE)) if is_valid_location(board, col): row = get_next_open_row(board, col) drop_piece(board, row, col, ii) if winning_move(board, 2): characterization = myfont.render("Histrion two wins!!", 1, YELLOW) screen.blit(characterization, (40,10)) game_over = True print_board(lath) draw_board(lath) turn += 1 turn = turn % 2 if game_over: pygame.time.wait(3000)
Our completed GUI Connect 4 Game in Python

Catastrophe notes…
This was the complete explanation of how to code the famous connect four game in Python. Pygame makes it easy for the users to learn and lawmaking a lot of games. I hope you will surely endeavor coding this and savour the game that you created yourself.
Happy Learning!
Source: https://www.askpython.com/python/examples/connect-four-game
0 Response to "Connect Four Game Python Matrix Again Random Play"
Post a Comment