battleship.tcl 65.5 KB
Newer Older
1 2 3 4
# battleship.tcl --
#
#       This file implements a Battleship game plugin for the Tkabber XMPP
#       client.
5 6 7 8 9 10 11

package require msgcat

namespace eval battleship {
    ::msgcat::mcload [file join [file dirname [info script]] msgs]

    if {![::plugins::is_registered battleship]} {
12 13 14 15 16 17 18 19
        ::plugins::register battleship \
                            -namespace [namespace current] \
                            -source [info script] \
                            -description [::msgcat::mc "Whether the Battleship\
                                                        plugin is loaded."] \
                            -loadcommand [namespace code load] \
                            -unloadcommand [namespace code unload]
        return
20 21
    }

22 23
    variable winid 0

24 25 26 27 28 29 30 31
    package require sha1

    variable square_size 27
    variable line_width 1

    variable board_size 10

    variable ships \
32
        {carrier 1 battleship 1 destroyer 1 cruiser 2 submarine 2}
33 34

    variable sizes \
35
        {carrier 5 battleship 4 destroyer 3 cruiser 2 submarine 1}
36 37 38

    variable themes
    set dirs \
39 40
        [glob -nocomplain -directory [file join [file dirname [info script]] \
                                                pixmaps] *]
41
    foreach dir $dirs {
42
        pixmaps::load_theme_name [namespace current]::themes $dir
43 44 45
    }
    set values {}
    foreach theme [lsort [array names themes]] {
46
        lappend values $theme $theme
47 48 49 50 51
    }

    custom::defgroup Plugins [::msgcat::mc "Plugins options."] -group Tkabber

    custom::defgroup Battleship [::msgcat::mc "Battleship plugin options."] \
52
        -group Plugins
53 54

    custom::defvar options(theme) Copybook \
55 56 57 58 59
        [::msgcat::mc "Battleship pixmaps theme."] \
        -group Battleship \
        -type options \
        -values $values \
        -command [namespace code load_stored_theme]
60
    custom::defvar options(show_last_move) 0 \
61 62
        [::msgcat::mc "Show last move by default."] \
        -type boolean -group Battleship
63
    custom::defvar options(show_tooltips) 1 \
64 65 66
        [::msgcat::mc "Show tooltips with short instructions."] \
        -type boolean -group Battleship \
        -command [namespace code set_tooltips]
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
}

proc battleship::load {} {
    hook::add postload_hook [namespace current]::load_stored_theme 70

    hook::add roster_create_groupchat_user_menu_hook \
              [namespace current]::add_groupchat_user_menu_item 48.5
    hook::add chat_create_user_menu_hook \
              [namespace current]::add_groupchat_user_menu_item 48.5
    hook::add roster_jid_popup_menu_hook \
              [namespace current]::add_groupchat_user_menu_item 48.5

    hook::add games_board_create_hook [namespace current]::iq_create
    hook::add games_board_init_hook [namespace current]::iq_init
    hook::add games_board_turn_hook [namespace current]::iq_turn

    ::xmpp::iq::register set create games:board \
84
                         [namespace parent]::iq_games_board_create
85
    ::xmpp::iq::register set board games:board \
86
                         [namespace parent]::iq_games_board_init
87
    ::xmpp::iq::register set turn games:board \
88
                         [namespace parent]::iq_games_board_turn
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

    load_stored_theme
}

proc battleship::unload {} {
    hook::remove postload_hook [namespace current]::load_stored_theme 70

    hook::remove finload_hook [namespace current]::calc_moves 100

    hook::remove roster_create_groupchat_user_menu_hook \
              [namespace current]::add_groupchat_user_menu_item 48.5
    hook::remove chat_create_user_menu_hook \
              [namespace current]::add_groupchat_user_menu_item 48.5
    hook::remove roster_jid_popup_menu_hook \
              [namespace current]::add_groupchat_user_menu_item 48.5

    hook::remove games_board_create_hook [namespace current]::iq_create
    hook::remove games_board_turn_hook [namespace current]::iq_turn

    if {[hook::is_empty games_board_create_hook]} {
        ::xmpp::iq::unregister set create games:board
        rename [namespace parent]::iq_games_board_create ""
    }

    if {[hook::is_empty games_board_init_hook]} {
        ::xmpp::iq::unregister set board games:board
        rename [namespace parent]::iq_games_board_init ""
    }

    if {[hook::is_empty games_board_turn_hook]} {
        ::xmpp::iq::unregister set turn games:board
        rename [namespace parent]::iq_games_board_turn ""
    }

    foreach var [info vars [namespace current]::*] {
        upvar #0 $var flags
        if {[info exists flags(window)]} {
            destroy_win $flags(window)
        }
    }

130
    foreach w [winfo children .] {
131 132 133 134 135 136 137
        if {[regexp {^\.battleship_invite} $w]} {
            catch {
                set wf [$w getframe]
                bind $wf <Destroy> {}
            }
            destroy $w
        }
138 139
    }

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    foreach var [info vars [namespace current]::*] {
        if {$var ne "[namespace current]::options"} {
            unset $var
        }
    }

    foreach img [image names] {
        if {[string first battleship/ $img] == 0} {
            image delete $img
        }
    }
}

proc battleship::load_stored_theme {args} {
    variable options
    variable themes

    pixmaps::load_dir $themes($options(theme))
}

proc battleship::invite_dialog {xlib jid} {
161
    variable winid
162

163
    set w .battleship_invite[incr winid]
164 165

    Dialog $w -title [::msgcat::mc "Battleship Invitation"] \
166 167
              -anchor e \
              -default 0
168 169

    set wf [$w getframe]
170 171 172 173 174
    Message $wf.message -aspect 50000 \
            -text [::msgcat::mc "Sending Battleship game invitation\
                                 to %s (%s)" \
                                [chat::get_nick $xlib $jid chat] \
                                $jid]
175 176 177
    pack $wf.message -pady 2m

    $w add -text [::msgcat::mc "I want to move first"] \
178
        -command [namespace code [list invite $w $xlib $jid true]]
179
    $w add -text [::msgcat::mc "I want to move second"] \
180
        -command [namespace code [list invite $w $xlib $jid false]]
181
    $w add -text [::msgcat::mc "Cancel invitation"] \
182
        -command [list destroy $w]
183 184 185 186

    $w draw
}

187 188
proc battleship::invite {w xlib jid first} {
    destroy $w
189

190
    set id battleship[rand 1000000000]
191 192 193 194 195

    # FIX
    #set rjid [get_jid_of_user $jid]

    ::xmpp::sendIQ $xlib set \
196 197 198 199 200 201 202
        -query [::xmpp::xml::create create \
                        -xmlns games:board \
                        -attrs [list type battleship \
                                     id $id \
                                     first $first]] \
        -to $jid \
        -command [namespace code [list invite_res $xlib $jid $id $first]]
203 204 205
}

proc battleship::invite_res {xlib jid id first status xml} {
206 207
    variable winid

208
    if {![string equal $status ok]} {
209
        set w .battleship_invite_error[incr winid]
210

211 212 213 214 215 216
        after idle [list NonmodalMessageDlg $w -aspect 50000 -icon error \
            -message [::msgcat::mc "%s (%s) has refused Battleship\
                                    invitation: %s" \
                                   [chat::get_nick $xlib $jid chat] \
                                   $jid [error_to_string $xml]]]
        return ""
217 218 219 220 221 222
    }

    start_play $xlib $jid $id $first
}

proc battleship::invited_dialog {xlib jid iqid id first} {
223
    variable winid
224

225
    set w .battleship_invited[incr winid]
226 227

    Dialog $w -title [::msgcat::mc "Battleship Invitation from %s" $jid] \
228
              -modal none -anchor e -default 0
229 230

    set wf [$w getframe]
231 232
    bind $wf <Destroy> \
         [namespace code [list invited_res $w $xlib $jid $iqid $id $first 0]]
233 234

    set nick [chat::get_nick $xlib $jid chat]
235 236 237
    set message1 [::msgcat::mc "Battleship game invitation from %s (%s)\
                                is received." \
                               $nick $jid]
238
    switch -- $first {
239 240 241 242 243 244 245 246 247 248 249 250 251 252
        true -
        1 {
            set message2 [::msgcat::mc "%s wants to move first." $nick]
        }
        false -
        0 {
            set message2 [::msgcat::mc "%s wants to move second." $nick]
        }
        default {
            return [list error modify bad-request]
        }
    }
    Message $wf.message1 -aspect 50000 -text $message1
    Message $wf.message2 -aspect 50000 -text $message2
253 254
    pack $wf.message1 -pady 1m
    pack $wf.message2 -pady 1m
255

256
    $w add -text [::msgcat::mc "Agree to play"] \
257 258
           -command [namespace code \
                        [list invited_res $w $xlib $jid $iqid $id $first 1]]
259
    $w add -text [::msgcat::mc "Refuse to play"] \
260 261
           -command [namespace code \
                        [list invited_res $w $xlib $jid $iqid $id $first 0]]
262 263 264 265 266 267 268

    $w draw
    return
}

