-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnect4.py
More file actions
73 lines (61 loc) · 2.28 KB
/
Connect4.py
File metadata and controls
73 lines (61 loc) · 2.28 KB
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
grid = []
for rowNumber in range(6):
grid.append(["-", "-", "-", "-", "-", "-", "-"])
# function to print the grid out
def printGrid():
# iterates through each row and each character in each row
for rowToPrint in grid:
stringToPrint = ""
for symbolToPrint in rowToPrint:
stringToPrint = stringToPrint + symbolToPrint + " "
print(stringToPrint)
# function to check if the board has a winner
def checkGameContinue(inputtedColumn, inputtedRow):
return True
def checkValidColumn(columnToCheck):
if columnToCheck.isdigit():
if 0 < int(columnToCheck) < 8:
return True
else:
return False
def checkRow(turnColumn):
# sets correct row to 10, which means that the tile is not placed
correctRow = 6
for rowToCheck in range(5, -1, -1):
if grid[rowToCheck][turnColumn] == "-" and correctRow == 6:
correctRow = rowToCheck
return correctRow
def rotateTurn(previousTurn):
if previousTurn == "X":
newTurn = "O"
else:
newTurn = "X"
return newTurn
# gives welcome text and prints the initial board
print("Welcome to Connect 4!")
printGrid()
# sets the starting players turn
playerTurn = "X"
# starts the game and keeps iterating till board is checked and a winner is recognised
gameRunning = True
while gameRunning:
# gets the column from the user
columnInput = input("Input a column: ")
# first checks that the input is a number 1-7 and formats the input accordingly
if checkValidColumn(columnInput):
columnInput = int(columnInput) - 1
# checks what row the tile will fall into, with 6 being that a tile cannot fit into the grid
selectedRow = checkRow(columnInput)
if selectedRow != 6:
# sets the spot to the player's character, switches the turn,
# checks if the game should continue and prints the grid
grid[selectedRow][columnInput] = playerTurn
playerTurn = rotateTurn(playerTurn)
gameRunning = checkGameContinue(columnInput, selectedRow)
printGrid()
else:
# outputs if the column is full
print("Column is full")
else:
# outputs if the column is not a number or an invalid number
print("Not a valid column number!")