'Trying to figure out horizontal wins for a connect 4 game in python
ive been trying to make a connect four game. As I was following a tutorial it abruptly ended and I wanting to finish it.
Right now im making win functions so the game can see if 4 peices are next to eachother horizontally. Right now i have this and it does give me a win if we put 4 peices in the first four colums. But if we do it on the last four the game continues which it should give the player a win.
(Im new to stack overflow sorry for the bad wording. You should try it yourself on your own IDE)
This snippet is running in html. It is a python program!
# Connect Four
# Creates 2d board list
numRows = 6
numCols = 7
board = [[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0], ]
### Prints board in 0's for empty boxs, and 1s, and 2s for players
def printBoard():
for rows in range(0, numRows):
for cols in range(0, numCols):
print(board[rows][cols], end=' ')
print(" ")
# Goes through all rows and checks if the player can place it there, if not it writes one above it
def fillIn(col, player):
col = col - 1
for rows in range(numRows - 1, -1, -1):
if board[rows][col] == 0:
print("Legal Move")
board[rows][col] = player
break
def win():
if horizWin() or vertWin() or diagWin():
return True
return False
def horizWin():
for row in board:
for i in range(len(row) - 4):
window = row[i:i + 4]
# check if all elements in the row are 1s or 2s
if window.count(window[0]) == len(window) and window[0] in [1, 2]:
print("You Win!")
return True
def vertWin():
for col in board:
()
def diagWin():
pass
player = 1
while not win():
col = int(input("Please Select A Colum 1-7: "))
if col > 7:
print("That colum is over 7!")
fillIn(col, player)
printBoard()
if player == 1:
player = 2
else:
player = 1
Solution 1:[1]
Cool project!
Python's range excludes the upper bound, meaning range(n) produces [0, 1, 2, ..., n-1], and range(len(row) - 4), like you have, will produce [0, 1, 2, ..., len(row)-5]. If you want the last 4 elements of a row ([row[len(row)-4], row[len(row)-3], row[len(row)-2], row[len(row)-1]]), you need to start on i = len(row)-4. Currently your code doesn't do this, because it has the line for i in range(len(row) - 4):. Try changing that to for i in range(len(row) - 3):.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