proc battleship::invited_res {w xlib jid iqid id first result} {
    catch {
269 270 271
        set wf [$w getframe]
        bind $wf <Destroy> {}
        destroy $w
272 273 274
    }

    if {$result} {
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
        switch -- $first {
            true -
            1 {
                start_play $xlib $jid $id false
            }
            false -
            0 {
                start_play $xlib $jid $id true
            }
            default {
                ::xmpp::sendIQ $xlib error \
                               -error [::xmpp::stanzaerror::error \
                                                modify bad-request] \
                               -to $jid \
                               -id $iqid
            }
        }
292 293 294

        ::xmpp::sendIQ $xlib result \
                       -query [::xmpp::xml::create create \
295 296 297
                                        -xmlns games:board \
                                        -attrs [list type battleship \
                                                     id $id]] \
298 299 300
                       -to $jid \
                       -id $iqid
    } else {
301 302 303 304 305
        ::xmpp::sendIQ $xlib error \
                       -error [::xmpp::stanzaerror::error \
                                        modify not-acceptable] \
                       -to $jid \
                       -id $iqid
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    }
    return
}

proc battleship::start_play {xlib jid id first} {
    set gid [make_gid $jid $id]
    variable $gid
    upvar 0 $gid state

    set state(window) [win_id battleship $gid]
    set state(xlib) $xlib
    set state(opponent) $jid
    set state(id) $id
    set state(move_first) $first

    trace variable [namespace current]::${gid}(position,turn) w \
322
                   [namespace code [list set_label_move $gid]]
323 324 325 326 327 328 329 330 331

    open_win $gid
}

proc battleship::set_label_move {gid args} {
    variable $gid
    upvar 0 $gid state

    switch -- $state(position,turn) {
332 333 334 335 336 337 338
        first -
        second {
            set move 1
        }
        default {
            set move 0
        }
339 340
    }
    if {$move && [is_my_move $gid]} {
341 342 343 344 345 346
        if {$state(board_is_sent) && $state(board_is_received)} {
            set state(move_label) [::msgcat::mc "You"]
        } else {
            set state(move_label) \
                [::msgcat::mc "You (after all parties freeze boards)"]
        }
347
    } else {
348 349 350 351 352 353
        if {$state(board_is_sent) && $state(board_is_received)} {
            set state(move_label) [::msgcat::mc "Opponent"]
        } else {
            set state(move_label) \
                [::msgcat::mc "Opponent (after all parties freeze boards)"]
        }
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    }
}

proc battleship::save_position {gid} {
    variable $gid
    upvar 0 $gid state

    set state(saved_position) [array get state position,*]
}

proc battleship::restore_position {gid} {
    variable $gid
    upvar 0 $gid state

    array set state $state(saved_position)
    draw_position $gid
    update_controls $gid
    find_reasonable_moves $gid $state(position,turn)
}

proc battleship::make_gid {jid id} {
    jid_to_tag [concat $jid $id]
}

proc battleship::board_recv {gid xmlElements} {
    variable board_size
    variable options
    variable $gid
    upvar 0 $gid state

    if {[llength [array names state hash,*]] == 0} {
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
        # Receiving hashes

        set numhashes 0
        set state(shiphashes) {}

        foreach element $xmlElements {
            ::xmpp::xml::split $element tag xmlns attrs cdata subels
            switch -- $tag {
                cell {
                    set c [::xmpp::xml::getAttr $attrs col]
                    set r [::xmpp::xml::getAttr $attrs row]
                    set hash [::xmpp::xml::getAttr $attrs hash]

                    if {![string is integer -strict $c] || \
                            $c < 0 || $c >= $board_size} {
                        return [list error modify bad-request]
                    }
                    if {![string is integer -strict $r] || \
                            $r < 0 || $r >= $board_size} {
                        return [list error modify bad-request]
                    }
                    if {$hash != "" && ![info exists state(hash,$c,$r)]} {
                        set state(hash,$c,$r) $hash
                        incr numhashes
                    } else {
                        return [list error modify bad-request]
                    }
                }
                ship {
                    lappend state(shiphashes) \
                            [::xmpp::xml::getAttr $attrs hash]
                }
            }
        }

        if {$numhashes == [expr {$board_size * $board_size}]} {
            set state(board_is_received) 1
            set_label_move $gid
            update_controls $gid
            find_reasonable_moves $gid $state(position,turn)

            return [list result {}]
        } else {
            array unset state hash,*
            array unset state shiphashes

            return [list error modify bad-request]
        }
433
    } else {
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
        # Checking hashes

        set numhashes 0
        set cells {}

        foreach element $xmlElements {
            ::xmpp::xml::split $element tag xmlns attrs cdata subels
            switch -- $tag {
                cell {
                    set c [::xmpp::xml::getAttr $attrs col]
                    if {![string is integer -strict $c] || \
                            $c < 0 || $c >= $board_size} {
                        attention_message $gid \
                                [::msgcat::mc "\n\n Opponent sent incorrect\
                                               cell column"]
                        return [list error modify bad-request]
                    }

                    set r [::xmpp::xml::getAttr $attrs row]
                    if {![string is integer -strict $r] || \
                            $r < 0 || $r >= $board_size} {
                        attention_message $gid \
                                [::msgcat::mc "\n\n Opponent sent incorrect\
                                               cell row"]
                        return [list error modify bad-request]
                    }

                    set seed [::xmpp::xml::getAttr $attrs seed]
                    if {[::xmpp::xml::getAttr $attrs ship]} {
                        set ship 1
                    } else {
                        set ship 0
                    }

                    if {[sha1::sha1 $seed$ship] ne $state(hash,$c,$r)} {
                        attention_message $gid \
                                [::msgcat::mc "\n\n Opponent sent incorrect\
                                               cell seed"]
                        return [list error modify bad-request]
                    }

                    lappend cells [list $c $r]
                    set board($c,$r) $ship
                    incr numhashes
                }
            }
        }

        if {$numhashes != $board_size*$board_size ||
                [llength [lsort -unique $cells]] != $board_size*$board_size} {
            attention_message $gid \
                    [::msgcat::mc "\n\n Opponent sent incorrect number\
                                   of cells"]
            return [list error modify bad-request]
        }

        if {![test_legal [array get board]]} {
            attention_message $gid \
                    [::msgcat::mc "\n\n Opponent sent illegal board"]
            return [list error modify bad-request]
        }

        return [list result {}]
497 498 499 500 501 502 503 504 505 506
    }
}

proc battleship::test_legal {boardlist} {
    variable board_size
    variable ships
    variable sizes

    array set board $boardlist
    foreach c [list -1 $board_size] {
507 508 509 510
        for {set r -1} {$r <= $board_size} {incr r} {
            set board($c,$r) 0
            set board($r,$c) 0
        }
511
    }
512

513 514 515
    array set size $sizes

    foreach {name number} $ships {
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
        for {set i 1} {$i <= $number} {incr i} {
            lassign [find_ship board $size($name)] status c1 r1 c2 r2

            if {!$status} {
                return 0
            }

            for {set c $c1} {$c <= $c2} {incr c} {
                for {set r $r1} {$r <= $r2} {incr r} {
                    set board($c,$r) 0
                }
            }
            for {set c [expr {$c1-1}]} {$c <= $c2+1} {incr c} {
                for {set r [expr {$r1-1}]} {$r <= $r2+1} {incr r} {
                    if {$board($c,$r) == 1} {
                        return 0
                    }
                }
            }
        }
536 537 538 539 540 541 542 543 544
    }
    return 1
}

