Could you please help me / explain me how to create a four in a row game in python?
Thanks!

If you can explain how the "four in the row game" works, we will help you.

Hi eleonora,

I am assuming that this is like a big game of tic-tac-toe, where the first player to get four in a row wins.

You need to decide three things first:
(i) are you going to do this using just the command prompt or are you going to use a graphical interface like the one pygame provides?
(ii) how are you going to store the game board itself?
(iii) how will the computer opponent work?

I have no idea what you should do about (i). If you are new to Python then I recommend just doing things from the command prompt. However, once you get the hang of things, pygame is really simple to use.

As for (ii), the way I would do it is, I would store the game board as a dictionary. The dictionary would have keys which are (x,y) pairs and values that are either 0 (blank), 1 (red), or 2 (yellow). Then after every move, you can print the contents of this dictionary like so:

board = dict()
for x in range(7):
     for y in range(6):
          board[(x,y)] = 0        # Initializes the board to be blank
nobody_won_yet = True
while nobody_won_yet:
     # Display the board
     for x in range(7):
          for y in range(6):
               print board[(x,y)],
          print ""
     # Put code which lets player and opponent move here
     # Put code which checks to see if somebody won here

# At this point, presumably somebody won, so print a message

The most challenging part is (iii). I would design a computer opponent which checks the board for any three-in-a-row conditions, then tries to block them. If there are no three-in-a-row conditions, it builds on whatever rows it already has going. Otherwise, it randomly selects a spot on the grid - you can simulate random behavior by importing the random module and using random.sample().

Hope this helps!

1) Just the command prompt

2) I've done it as a dictionary

3) About the third part i have to do it as i) Human vs Pc[random play]
ii) Human vs. Human_2

#-----------------------------------------------------#

import random
from random import choice


##############################
# #
# FUNCTION === CREATES BOARD #
# #
##############################

class board:
def size_grid():

board = dict()
print
print "################################"
rows = input("Give number of rows: ")
print "-- -- -- -- -- -- -- -- --"
columns = input("Give number of columns: ")
print "################################"
print
print
print "######### "
print "# # "
print "# BOARD # "
print "# # "
print "######### "
print
print
min = 4
if rows < min:
print "Minimum rows & columns = 4"
size_grid()
elif columns < min:
print "Minimum rows & columns = 4"
grid()
else:
i = 1
for i in range(rows):
for y in range(columns):
board = (i+1,y+1)
print " | ",
print board,
print " ",
print "",
print


