vb.net - Connect four winner -
i'm trying check winner vertically , horizontally in connect 4. have playing board of 7,6 when click button change labels color. labels in 2 dimensional array. loop have created make see if there winner every time button clicked, doesn't work.
dim board(7,6) integer dim labelboard (7,6) label labelboard(0,0) = l00 'i have 41 others integer = 0 3 k integer = 0 3 if pturn =1 tag= "p1" 'horizontal win integer = 0 3 k integer = 0 6 if labelboard(i, k).tag.tostring = "p1" andalso labelboard(i + 1, k).tag.tostring = "p1" andalso labelboard(i + 2, k).tag.tostring = "p1" andalso labelboard(i + 3, k).tag.tostring = "p1" msgbox("game on player 1 wins.") end if next next
your current posted code doesn't need outer for
loops, , you'll index out of bound for k integer = 0 6
, there's 6 elements in dimension - labelboard(7, 6)
. should for k integer = 0 5
.
with changes in mind, following code (not tested) should trick:
if pturn = 1 tag = "p1" integer = 0 3 k integer = 0 5 if labelboard(i, k).tag.tostring() = tag andalso labelboard(i + 1, k).tag.tostring() = tag andalso lableboard(i + 2, k).tag.tostring() = tag andalso labelboard(i + 3, k).tag.tostring() = tag msgbox("game on player 1 wins.") end if next next
however, that's pretty brute force way it, , you're not flagging game over, displaying message box. approach use couple of while
loops (there other ways well). advantage of while
loop once connect 4 found, can exit loop (i efficiency, though still inefficient).
for example, assuming standard 6 rows, 7 columns, this:
dim currentrow integer = 0 dim currentcol integer = 0 dim connectfour boolean = false dim connectcount integer = 0 if pturn = 1 tag = "p1" while not connectfour , currentrow <= 5 currentcol = 0 connectcount = 0 while not connectcount = 4 , currentcol <= 6 if labelboard(currentcol, currentrow).tag.tostring() = tag connectcount = connectcount + 1 else connectcount = 0 end if currentcol = currentcol + 1 end while if connectcount = 4 connectfour = true else currentrow = currentrow + 1 end while
the above sets 4 local variables, 1 currentrow, 1 currentcolumn, 1 count of connected labels , flag whether or not connect 4 found.
the outer while
loop run long connectfour
false
, currentrow
less or equal 5.
the inner loop (as we're looking @ specific row) first resets current column 0 , connect count 0.
during inner loop, each column checked. if matches tag
, connectcount
incremented 1. if doesn't, connectcount
reset 0. currentcol
incremented 1 @ end of each iteration of inner loop.
when inner loop finished (either connect 4 found or we've reached end of current row) check value of connectcount
, , if it's 4 set connectfour
true
, end outer looop.
not different original code (modified), except won't check every row if connect 4 found on.
Comments
Post a Comment