proc battleship::find_ship {vboard size} {
    variable board_size
    upvar $vboard board

    for {set c1 0} {$c1 < $board_size} {incr c1} {
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
        for {set r1 0} {$r1 <= $board_size} {incr r1} {
            if {$board($c1,$r1) == 0} continue

            set q 1
            set c2 $c1
            for {set r2 $r1} {$r2 < $r1+$size} {incr r2} {
                if {$board($c2,$r2) == 0} {
                    set q 0
                    break
                }
            }
            if {$q} {
                return [list 1 $c1 $r1 $c2 [incr r2 -1]]
            }

            set q 1
            set r2 $r1
            for {set c2 $c1} {$c2 < $c1+$size} {incr c2} {
                if {$board($c2,$r2) == 0} {
                    set q 0
                    break
                }
            }
            if {$q} {
                return [list 1 $c1 $r1 [incr c2 -1] $r2]
            }
        }
572 573 574 575 576 577 578 579 580 581 582 583 584 585
    }
    return {0}
}

proc battleship::turn_recv {gid xmlElements} {
    variable board_size
    variable options
    variable $gid
    upvar 0 $gid state

    set move 0
    set draw 0

    foreach element $xmlElements {
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
        ::xmpp::xml::split $element tag xmlns attrs cdata subels
        switch -- $tag {
            shot {
                set c [::xmpp::xml::getAttr $attrs col]
                set r [::xmpp::xml::getAttr $attrs row]
                if {![string is integer -strict $c] || \
                        ![string is integer -strict $r] || \
                        $c < 0 || $c >= $board_size || \
                        $r < 0 || $r >= $board_size} {
                    return [list error modify not-acceptable]
                }
                set move 1
            }
            resign {
                end_game $gid 1 [::msgcat::mc "You win (Opponent resigned)"]
                update_controls $gid
                draw_position $gid
                highlight_last_move $gid
                return [list result [::xmpp::xml::create turn \
                                            -xmlns games:board \
                                            -attrs [list type battleship \
                                                         id $state(id)]]]
            }
            accept {
                if {$state(position,draw)} {
                    end_game $gid 0.5 [::msgcat::mc "Draw (Opponent accepted)"]
                    update_controls $gid
                    draw_position $gid
                    highlight_last_move $gid
                    return [list result [::xmpp::xml::create turn \
                                            -xmlns games:board \
                                            -attrs [list type battleship \
                                                         id $state(id)]]]
                } else {
                    return [list error modify not-acceptable]
                }
            }
            draw {
                set draw 1
            }
        }
627 628 629
    }

    if {$move} {
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
        set hit 0
        foreach ship $state(position,ships) {
            set sunk 1
            foreach {sc sr} [coordinates $ship] {
                if {$c == $sc && $r == $sr} {
                    set hit 1
                } elseif {$state(position,oshot,$sc,$sr) != 1} {
                    set sunk 0
                }
            }
            if {$hit} {
                break
            }
        }

        if {$hit && $sunk} {
            set result destroy
            lappend state(position,destroyed_my_ships) $ship
        } elseif {$hit} {
            set result hit
        } else {
            set result miss
        }

        if {[do_move $gid $c $r $result $draw]} {
            update_controls $gid $draw
            draw_position $gid
            highlight_last_move $gid

            set subel [::xmpp::xml::create shot \
                                -attrs [list result $result \
                                             seed $state(seed,$c,$r)]]
            return [list result [::xmpp::xml::create turn \
                                        -xmlns games:board \
                                        -attrs [list type battleship \
                                                     id $state(id)] \
                                        -subelement $subel]]
        } else {
            return [list error modify not-acceptable]
        }
670
    } else {
671
        return [list error modify not-acceptable]
672 673 674 675 676 677 678 679 680 681
    }
}

###############################################################################

proc battleship::center {c r} {
    variable square_size
    variable line_width

    list [expr {$line_width + ($square_size * 0.5) + \
682 683 684
                    (($square_size + $line_width) * $c)}] \
         [expr {$line_width + ($square_size * 0.5) + \
                    (($square_size + $line_width) * $r)}]
685 686 687 688 689 690 691
}

proc battleship::nw {c r} {
    variable square_size
    variable line_width

    list [expr {$line_width + ($square_size + $line_width) * $c}] \
692
         [expr {$line_width + ($square_size + $line_width) * $r}]
693 694 695 696 697 698 699 700
}

proc battleship::onw {c r} {
    variable board_size
    variable square_size
    variable line_width

    list [expr {($square_size + $line_width) * ($board_size + 1) + \
701 702
                $line_width + ($square_size + $line_width) * $c}] \
         [expr {$line_width + ($square_size + $line_width) * $r}]
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
}

proc battleship::close {gid} {
    variable $gid
    upvar 0 $gid state

    array unset state
    catch {unset state}
}

proc battleship::exists {gid} {
    variable $gid
    info exists $gid
}

718 719 720 721 722 723 724 725
proc battleship::button_update_relief {b flag} {
    set rstate [expr {$flag? {pressed} : {!$pressed}}]
    if {[catch {$b state $rstate}]} {
        set relief [expr {$flag? "sunken" : "raised"}]
        $b configure -relief $relief
    }
}

