我正在开展一个井字游戏计划。 CHECK_WINNER函数应该接收一个给定状态的棋盘,并确定游戏是否已获胜,并列,或者玩家是否需要继续游戏。 CHECK_WINNER根据电路板的状态采用不同的值。
胜利块(n; 1:3)列出了一个井字棋盘的8种可能的获胜配置。
我认为问题出在do循环中。我的目标是为每个玩家(1和2)循环完成棋盘的每个获胜场景,并检查是否已满足获胜条件。如果玩家1获胜,CHECK_MOVE应为1,如果玩家2获胜则为2,如果游戏为平局则为3,对于任何其他情况为0。我究竟做错了什么?
program checkwinner
implicit none
integer, dimension(9) :: board
integer, external :: CHECK_WINNER
integer :: cw
!board = (/ 1,2,1,2,1,2,2,2,1 /) ! not working correctly. 1 is winner, board full; cw returns 3
!board = (/ 1,2,1,2,0,2,2,2,1 /) ! working correctly. no winner, open spaces; cw returns 0
!board = (/ 1,1,1,0,0,0,0,0,0 /) ! not working. cw should return 1; instead cw returns 0
board = (/ 2,2,2,0,0,0,0,0,0 /) ! not working
cw = CHECK_WINNER(board)
print *, board(1:3)
print *, board(4:6)
print *, board(7:9)
print *, cw
end program checkwinner
!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!
integer function CHECK_WINNER(fboard)
implicit none
integer :: i
integer, dimension(8,3) :: win
integer, dimension(9), intent(in) :: fboard
win(1,1:3) = (/ 1,2,3 /)
win(2,1:3) = (/ 4,5,6 /)
win(3,1:3) = (/ 7,8,9 /)
win(4,1:3) = (/ 1,4,7 /)
win(5,1:3) = (/ 2,5,8 /)
win(6,1:3) = (/ 3,6,9 /)
win(7,1:3) = (/ 1,5,9 /)
win(8,1:3) = (/ 3,5,7 /)
do i = 1,8
if (fboard(win(i,1)) == 1 .and. fboard(win(i,2)) == 1 .and. fboard(win(i,3)) == 1) then
CHECK_WINNER = 1
else if (fboard(win(i,1)) == 2 .and. fboard(win(i,2)) == 2 .and. fboard(win(i,3)) == 2) then
CHECK_WINNER = 2
else if ((fboard(win(i,1)) == 1 .or. fboard(win(i,1)) == 2) .and. (fboard(win(i,2)) == 1 .or. &
fboard(win(i,2)) == 2) .and. (fboard(win(i,3)) == 1 .or. fboard(win(i,3)) == 2)) then
CHECK_WINNER = 3
else
CHECK_WINNER = 0
end if
end do
end function CHECK_WINNER
答案 0 :(得分:1)
因此,在函数的do循环中board = (/ 2,2,2,0,0,0,0,0,0 /)
时,您在代码中使用i=1
给出了它,它正确设置了CHECK_WINNER = 2,因为
fboard(win(i,1)) == 2 .and. fboard(win(i,2)) == 2 .and. fboard(win(i,3)) == 2
是真的。不幸的是,当循环到达i = 2,i = 3等时,它将CHECK_WINNER重置为零,因为没有胜利条件匹配。这是造成问题的else
块。将do循环更改为
CHECK_WINNER = 0
do i = 1,8
if (fboard(win(i,1)) == 1 .and. fboard(win(i,2)) == 1 .and. fboard(win(i,3)) == 1) then
CHECK_WINNER = 1
else if (fboard(win(i,1)) == 2 .and. fboard(win(i,2)) == 2 .and. fboard(win(i,3)) == 2) then
CHECK_WINNER = 2
else if ((fboard(win(i,1)) == 1 .or. fboard(win(i,1)) == 2) .and. (fboard(win(i,2)) == 1 .or. &
fboard(win(i,2)) == 2) .and. (fboard(win(i,3)) == 1 .or. fboard(win(i,3)) == 2)) then
CHECK_WINNER = 3
end if
end do
所以如果找到已知的组合,它会设置CHECK_WINNER。只要在每个(else)if子句中使用exit
找到已知组合,您也可以退出循环。 (在设置CHECK_WINNER之后)