frommathimport*fromcmathimportsqrtimportmatplotlib.pyplotaspltimportturtleimportrandomimportkandinskyaskdimporttime# Connect Four game functions
defcreate_board(rows,cols):return[[0for_inrange(cols)]for_inrange(rows)]defmake_move(board,col,player):row=len(board)-1whileboard[row][col]!=0:row-=1board[row][col]=playerdefis_winner(board,player):# Check rows
forrowinboard:if[player]*4in[row[i:i+4]foriinrange(len(row)-3)]:returnTrue# Check columns
forjinrange(len(board[0])):if[player]*4in[[board[i][j],board[i+1][j],board[i+2][j],board[i+3][j]]foriinrange(len(board)-3)]:returnTrue# Check diagonals
foriinrange(len(board)-3):forjinrange(len(board[0])-3):ifboard[i][j]==playerandboard[i+1][j+1]==playerandboard[i+2][j+2]==playerandboard[i+3][j+3]==player:returnTrueforiinrange(len(board)-3):forjinrange(3,len(board[0])):ifboard[i][j]==playerandboard[i+1][j-1]==playerandboard[i+2][j-2]==playerandboard[i+3][j-3]==player:returnTruereturnFalsedefai_algorithm(board):returnrandom.choice([colforcolinrange(len(board[0]))ifboard[0][col]==0])# Graphics functions
definit():kd.fill_rect(0,0,kd.get_screen_width(),kd.get_screen_height(),(255,255,255))defclose():passdefdisplay_board(board):kd.clear()kd.draw_string('Connect Four',10,10)kd.draw_string('Generation: {}'.format(generation),10,40)forrowinrange(len(board)):forcolinrange(len(board[0])):ifboard[row][col]==0:kd.fill_rect(col*40+20,row*40+60,40,40,(255,255,255))elifboard[row][col]==1:kd.fill_circle(col*40+40,row*40+80,16,(255,0,0))else:kd.fill_circle(col*40+40,row*40+80,16,(0,0,255))kd.show()defkey_down(key):returnFalsedefset_auto_refresh(enable):pass# Main loop
defmain():init()set_auto_refresh(False)generation=1whilenotkey_down(KEY_OK):display_board(board)col=ai_algorithm(board)make_move(board,col,1)ifis_winner(board,1):print("AI wins!")breakcol=ai_algorithm(board)make_move(board,col,2)ifis_winner(board,2):print("Player wins!")breakgeneration+=1time.sleep(0.5)close()if__name__=='__main__':main()
During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:
Ensure the proper functioning of the site (essential cookies); and
Track your browsing to send you personalized communications if you have created a professional account on the site and can be contacted (audience measurement cookies).
With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.