726 727 728 729 730 731 732 733 734 735 736 737
proc battleship::open_win {gid} {
    variable options
    variable board_size
    variable square_size
    variable line_width
    variable $gid
    upvar 0 $gid state

    set jid $state(opponent)

    set w $state(window)
    if {[winfo exists $w]} {
738
        return
739 740 741
    }

    set title [::msgcat::mc "Battleship with %s" \
742
                            [chat::get_nick $state(xlib) $jid chat]]
743
    add_win $w -title $title \
744 745 746
               -tabtitle $title \
               -class Battleship \
               -raise 1
747 748 749

    catch {grid anchor $w center}

750 751
    set mylabel [Label $w.mylabel -text [::msgcat::mc "My ships"]]
    set theirlabel [Label $w.theirlabel -text [::msgcat::mc "Opponent ships"]]
752 753
    grid $mylabel -row 0 -column 0 -sticky w
    grid $theirlabel -row 0 -column 1 -sticky e
754 755 756 757 758 759

    if {[catch {lindex [$w configure -background] 4} bg]} {
        # Ttk
        set bg [ttk::style lookup TFrame -background]
    }

760
    set board [canvas $w.board \
761 762 763 764 765 766 767
                   -borderwidth 0 \
                   -highlightthickness 0 \
                   -background $bg \
                   -width [expr {($square_size + $line_width) *
                                 (2 * $board_size + 1) + $line_width}] \
                   -height [expr {($square_size + $line_width) *
                                  $board_size + $line_width}]]
768 769 770 771 772
    grid $board -row 1 -column 0 -columnspan 2 -sticky nw -padx 10 -pady 10

    set state(board) $board
    set state(show_last_move) $options(show_last_move)

773
    Frame $w.move
774
    grid $w.move -row 2 -column 0 -columnspan 2 -sticky wn
775
    Label $w.move.title -text [::msgcat::mc "Move: "]
776
    pack $w.move.title -side left
777 778
    Label $w.move.label -anchor w \
                        -textvariable [namespace current]::${gid}(move_label)
779 780 781 782
    pack $w.move.label -side left -anchor w

    set bbox [ButtonBox $w.bbox -orient vertical -spacing 0]
    $bbox add -text [::msgcat::mc "Freeze ships position"] \
783
              -command [namespace code [list send_board $gid]]
784
    set state(show_last_move_button) \
785 786 787 788 789 790 791
        [$bbox add -text [::msgcat::mc "Show last move"] \
                   -command [namespace code [list toggle_show_last_move $gid]]]
    button_update_relief $state(show_last_move_button) $state(show_last_move)
    set state(propose_draw_button) \
        [$bbox add -text [::msgcat::mc "Propose a draw"] \
                   -state disabled \
                   -command [namespace code [list toggle_draw $gid]]]
792
    $bbox add -text [::msgcat::mc "Accept the draw proposal"] \
793 794
              -state disabled \
              -command [namespace code [list accept_draw $gid]]
795
    $bbox add -text [::msgcat::mc "Resign the game"] \
796 797
              -state disabled \
              -command [namespace code [list send_resign $gid]]
798 799 800 801 802 803 804 805 806 807 808
    grid columnconfigure $bbox 0 -weight 1
    grid $bbox -row 3 -column 1 -sticky wen

    set state(bbox) $bbox

    set_tooltips

    #label $w.history -text [::msgcat::mc "History"]
    #pack $w.history -side top -anchor w
    set hsw [ScrolledWindow $w.hsw]
    grid $hsw -row 3 -column 0 -sticky nwes
809
    set ht [Text $w.text -wrap word -height 5 -width 25 -state disabled]
810 811 812 813
    set font [$ht cget -font]
    set tabstop1 [font measure $font "100.."]
    set tabstop2 [font measure $font "100..[::msgcat::mc Opponent]   "]
    $ht configure -tabs "$tabstop1 $tabstop2"
814 815
    $ht tag configure attention \
        -foreground [option get $ht errorForeground Text]
816 817 818 819 820 821 822 823 824 825 826
    $hsw setwidget $ht
    set state(hw) $ht

    grid columnconfigure $w 0 -weight 0
    grid columnconfigure $w 1 -weight 0
    grid rowconfigure $w 0 -weight 0
    grid rowconfigure $w 1 -weight 0
    grid rowconfigure $w 2 -weight 0
    grid rowconfigure $w 3 -weight 0

    for {set c 0} {$c < $board_size} {incr c} {
827 828 829 830 831 832 833 834 835 836 837 838
        for {set r 0} {$r < $board_size} {incr r} {
            set x1 [expr {$line_width + (($square_size + $line_width) * $c)}]
            set x2 [expr {($square_size + $line_width) * ($c + 1)}]
            set y1 [expr {$line_width + (($square_size + $line_width) * $r)}]
            set y2 [expr {($square_size + $line_width) * ($r + 1)}]

            $board create image $x1 $y1 -image battleship/field -anchor nw \
                -tags [list mbackground [list cr $c $r]]
            $board create rectangle $x1 $y1 $x2 $y2 \
                -outline {} \
                -tags [list olast [list cr $c $r]]
        }
839 840 841
    }

    for {set c 0} {$c < $board_size} {incr c} {
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
        for {set r 0} {$r < $board_size} {incr r} {
            set x1 [expr {($square_size + $line_width) * ($board_size + 1) + \
                          $line_width + (($square_size + $line_width) * $c)}]
            set x2 [expr {($square_size + $line_width) * ($board_size + 1) + \
                          ($square_size + $line_width) * ($c + 1)}]
            set y1 [expr {$line_width + (($square_size + $line_width) * $r)}]
            set y2 [expr {($square_size + $line_width) * ($r + 1)}]

            $board create image $x1 $y1 -image battleship/field/shaded \
                -anchor nw \
                -tags [list obackground [list cr $c $r]]
            $board create rectangle $x1 $y1 $x2 $y2 \
                -outline {} \
                -tags [list mlast [list cr $c $r]]
            $board create rectangle $x1 $y1 $x2 $y2 \
                -outline {} \
                -tags [list square [list cr $c $r]]
        }
860 861 862
    }

    $board bind figure <1> \
863
                [namespace code [list start_drag_figure $gid %x %y]]
864
    $board bind figure <B1-Motion> \
865
                [namespace code [list drag_figure $gid %x %y]]
866
    $board bind figure <ButtonRelease-1> \
867
                [namespace code [list drag_end $gid %x %y]]
868
    $board bind figure <<ContextMenu>> \
869
                [namespace code [list flip_figure $gid %x %y]]
870 871 872 873

    bind $w <Destroy> [namespace code [list close $gid]]

    for {set c 0} {$c < $board_size} {incr c} {
874 875 876 877
        for {set r 0} {$r < $board_size} {incr r} {
            set state(position,mshot,$c,$r) ""
            set state(position,oshot,$c,$r) ""
        }
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
    }

    set state(board_is_sent) 0
    set state(board_is_received) 0

    set state(position,turn) first

    catch {unset state(position,last_move)}
    set state(position,draw) 0
    set state(position,halfmove) 0
    set state(position,history) {}
    set state(position,ships) {}
    set state(position,destroyed_ships) {}
    set state(position,destroyed_my_ships) {}

    for {set c 0} {$c < $board_size} {incr c} {
894 895 896 897
        for {set r 0} {$r < $board_size} {incr r} {
          set state(seed,$c,$r) \
           [rand 1000000000][rand 1000000000][rand 1000000000][rand 1000000000]
        }
898 899 900
    }

    make_random_position $gid
901

902 903 904
    predraw_position $gid
    update_controls $gid
    attention_message $gid \
905 906 907 908
            [::msgcat::mc "\nDrag and drop ships to desired locations, then\
                           click the 'Freeze ships position'\
                           button.\nRight mouse button switches horizontal\
                           and vertical ship orientation."]
909 910 911 912 913 914 915 916 917 918 919
}

proc battleship::predraw_position {gid} {
    variable board_size
    variable sizes
    variable $gid
    upvar 0 $gid state

    $state(board) delete figure

    foreach ship $state(position,ships) {
920
        lassign $ship name dir c r
921

922 923 924 925
        $state(board) create image [nw $c $r] \
                      -anchor nw \
                      -image battleship/$name/$dir \
                      -tags [list figure [list ship $name $dir $c $r]]
926 927 928 929 930 931 932 933 934 935 936 937
    }
}

proc battleship::flip_figure {gid x y} {
    variable board_size
    variable sizes
    variable $gid
    upvar 0 $gid state

    array set size $sizes
    set board $state(board)

938 939
    lassign [lsearch -inline -regexp [$board gettags current] ^ship] ship \
            name dir c r
940 941 942 943

    set x [$board canvasx $x]
    set y [$board canvasy $y]
    $board dtag dst
944
    $board addtag dst overlapping [expr {$x-1}] [expr {$y-1}] $x $y
945 946
    lassign [lsearch -inline -regexp [$board gettags dst&&mbackground] ^cr] \
            cr c1 r1
947 948 949 950 951
    $board dtag dst

    set c2 [expr {$c1 - $r1 + $r}]
    if {$c2 < 0} { set c2 0 }
    if {$dir == "vertical" && $c2 > $board_size - $size($name)} {
952
        set c2 [expr {$board_size - $size($name)}]
953 954 955 956 957
    }

    set r2 [expr {$r1 - $c1 + $c}]
    if {$r2 < 0} { set r2 0 }
    if {$dir == "horizontal" && $r2 > $board_size - $size($name)} {
958
        set r2 [expr {$board_size - $size($name)}]
959 960
    }

961 962 963 964 965
    if {$dir == "horizontal"} {
        set dir2 vertical
    } else {
        set dir2 horizontal
    }
966 967 968 969 970 971 972

    set idx [lsearch -exact $state(position,ships) [list $name $dir $c $r]]
    set state(position,ships) [lreplace $state(position,ships) $idx $idx]
    lappend state(position,ships) [list $name $dir2 $c2 $r2]
    predraw_position $gid

    if {[position_is_legal $gid 0]} {
973
        $state(bbox) itemconfigure 0 -state normal
974
    } else {
975
        $state(bbox) itemconfigure 0 -state disabled
976 977 978 979 980 981 982 983 984 985 986 987
    }
}

proc battleship::start_drag_figure {gid x y} {
    variable $gid
    upvar 0 $gid state

    set board $state(board)

    set state(lastx) [$board canvasx $x]
    set state(lasty) [$board canvasy $y]
    $board dtag dst
988
    $board addtag dst overlapping [expr {$x-1}] [expr {$y-1}] $x $y
989 990
    lassign [lsearch -inline -regexp [$board gettags dst&&mbackground] ^cr] \
            cr state(startc) state(startr)
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    $board dtag dst

    $board raise current
    $board addtag drag withtag current
    $board config -cursor hand2
}