def choose_player():
choose = raw_input("P1 VS. COMPUTER" [1] , P1 VS. P2 [2] ")
if choose == "1":
#switch the p1 vs. computer function
choose_1()
elif choose == "2":
#switch the p1 vs. p2 function
choose_2()
else:
chooseplayer()

def choose_1():
########
#p1 turn
########
place_4 = raw_input("please choose column 1 to columns number choice")
place_4 = int(place_4)
while True:
if position[place_4 - 1] in ("1_B", "2_R"): #"1_B" = BLACK TOKEN___"2_R" = RED TOKEN
place_4 = raw_input("occupied column__ chose another one")
place_4 = int(place_4)
place_4 = "1_B"
else:
break
return place_4 - 1
return board

##############
#computer turn
##############
possibe_moves = []
for index in range(len(y)):
if board[index] == " ":
possible_moves.append(index)
move = random.choice(possible_moves)
board[move] = "2_R"
return board


def choose_2():


########
#p1 turn
########
p1_place_4 = raw_input("choose column")
p1_place_4 = int(p1_place_4):
while True:
if position[p1_place_4 - 1] in ("1_B , "2_B"):
p1_place_4 = raw_input("occupied, choose another one ")
p1_place_4 = int(p1_place_4)
else:
break
return p1_place_4 - 1
return board

########
#p2 turn
########
????????
????????


########################
# #
# IS_WINNER FUNCTION #
# #
########################

def isWinner(board,player):
if VerticalWin(board, player):
return 4
elif HorizontalWin(board, player):
return 4
elif DiagonalWin(board,player):
return 4
return 0

def VerticalWin(board,player):
x = board.last_move
y = len(board.state[x]) - 1
four_in_a_row = str(player) * 4
row = []
for i in range(-3, 4):
try:
if x+1 <0: continue
row.append(str(board.state[x+i][y]))
except IndexError:
row.append('s') # 's' stands for sentinel
return "".join(row).find(four_in_a_row) >= 0

def DiagonalWin(board,player):
x = board.last_move
y = len(board.state[x]) - 1
four_in_a_row = str(player) * 4
row = []
for i in range(-3, 4):
try:
if x+i<0: continue
if y+i<0: continue
row.append(str(board.state[x+i][y+i]))
except IndexError:
row.append('s')
if "".join(row).find(four_in_a_row) >= 0:
return 1
row = []
for i in range(-3, 4):
try:
if x+i < 0: continue
if y-1 < 0: continue
row.append(str(board.state[x+i][y-i]))
except IndexError:
row.append('s')
if "".join(row).find(four_in_a_row) >= 0:
return 1
return 0

Hi eleonora,

I can't read your code. Please re-post it enclosed in CODE tags.

But anyway, it doesn't look like this code even plays a game beyond the first turn (but I can't tell because I can't see the indents). What you should do is structure it like this:

board = make_board()
quit_game, player, winner = False, 0, "Nobody"
while not quit_game:
     move_player(player, board)
     if check_for_win(player, board):
          quitflag = True
          winner = "Player "+str(player%2+1)
     player = (player+1)%2
print player, "won!"

In other words, every iteration of the loop is a round of the game. In each round, we let a different player move (the player switches back and forth from 0 to 1). After each player moves, we check the board to see if that player has won. If the player won, we exit the loop by raising quitflag and set the winner to whatever player won. Then we print the winner's name.

A couple things to keep in mind:

Remember to check for stalemates. In that case, the winner should be "Nobody."

This version applies only to the case where there are two human players. You'll have to tweak things for the PC-vs-human case.

You could simplify the whole thing by forcing check_for_win() to return both a boolean and the winner string:

quitflag, winner = check_for_win(player, board)

Hope this helps.

import random


class board:
    def size_grid():

        board = dict()
        print 
        print 
        rows  = input("Give number of rows: ")
        print "--  --  --  --  --  -- --  -- --"
        columns = input("Give number of columns: ")
     
        min = 4
        if rows < min:
                print "Minimum rows & columns = 4"
                size_grid()
        elif columns < min:
                print "Minimum rows & columns = 4"
                grid()
        else:
                i = 1
        for i in range(rows):
            for y in range(columns):
                board = (i+1,y+1)
                print " | ",
                print board,
                print " ", 
                print "",
            print


def board(rows,columns):
    for i in range(rows):
        for y in range(columns):
            board = (i+1),(y+1)

    


def choose_player():
	choose = raw_input("P1 vs COMPUTER [1], P1 VS P2 [2] ")
	if choose == "1":
		#switch the p1 vs. computer function
		choose_1()
	elif choose == "2":
		#switch the p1 vs. p2 function
		choose_2()
	else:
		chooseplayer()

		


         
def choose_1():
    rows  = input("Give number of rows [more than 4]: ")
    print
    columns = input("Give number of columns [more than 4]: ")
    board = dict()
    i = 1
    for x in range(rows):
        for y in range(columns):
            board = (x+1,y+1)
            

    board = 0
    for i in range(rows*columns):
        #p1 turn
        if i%2 <> 0:
            i = 1
            def size(columns,rows):
                y = raw_input("please choose column: 1 to columns number choice ")
                if y>=columns:
                    size(columns,rows)
                else:
                    x = rows
                    while x>=1:
                        if (x,y)==0:
                            (x,y) == "R"
                            x == 0
                        else:
                            x = x - 1
                
            size(columns,rows)
                
        else:
            
            #computer turn
            x = rows
            y = random.choice(columns)
            while x>=1:
                if (x,y) == 0:
                    (x,y) == "B"
                    print (x,y)
                    x = 0
                else:
                    x = x - 1
                    print (x,y)
            

    
def choose_2():
    rows  = input("Give number of rows [more than 4]: ")
   
    columns = input("Give number of columns [more than 4]: ")
    board = dict()
    i = 1
    for i in range(rows):
        for y in range(columns):
            board = (i+1,y+1)
            
    
    for i in range(rows*columns):
        #p1 turn
        if i%2 <> 0:
            place_4 = raw_input("please choose column: 1 to columns number choice ")
            x = rows
            while x>=1:
                if (x,place_4) == 0:
                    x,place_4 == "R"
                    (x,place_4) == last.move
                    x == 0
                else:
                    x = x-1
                    
        else:
            #p2 turn
            place_4 = raw_input("please choose column: 1 to to columns number choice ")
            x = rows
            while x>=1:
                if (x,place_4) == 0:
                    x,place_4 == "R"
                    x == 0
                else:
                    x = x-1


def game():
    choose_player()

Hi eleonora,

Okay. So what do you want help with?

how will i check whether there is a winner ? :-/

Hi eleonora,

Okay. Here's the naive approach. After every turn, call a function which examines the board. For every cell in the grid, check to see if that cell and the four succeeding cells are all the same.

So, you would make a function like this:

# Suppose that player 1 just moved
for x in range(x_max):
     for y in range(y_max):
          # Horizontal check
          try:
               if (board[(x,y)] == 1 and board[(x+1,y)] == 1 and
                   board[(x+2,y)] == 1 and board[(x+3,y)] == 1): return True
          except Exception, e: pass # So we don't try to access cells not in the grid
          # Vertical check
          try:
               if (board[(x,y)] == 1 and board[(x,y+1)] == 1 and
                   board[(x,y+2)] == 1 and board[(x,y+3)] == 1): return True
          except Exception, e: pass
          # Diagonal check
          # For the diagonals we need to do two checks: up-left to low-right and
          # low-left to up-right
          try:
               if (board[(x,y)] == 1 and board[(x+1,y+1)] == 1 and
                   board[(x+2,y+2)] == 1 and board[(x+3,y+3)] == 1): return True
          except Exception, e: pass
          try:
               if (board[(x,y)] == 1 and board[(x-1,y+1)] == 1 and
                   board[(x-2,y+2)] == 1 and board[(x-3,y+3)] == 1): return True
          except Exception, e: pass
return False

It's wasteful because it checks cells more than once. To make this cleaner, just keep track of the last move and only check for 4-in-a-rows around that position.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.