proc battleship::drag_figure {gid x y} {
    variable board_size
    variable square_size
    variable line_width
    variable $gid
    upvar 0 $gid state

    set board $state(board)

    set minx $line_width
    set maxx [expr {($square_size + $line_width) * $board_size}]
    set miny $line_width
    set maxy [expr {($square_size + $line_width) * $board_size}]

    set x [$board canvasx $x]
    set y [$board canvasy $y]
    set dx [expr {$x - $state(lastx)}]
    set dy [expr {$y - $state(lasty)}]

    lassign [$board bbox drag] x1 y1 x2 y2

    if {$x1 + $dx < $minx} {
1020
        set dx [expr {$minx - $x1}]
1021 1022 1023
    }

    if {$x2 + $dx > $maxx} {
1024
        set dx [expr {$maxx - $x2}]
1025 1026 1027
    }

    if {$y1 + $dy < $miny} {
1028
        set dy [expr {$miny - $y1}]
1029 1030 1031
    }

    if {$y2 + $dy > $maxy} {
1032
        set dy [expr {$maxy - $y2}]
1033 1034 1035 1036 1037
    }

    $board move drag $dx $dy

    if {$x < $minx} {
1038
        set state(lastx) $minx
1039
    } elseif {$x > $maxx} {
1040
        set state(lastx) $maxx
1041
    } else {
1042
        set state(lastx) $x
1043 1044
    }
    if {$y < $miny} {
1045
        set state(lasty) $miny
1046
    } elseif {$y > $maxy} {
1047
        set state(lasty) $maxy
1048
    } else {
1049
        set state(lasty) $y
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
    }
}

proc battleship::drag_end {gid x y} {
    variable square_size
    variable $gid
    upvar 0 $gid state

    set board $state(board)

1060 1061
    lassign [lsearch -inline -regexp [$board gettags drag] ^ship] ship \
            name dir c r
1062 1063 1064 1065 1066 1067
    lassign [$board bbox drag] x1 y1
    $board dtag drag

    set x [expr {$x1 + $square_size/2}]
    set y [expr {$y1 + $square_size/2}]
    $board dtag dst
1068
    $board addtag dst overlapping [expr {$x-1}] [expr {$y-1}] $x $y
1069 1070
    lassign [lsearch -inline -regexp [$board gettags dst&&mbackground] ^cr] \
            cr c1 r1
1071 1072 1073 1074 1075 1076 1077 1078
    $board dtag dst

    set idx [lsearch -exact $state(position,ships) [list $name $dir $c $r]]
    set state(position,ships) [lreplace $state(position,ships) $idx $idx]
    lappend state(position,ships) [list $name $dir $c1 $r1]

    predraw_position $gid
    if {[position_is_legal $gid 0]} {
1079
        $state(bbox) itemconfigure 0 -state normal
1080
    } else {
1081
        $state(bbox) itemconfigure 0 -state disabled
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
    }
}

proc battleship::make_random_position {gid} {
    variable board_size
    variable ships
    variable sizes
    variable $gid
    upvar 0 $gid state

    array set tmp $sizes
    set state(position,ships) {}

    foreach {name num} $ships {
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
        for {set i 0} {$i < $num} {incr i} {
            while {1} {
                set c [rand $board_size]
                set r [rand $board_size]
                set dir [lindex {horizontal vertical} [rand 2]]
                set ship [list $name $dir $c $r]

                set saved $state(position,ships)
                lappend state(position,ships) $ship
                if {[position_is_legal $gid 0]} {
                    break
                } else {
                    set state(position,ships) $saved
                }
            }
        }
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
    }
}

proc battleship::position_is_legal {gid checkSizesOfShips} {
    variable board_size
    variable ships
    variable sizes
    variable $gid
    upvar 0 $gid state

    if {$checkSizesOfShips} {
1123 1124 1125 1126 1127 1128 1129 1130 1131
        array set tmp $ships

        foreach ship $state(position,ships) {
            set name [lindex $ship 0]
            if {![info exists tmp($name)]} {
                return 0
            }
            incr tmp($name) -1
        }
1132

1133 1134 1135 1136 1137
        foreach name [array names tmp] {
            if {$tmp($name) != 0} {
                return 0
            }
        }
1138 1139 1140 1141
    }

    set max -1
    foreach ship $state(position,ships) {
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
        foreach {c r} [coordinates $ship] {
            if {$c < 0 || $c >= $board_size || $r < 0 || $r >= $board_size} {
                return 0
            }

            foreach ship2 [lrange $state(position,ships) 0 $max] {
                foreach {c1 r1} [coordinates $ship2] {
                    if {abs($c1 - $c) <= 1 && abs($r1 - $r) <= 1} {
                        return 0
                    }
                }
            }
        }
        incr max
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
    }

    return 1
}

proc battleship::coordinates {ship} {
    variable sizes

    array set tmp $sizes
    lassign $ship name dir c r

    set coords {}
    for {set i 0} {$i < $tmp($name)} {incr i} {
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
        lappend coords $c $r
        switch -- $dir {
            horizontal {
                incr c
            }
            vertical {
                incr r
            }
            default {
                return -code error
            }
        }
1181 1182 1183 1184 1185 1186 1187 1188
    }
    return $coords
}

proc battleship::set_tooltips {args} {
    variable options

    if {$options(show_tooltips)} {
1189 1190 1191 1192 1193 1194 1195
        set tooltip0 ""
        set tooltip1 ""
        set tooltip2 [::msgcat::mc "Press button and make move if you want\
                                    to propose draw"]
        set tooltip3 [::msgcat::mc "Press button if you want to accept the\
                                    draw proposal"]
        set tooltip4 [::msgcat::mc "Press button if you want to resign"]
1196
    } else {
1197 1198 1199 1200 1201
        set tooltip0 ""
        set tooltip1 ""
        set tooltip2 ""
        set tooltip3 ""
        set tooltip4 ""
1202 1203 1204
    }

    foreach var [info vars [namespace current]::*] {
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
        upvar 0 $var state
        if {[info exists state(bbox)]} {
            catch {
                $state(bbox) itemconfigure 0 -helptext $tooltip0
                $state(bbox) itemconfigure 1 -helptext $tooltip1
                $state(bbox) itemconfigure 2 -helptext $tooltip2
                $state(bbox) itemconfigure 3 -helptext $tooltip3
                $state(bbox) itemconfigure 4 -helptext $tooltip4
            }
        }
1215 1216 1217 1218 1219 1220 1221 1222 1223
    }
}

proc battleship::toggle_show_last_move {gid} {
    variable $gid
    upvar 0 $gid state

    set state(show_last_move) [expr {!$state(show_last_move)}]

1224
    button_update_relief $state(show_last_move_button) $state(show_last_move)
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234

    highlight_last_move $gid
}

proc battleship::toggle_draw {gid} {
    variable $gid
    upvar 0 $gid state

    set state(position,draw) [expr {!$state(position,draw)}]

1235
    button_update_relief $state(propose_draw_button) $state(position,draw)
1236 1237 1238 1239 1240 1241 1242
}

proc battleship::update_controls {gid {draw_proposed 0}} {
    variable $gid
    upvar 0 $gid state

    if {!$state(board_is_sent)} {
1243 1244
        $state(bbox) itemconfigure 0 -state normal
        return
1245
    } else {
1246
        $state(bbox) itemconfigure 0 -state disabled
1247 1248 1249
    }

    if {!$state(board_is_received)} {
1250
        return
1251 1252
    }

1253
    button_update_relief $state(propose_draw_button) 0
1254 1255

    if {[is_my_move $gid]} {
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
        $state(board) config -cursor ""
        set state(position,draw) 0
        if {$draw_proposed} {
            $state(bbox) itemconfigure 2 -state disabled
            $state(bbox) itemconfigure 3 -state normal
            $state(bbox) itemconfigure 4 -state disabled
        } else {
            $state(bbox) itemconfigure 2 -state normal
            $state(bbox) itemconfigure 3 -state disabled
            $state(bbox) itemconfigure 4 -state normal
        }
1267
    } else {
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
        if {$state(position,turn) ne "first" && \
                $state(position,turn) ne "second"} {
            $state(board) config -cursor ""
        } else {
            set state(position,draw) $draw_proposed
            $state(board) config -cursor watch
        }
        $state(bbox) itemconfigure 2 -state disabled
        $state(bbox) itemconfigure 3 -state disabled
        $state(bbox) itemconfigure 4 -state disabled
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
    }
}

proc battleship::end_game {gid my_score message} {
    variable $gid
    upvar 0 $gid state

    set opponent_score [expr {1 - $my_score}]

    if {$state(move_first)} {
1288
        set score "$my_score : $opponent_score"
1289
    } else {
1290
        set score "$opponent_score : $my_score"
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
    }

    set state(position,turn) none
    set state(move_label) $message

    set hw $state(hw)
    $hw configure -state normal
    catch {$hw delete attention.first attention.last}
    $hw delete {end -1 char} end
    $hw insert end "\n\t\t$score\n"
    $hw see end
    $hw configure -state disabled

    after idle [namespace code [list send_board2 $gid]]
}

proc battleship::draw_position {gid} {
    variable board_size
    variable sizes
    variable $gid
    upvar 0 $gid state

    $state(board) delete figure
    $state(board) delete unshaded
    $state(board) delete oshot
    $state(board) delete mshot

    foreach ship $state(position,ships) {
1319
        lassign $ship name dir c r
1320

1321 1322 1323 1324
        $state(board) create image [nw $c $r] \
                      -anchor nw \
                      -image battleship/$name/$dir \
                      -tags [list figure [list ship $name $dir $c $r]]
1325 1326 1327
    }

    for {set c 0} {$c < $board_size} {incr c} {
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
        for {set r 0} {$r < $board_size} {incr r} {
            switch -- $state(position,oshot,$c,$r) {
                1 { set image battleship/hit }
                0 { set image battleship/miss }
                default { continue }
            }
            $state(board) create image [nw $c $r] \
                          -anchor nw \
                          -image $image \
                          -tags [list oshot [list cr $c $r]]
        }
1339 1340 1341 1342 1343
    }

    array set tmp $sizes

    foreach ship $state(position,destroyed_ships) {
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
        lassign $ship name dir c r

        switch -- $dir {
            vertical {
                for {set c1 [expr {$c - 1}]} {$c1 <= $c + 1} {incr c1} {
                    if {$c1 < 0 || $c1 >= $board_size} continue
                    for {set r1 [expr {$r - 1}]} {$r1 <= $r + $tmp($name)} \
                        {incr r1} {
                        if {$r1 < 0 || $r1 >= $board_size} continue

                        $state(board) create image [onw $c1 $r1] \
                                      -anchor nw \
                                      -image battleship/field \
                                      -tags [list unshaded $c1 $r1]
                        set unshaded($c1,$r1) 1
                    }
                }
            }
            horizontal {
                for {set c1 [expr {$c - 1}]} {$c1 <= $c + $tmp($name)} \
                    {incr c1} {
                    if {$c1 < 0 || $c1 >= $board_size} continue
                    for {set r1 [expr {$r - 1}]} {$r1 <= $r + 1} {incr r1} {
                        if {$r1 < 0 || $r1 >= $board_size} continue

                        $state(board) create image [onw $c1 $r1] \
                                      -anchor nw \
                                      -image battleship/field \
                                      -tags [list unshaded $c1 $r1]
                        set unshaded($c1,$r1) 1
                    }
                }
            }
        }

        $state(board) create image [onw $c $r] \
                      -anchor nw \
                      -image battleship/$name/$dir \
                      -tags [list figure [list ship $name $dir $c $r]]
1383 1384 1385
    }

    for {set c 0} {$c < $board_size} {incr c} {
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
        for {set r 0} {$r < $board_size} {incr r} {
            switch -- $state(position,mshot,$c,$r) {
                1 { set image battleship/hit }
                0 { set image battleship/miss }
                default { continue }
            }
            if {![info exists unshaded($c,$r)]} {
                $state(board) create image [onw $c $r] \
                              -anchor nw \
                              -image battleship/field \
                              -tags [list unshaded $c $r]
            }
            $state(board) create image [onw $c $r] \
                          -anchor nw \
                          -image $image \
                          -tags [list mshot [list cr $c $r]]
        }
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
    }

    $state(board) raise mlast
    $state(board) raise olast
    $state(board) raise square
}

proc battleship::motion {gid x y} {
    variable $gid
    upvar 0 $gid state

    set board $state(board)

    set x [$board canvasx $x]
    set y [$board canvasy $y]

    $board itemconfigure dst_sq&&square -outline ""
    $board dtag dst_sq
1421

1422
    $board addtag dst_sq overlapping [expr {$x-1}] [expr {$y-1}] $x $y
1423 1424 1425
    set tags [$board gettags dst_sq&&obackground]
    lassign [lindex $tags [lsearch $tags cr*]] cr c r
    $board addtag dst_sq withtag [list cr $c $r]&&square
1426

1427
    if {[is_my_move $gid] && [info exists state(position,mshot,$c,$r)] && \
1428 1429 1430
            $state(position,mshot,$c,$r) == ""} {
        $board itemconfigure dst_sq&&square -outline red
        $board itemconfigure dst_sq&&reasonable&&square -outline blue
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
    }
}

proc battleship::leave {gid x y} {
    variable $gid
    upvar 0 $gid state

    set board $state(board)

    $board itemconfigure dst_sq&&square -outline ""
    $board dtag dst_sq
    highlight_last_move $gid
}

proc battleship::release {gid x y} {
    variable options
    variable $gid
    upvar 0 $gid state

    set board $state(board)

    set x [$board canvasx $x]
    set y [$board canvasy $y]
    $board dtag dst_sq
1455
    $board addtag dst_sq overlapping [expr {$x-1}] [expr {$y-1}] $x $y
1456 1457 1458 1459 1460 1461

    set tags [$board gettags dst_sq&&obackground]
    lassign [lindex $tags [lsearch $tags cr*]] cr c r
    $board dtag dst_sq

    if {[is_my_move $gid]} {
1462 1463 1464
        if {[start_do_move $gid $c $r $state(position,draw)]} {
            $board itemconfigure [list cr $c $r]&&square -outline ""
        }
1465
    }
1466

1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
    update_controls $gid
    draw_position $gid

    highlight_last_move $gid
}

proc battleship::highlight_last_move {gid} {
    variable $gid
    upvar 0 $gid state

    $state(board) itemconfigure mlast -outline ""
    $state(board) itemconfigure olast -outline ""
1479

1480
    if {[catch {lassign $state(position,last_move) c r}]} {
1481
        return
1482 1483 1484
    }

    if {$state(show_last_move)} {
1485
        set color white
1486
    } else {
1487
        set color {}
1488 1489 1490
    }

    if {$state(position,my_last_move)} {
1491
        $state(board) itemconfigure [list cr $c $r]&&mlast -outline $color
1492
    } else {
1493
        $state(board) itemconfigure [list cr $c $r]&&olast -outline $color
1494 1495 1496 1497 1498 1499
    }
}

proc battleship::start_do_move {gid c r draw} {
    variable $gid
    upvar 0 $gid state
1500

1501
    if {$c == "" || $r == ""} {
1502
        return 0
1503 1504 1505 1506 1507
    }

    set my_move [is_my_move $gid]

    if {!$my_move} {
1508
        return 0
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
    }

    save_position $gid

    set state(position,mshot,$c,$r) -1
    set state(position,last_move) [list $c $r]
    set state(position,my_last_move) 1

    update_controls $gid
    draw_position $gid
    highlight_last_move $gid
    send_move $gid $c $r $draw
    return 1
}

proc battleship::do_move {gid c r result draw} {
    variable options
    variable ships
    variable $gid
    upvar 0 $gid state
1529

1530
    if {$c == "" || $r == ""} {
1531
        return 0
1532 1533 1534
    }

    switch -- $result {
1535 1536 1537
        destroy -
        hit { set hit 1 }
        default { set hit 0 }
1538 1539 1540 1541 1542
    }

    set my_move [is_my_move $gid]

    if {!$my_move} {
1543 1544 1545 1546
        save_position $gid
        set state(position,oshot,$c,$r) $hit
        set state(position,last_move) [list $c $r]
        set state(position,my_last_move) 0
1547
    } else {
1548 1549 1550 1551 1552 1553 1554
        set state(position,mshot,$c,$r) $hit
        if {$result == "destroy"} {
            set ship [find_destroyed_ship $gid $c $r]
            if {[llength $ship] > 0} {
                lappend state(position,destroyed_ships) $ship
            }
        }
1555 1556 1557 1558 1559
    }

    add_move_to_history $gid $c $r $result $draw

    if {$draw && !$my_move} {
1560 1561
        attention_message $gid \
            [::msgcat::mc "\n\n Opponent proposes a draw\n\n"]
1562 1563 1564
    }

    switch -glob -- $state(position,turn)/$hit/$draw {
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
        first/1/0 {
            # Add skipping move to history
            add_move_to_history $gid
            set state(position,turn) first
        }
        second/1/0 {
            # Add skipping move to history
            add_move_to_history $gid
            set state(position,turn) second
        }
        first/1/1 -
        first/0/* {
            set state(position,turn) second
        }
        second/1/1 -
        second/0/* {
            set state(position,turn) first
        }
1583 1584 1585 1586 1587 1588
    }

    find_reasonable_moves $gid $state(position,turn)

    set endgame 0
    if {[llength $state(reasonable_moves)] == 0} {
1589
        set endgame 1
1590
    }
1591

1592
    if {$endgame} {
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
        set total 0
        foreach {name size} $ships {
            incr total $size
        }
        if {[llength $state(position,destroyed_ships)] >= $total &&
                [llength $state(position,destroyed_my_ships)] < $total} {
            # I win
            end_game $gid 1 [::msgcat::mc "You win"]
        } elseif {[llength $state(position,destroyed_my_ships)] >= $total &&
                [llength $state(position,destroyed_ships)] < $total} {
            # Opponent wins
            end_game $gid 0 [::msgcat::mc "Opponent wins"]
        } else {
            # Can't be here
            end_game $gid 0.5 [::msgcat::mc "Impossible draw"]
        }
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
    }

    tab_set_updated [winfo parent $state(board)] 1 mesg_to_user
    return 1
}

proc battleship::accept_draw {gid} {
    variable $gid
    upvar 0 $gid state

    ::xmpp::sendIQ $state(xlib) set \
1620 1621 1622 1623 1624 1625 1626
        -query [::xmpp::xml::create turn \
                    -xmlns games:board \
                    -attrs [list type battleship \
                                 id $state(id)] \
                    -subelement [::xmpp::xml::create accept]] \
        -to $state(opponent) \
        -command [namespace code [list accept_draw_result $gid]]
1627

1628 1629 1630 1631
        end_game $gid 0.5 [::msgcat::mc "Draw (You accepted)"]
        update_controls $gid
        draw_position $gid
        highlight_last_move $gid
1632 1633 1634 1635 1636 1637 1638
}

proc battleship::accept_draw_result {gid status xml} {
    variable $gid
    upvar 0 $gid state

    if {![string equal $status ok]} {
1639 1640 1641 1642
        attention_message $gid \
                [::msgcat::mc "\n\n Opponent rejected accepted\
                               draw:\n %s\n\n" \
                              [error_to_string $xml]]
1643 1644 1645 1646 1647 1648 1649 1650
    }
}

proc battleship::send_resign {gid} {
    variable $gid
    upvar 0 $gid state

    ::xmpp::sendIQ $state(xlib) set \
1651 1652 1653 1654 1655 1656
        -query [::xmpp::xml::create turn \
                    -xmlns games:board \
                    -attrs [list type battleship \
                                 id $state(id)] \
                    -subelement [::xmpp::xml::create resign]] \
        -to $state(opponent)
1657

1658 1659 1660 1661
        end_game $gid 0 [::msgcat::mc "Opponent wins (You resigned)"]
        update_controls $gid
        draw_position $gid
        highlight_last_move $gid
1662 1663 1664 1665 1666 1667 1668 1669
}

proc battleship::send_board {gid} {
    variable board_size
    variable $gid
    upvar 0 $gid state

    for {set c 0} {$c < $board_size} {incr c} {
1670 1671 1672
        for {set r 0} {$r < $board_size} {incr r} {
            set pos($c,$r) 0
        }
1673 1674 1675 1676
    }

    set shipSubels {}
    foreach ship $state(position,ships) {
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
        set size 0
        set seed ""
        foreach {c r} [coordinates $ship] {
            incr size
            append seed $state(seed,$c,$r)
            set pos($c,$r) 1
        }
        lappend shipSubels [::xmpp::xml::create ship \
                                    -attrs [list length $size \
                                                 hash [sha1::sha1 $seed]]]
1687 1688 1689 1690
    }

    set subels {}
    for {set c 0} {$c < $board_size} {incr c} {
1691 1692 1693 1694 1695 1696 1697 1698
        for {set r 0} {$r < $board_size} {incr r} {
            lappend subels \
                [::xmpp::xml::create cell \
                        -attrs [list col $c \
                                     row $r \
                                     hash [sha1::sha1 \
                                               $state(seed,$c,$r)$pos($c,$r)]]]
        }
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
    }

    set state(board_is_sent) 1
    set_label_move $gid
    draw_position $gid
    update_controls $gid
    find_reasonable_moves $gid $state(position,turn)

    set hw $state(hw)
    $hw configure -state normal
    $hw delete 0.0 end
    $hw configure -state disabled

    $state(board) bind figure <1> {}
    $state(board) bind figure <B1-Motion> {}
    $state(board) bind figure <ButtonRelease-1> {}

1716 1717 1718 1719 1720
    bind $state(board) <Any-Enter>  [namespace code [list motion $gid %x %y]]
    bind $state(board) <Any-Motion> [namespace code [list motion $gid %x %y]]
    bind $state(board) <Any-Leave>  [namespace code [list leave $gid %x %y]]
    bind $state(board) <ButtonRelease-1> \
         [namespace code [list release $gid %x %y]]
1721 1722

    ::xmpp::sendIQ $state(xlib) set \
1723 1724 1725 1726 1727 1728 1729 1730
            -query [::xmpp::xml::create board \
                            -xmlns games:board \
                            -attrs [list type battleship \
                                         id $state(id)] \
                            -subelements $subels \
                            -subelements $shipSubels] \
            -to $state(opponent) \
            -command [namespace code [list send_result board $gid]]
1731 1732 1733 1734 1735 1736 1737 1738
}

proc battleship::send_board2 {gid} {
    variable board_size
    variable $gid
    upvar 0 $gid state

    for {set c 0} {$c < $board_size} {incr c} {
1739 1740 1741
        for {set r 0} {$r < $board_size} {incr r} {
            set pos($c,$r) 0
        }
1742 1743 1744
    }

    foreach ship $state(position,ships) {
1745 1746 1747
        foreach {c r} [coordinates $ship] {
            set pos($c,$r) 1
        }
1748 1749 1750 1751
    }

    set subels {}
    for {set c 0} {$c < $board_size} {incr c} {
1752 1753 1754 1755 1756 1757 1758
        for {set r 0} {$r < $board_size} {incr r} {
            lappend subels [::xmpp::xml::create cell \
                                    -attrs [list col $c \
                                                 row $r \
                                                 ship $pos($c,$r) \
                                                 seed $state(seed,$c,$r)]]
        }
1759 1760 1761
    }

    ::xmpp::sendIQ $state(xlib) set \
1762 1763 1764 1765 1766 1767 1768
            -query [::xmpp::xml::create board \
                            -xmlns games:board \
                            -attrs [list type battleship \
                                         id $state(id)] \
                            -subelements $subels] \
            -to $state(opponent) \
            -command [namespace code [list send_result board2 $gid]]
1769 1770 1771 1772 1773 1774 1775 1776
}

proc battleship::send_move {gid c r draw} {
    variable $gid
    upvar 0 $gid state

    set els [list [::xmpp::xml::create shot -attrs [list row $r col $c]]]
    if {$draw} {
1777
        lappend els [::xmpp::xml::create draw]
1778 1779 1780
    }

    ::xmpp::sendIQ $state(xlib) set \
1781 1782 1783 1784 1785 1786 1787
            -query [::xmpp::xml::create turn \
                            -xmlns games:board \
                            -attrs [list type battleship \
                                         id $state(id)] \
                            -subelements $els] \
            -to $state(opponent) \
            -command [namespace code [list send_turn_result $gid $c $r $draw]]
1788 1789 1790 1791 1792 1793 1794
}

proc battleship::send_turn_result {gid c r draw status xml} {
    variable $gid
    upvar 0 $gid state

    if {![string equal $status ok]} {
1795 1796 1797 1798
        attention_message $gid \
                [::msgcat::mc "\n\n Opponent rejected move:\n %s\n\n" \
                              [error_to_string $xml]]
        restore_position $gid
1799
    } else {
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
        ::xmpp::xml::split $xml tag xmlns attrs cdata subels

        foreach subel $subels {
            ::xmpp::xml::split $subel stag sxmlns sattrs scdata ssubels

            switch -- $stag {
                shot {
                    set result [::xmpp::xml::getAttr $sattrs result]
                    set seed [::xmpp::xml::getAttr $sattrs seed]
                    set state(oseed,$c,$r) $seed

                    switch -- $result {
                        hit {
                            set hit 1
                            set destroy 0
                        }
                        destroy {
                            set hit 1
                            set destroy 1
                        }
                        default {
                            set hit 0
                            set destroy 0
                        }
                    }

                    if {[sha1::sha1 $seed$hit] ne $state(hash,$c,$r)} {
                        attention_message $gid \
                                [::msgcat::mc "\n\n Opponent returned\
                                               incorrect cell seed"]
                        return
                    }

                    if {$hit} {
                        # Checking if the currenlty hit ship is destroyed

                        set ship [find_destroyed_ship $gid $c $r]
                        set acc ""
                        foreach {c1 r1} [coordinates $ship] {
                            append acc $state(oseed,$c1,$r1)
                        }
                        set hash [sha1::sha1 $acc]
                        if {$destroy && \
                               [lsearch -exact $state(shiphashes) $hash] < 0} {
                            attention_message $gid \
                                [::msgcat::mc "\n\n Opponent returned\
                                               incorrect destroy answer"]
                            return
                        } elseif {!$destroy && $hit && \
                              [lsearch -exact $state(shiphashes) $hash] >= 0} {
                            attention_message $gid \
                                [::msgcat::mc "\n\n Opponent returned\
                                               inconrrect hit answer"]
                            return
                        }
                    }

                    do_move $gid $c $r $result $draw
                    update_controls $gid $draw
                    draw_position $gid
                    highlight_last_move $gid
                    return
                }
            }
        }

        attention_message $gid \
                [::msgcat::mc "\n\n Opponent returned incorrect answer"]
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
    }
}

proc battleship::find_destroyed_ship {gid c r} {
    variable sizes
    variable board_size
    variable $gid
    upvar 0 $gid state

    set r1 $r
    while {$r1 >= 0 && ($state(position,mshot,$c,$r1) == 1 ||
1879 1880
                        $state(position,mshot,$c,$r1) == -1)} {
        incr r1 -1
1881 1882 1883 1884
    }
    incr r1
    set r2 $r
    while {$r2 < $board_size && ($state(position,mshot,$c,$r2) == 1 ||
1885 1886
                                 $state(position,mshot,$c,$r2) == -1)} {
        incr r2
1887 1888 1889
    }
    incr r2 -1
    if {$r2 > $r1} {
1890 1891 1892 1893 1894 1895 1896
        set size [expr {$r2 - $r1 + 1}]
        foreach {name s} $sizes {
            if {$s == $size} {
                return [list $name vertical $c $r1]
            }
        }
        return
1897 1898 1899 1900
    }

    set c1 $c
    while {$c1 >= 0 && ($state(position,mshot,$c1,$r) == 1 ||
1901 1902
                        $state(position,mshot,$c1,$r) == -1)} {
        incr c1 -1
1903 1904 1905 1906
    }
    incr c1
    set c2 $c
    while {$c2 < $board_size && ($state(position,mshot,$c2,$r) == 1 ||
1907 1908
                                 $state(position,mshot,$c2,$r) == -1)} {
        incr c2
1909 1910 1911 1912
    }
    incr c2 -1
    set size [expr {$c2 - $c1 + 1}]
    foreach {name s} $sizes {
1913 1914 1915
        if {$s == $size} {
            return [list $name horizontal $c1 $r]
        }
1916 1917 1918 1919 1920 1921 1922 1923 1924
    }
    return
}

proc battleship::send_result {type gid status xml} {
    variable $gid
    upvar 0 $gid state

    switch -- $type {
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
        board {
            if {![string equal $status ok]} {
                set state(board_is_sent) 0
                set_label_move $gid
                update_controls $gid
                attention_message $gid \
                        [::msgcat::mc "\n\n Opponent rejected\
                                       board:\n %s\n\n" \
                                      [error_to_string $xml]]
            }
        }
        board2 {
            if {![string equal $status ok]} {
                attention_message $gid \
                        [::msgcat::mc "\n\n Opponent rejected\
                                       board:\n %s\n\n" \
                                      [error_to_string $xml]]
            }
        }
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
    }
}

proc battleship::add_move_to_history {gid {c ""} {r ""} {result ""} {draw 0}} {
    variable board_size
    variable $gid
    upvar 0 $gid state

    incr state(position,halfmove)

    if {$c != "" && $r != ""} {
1955
        lappend state(position,history) [list $c $r $result $draw]
1956
    } else {
1957
        lappend state(position,history) skip
1958 1959 1960 1961 1962 1963 1964
    }

    set hw $state(hw)
    $hw configure -state normal
    $hw delete 0.0 end

    if {$state(move_first)} {
1965
        $hw insert end "\t[::msgcat::mc You]\t[::msgcat::mc Opponent]\n"
1966
    } else {
1967
        $hw insert end "\t[::msgcat::mc Opponent]\t[::msgcat::mc You]\n"
1968 1969 1970
    }
    set i 1
    foreach {b w} $state(position,history) {
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
        $hw insert end "${i}.\t"
        if {$b == "skip"} {
            $hw insert end "--\t"
        } elseif {$b != {}} {
            lassign $b c r res d
            set r [expr {$board_size - $r}]
            set l [format %c [expr {$c+97}]]
            switch -- $res {
                destroy { set s # }
                hit     { set s + }
                default { set s "" }
            }
            if {$d} {
                set e "="
            } else {
                set e ""
            }
            $hw insert end "$l$r$s$e\t"
        }
        if {$w == "skip"} {
            $hw insert end "--\n"
        } elseif {$w != {}} {
            lassign $w c r res d
            set r [expr {$board_size - $r}]
            set l [format %c [expr {$c+97}]]
            switch -- $res {
                destroy { set s # }
                hit     { set s + }
                default { set s "" }
            }
            if {$d} {
                set e "="
            } else {
                set e ""
            }
            $hw insert end "$l$r$s$e\n"
        } else {
            $hw insert end "\n"
        }
        incr i
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
    }
    $hw see end
    $hw configure -state disabled
}

proc battleship::find_reasonable_moves {gid color} {
    variable board_size
    variable ships
    variable $gid
    upvar 0 $gid state

    set state(reasonable_moves) {}

    set total 0
    foreach {name number} $ships {
2026
        incr total $number
2027 2028 2029
    }

    if {[llength $state(position,destroyed_my_ships)] < $total &&
2030 2031 2032 2033 2034 2035 2036 2037
                [llength $state(position,destroyed_ships)] < $total} {
        for {set c 0} {$c < $board_size} {incr c} {
            for {set r 0} {$r < $board_size} {incr r} {
                if {$state(position,mshot,$c,$r) == ""} {
                    lappend state(reasonable_moves) [list $c $r]
                }
            }
        }
2038 2039 2040 2041 2042 2043 2044 2045
    }
    highlight_reasonable_moves $gid
}

proc battleship::is_move_reasonable {gid c r} {
    variable $gid
    upvar 0 $gid state

2046
    expr {[lsearch -regexp $state(reasonable_moves) ^[list $c $r]] >= 0}
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
}

proc battleship::highlight_reasonable_moves {gid} {
    variable $gid
    upvar 0 $gid state

    set board $state(board)

    $board dtag reasonable
    foreach move $state(reasonable_moves) {
2057 2058
        lassign $move c r
        $board addtag reasonable withtag [list cr $c $r]&&square
2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
    }
}

proc battleship::attention_message {gid message} {
    variable $gid
    upvar 0 $gid state

    set hw $state(hw)
    $hw configure -state normal
    $hw delete {end -1 char} end
    $hw insert end $message attention
    $hw see end
    $hw configure -state disabled
}

proc battleship::is_my_move {gid} {
    variable $gid
    upvar 0 $gid state
    if {$state(move_first) && $state(position,turn) == "first"} {
2078
        return 1
2079
    } elseif {!$state(move_first) && $state(position,turn) == "second"} {
2080
        return 1
2081
    } else {
2082
        return 0
2083 2084 2085 2086 2087 2088 2089 2090 <