File: CardGame.itcl

package info (click to toggle)
coccinella 0.96.20-9
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster
  • size: 13,184 kB
  • sloc: tcl: 124,744; xml: 206; makefile: 66; sh: 62
file content (629 lines) | stat: -rw-r--r-- 16,798 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
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
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
433
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
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
627
628
629
# CardGame.itcl 
# 
#       Creates a card game in a whiteboard canvas. 
# 
# 
# $Id: CardGame.itcl,v 1.14 2007-09-16 07:39:13 matben Exp $

namespace eval CardGame {
    
    variable infoScript [info script]
}

# This file may be sourced more than once; protect for this!
# Is there a better way? Ugly!

if {[itcl::find classes CardGame] == ""} {
    
    class CardGame {
	
	inherit CardStack BaseWBCanvas
	    
	# -----------------------
	# Private static methods.
	# -----------------------

	private {
	    proc Init {}
	    proc Handler {w type cmd args}
	    proc GetThisFromStackUtag {utag}
	}

	# ------------------
	# Class constructor.
	# ------------------
	
	protected {
	    constructor {w x y args} {$this BaseWBCanvas::constructor $w} {}
	    destructor {}
	}
	
	# --------------
	# Class methods.
	# --------------

	public {
	    method Save {id args}
	    method Delete {id}
	}
	
	# ----------------------
	# Private class methods.
	# ----------------------
	
	protected {
	    method DrawCardStack {x y args}
	    method MakeMenus {}
	    method PointPress {x y} {}
	    method PointMotion {x y} {}
	    method PointRelease {x y} {}
	    method MoveInitStack {x y} {}
	    method MoveMotionStack {x y} {}
	    method MoveReleaseStack {x y} {}
	    method MoveInitCard {x y} {}
	    method MoveMotionCard {x y} {}
	    method MoveReleaseCard {x y} {}
	    method DeleteStack {} {}
	    method DeleteCard {} {}
	    method StackPopup {x y} {}
	    method CardPopup {x y} {}
	    method PopupRelease {}
	    method NewCard {x y}
	    method NewBlankCard {}
	    method NewCardAutoPlace {}
	    method ShowMe {}
	    method ShowAll {}
	    method Hide {}
	    method MixStack {}
	    method GetValue {name}
	    method InvokeCardStack {args}
	    method CheckIfEmptyStack {}
	}
    
	# ----------------------------
	# Private static data members.
	# ----------------------------

	private common cardstackMenu
	private common cardMenu
	private common cardStatePopup
	private common stickyDistance 20
	private common autoPlaceOffset 6
	private common idpopup
	private common inited 0
	private common sound 0
	
	# ---------------------------
	# Private class data members.
	# ---------------------------
	
	protected {
	    variable idstack
	    variable utagstack
	    variable csObj
	    variable move
	    variable idcard
	    variable currentCard
	    variable played 0
	    variable emptyPointStackBinds
	    variable emptyInstBinds
	}    
    }

    body CardGame::constructor {w x y args} {
	
	::Debug 4 "CardGame::constructor $this, args='$args'"
	
	MakeMenus
	
	# CardStack object as a canvas item.
	set csObj [CardStack #auto]
	$csObj MixCards
	
	# Make actual canvas item(s).
	eval {DrawCardStack $x $y} $args
	
	# All special bindings for the card stack.
	# %W will be substituted by the canvas widget path.
	# 
	# IMPORTANT: we cannot access instance specific stuff,
	# variables and such, when binding to tags shared by many objects!
	set b1Stack        {%W bind cardstack <Button-1>}
	set b1MotionStack  {%W bind cardstack <B1-Motion>}
	set b1ReleaseStack {%W bind cardstack <ButtonRelease-1>}
	set b1Card         {%W bind playcard <Button-1>}
	set b1MotionCard   {%W bind playcard <B1-Motion>}
	set b1ReleaseCard  {%W bind playcard <ButtonRelease-1>}
	
	set b1StackInst         [list %W bind $idstack <Button-1>]
	set b1MotionStackInst   [list %W bind $idstack <B1-Motion>]
	set b1ReleaseStackInst  [list %W bind $idstack <ButtonRelease-1>]
	
	switch -- [tk windowingsystem] {
	    aqua {
		set b1PopupStack {%W bind cardstack <Control-Button-1>}
		set b1PopupCard  {%W bind playcard  <Control-Button-1>}
		set b1PopupRel   {%W bind playcard  <Control-ButtonRelease-1>}
		set b2PopupStack {%W bind cardstack <Button-2>}
		set b2PopupCard  {%W bind playcard  <Button-2>}
	    }
	    default {
		set b3PopupStack {%W bind cardstack <Button-3>}
		set b3PopupCard  {%W bind playcard  <Button-3>}
	    }
	}
	
	set classBindList [list \
	  move    [list $b1Stack        [code $this MoveInitStack %x %y]] \
	  move    [list $b1MotionStack  [code $this MoveMotionStack %x %y]] \
	  move    [list $b1ReleaseStack [code $this MoveReleaseStack %x %y]] \
	  move    [list $b1Card         [code $this MoveInitCard %x %y]] \
	  move    [list $b1MotionCard   [code $this MoveMotionCard %x %y]] \
	  move    [list $b1ReleaseCard  [code $this MoveReleaseCard %x %y]] \
	  del     [list $b1Card         [code $this DeleteCard]] ]
	set instBindList [list \
	  point   [list $b1StackInst        [code $this PointPress %x %y]] \
	  point   [list $b1MotionStackInst  [code $this PointMotion %x %y]] \
	  point   [list $b1ReleaseStackInst [code $this PointRelease %x %y]] \
	  del     [list $b1StackInst        [code $this DeleteStack]] ]

	set emptyPointStackBinds [list \
	  point   [list $b1StackInst        {}] \
	  point   [list $b1MotionStackInst  {}] \
	  point   [list $b1ReleaseStackInst {}]]
	set emptyInstBinds [list \
	  point   [list $b1StackInst        {}] \
	  point   [list $b1MotionStackInst  {}] \
	  point   [list $b1ReleaseStackInst {}] \
	  del     [list $b1StackInst        {}]]

	switch -- [tk windowingsystem] {
	    aqua {
		lappend classBindList \
		  point   [list $b1PopupStack   [code $this StackPopup %X %Y]] \
		  *       [list $b1PopupCard    [code $this CardPopup %X %Y]]  \
		  *       [list $b1PopupRel     [code $this PopupRelease]]  \
		  point   [list $b2PopupStack   [code $this StackPopup %X %Y]] \
		  *       [list $b2PopupCard    [code $this CardPopup %X %Y]]
	    }
	    default {
		lappend classBindList \
		  point   [list $b3PopupStack   [code $this StackPopup %X %Y]] \
		  *       [list $b3PopupCard    [code $this CardPopup %X %Y]]
	    }
	}
	
	# The naming here is a bit confusing...
	RegisterCanvasClassBinds CardGame $classBindList
	RegisterCanvasInstBinds  CardGame:$this $instBindList
	
	# Check if swash.wav sound available.
	if {!$inited} {
	    Init
	}
	bind $tkCanvas <Destroy> +[list delete object $this]
    }

    body CardGame::destructor {} {	
	# empty, so far.
    }
    
    body CardGame::Init {} {
	
	# Check if swash.wav sound available.
	# Eventually we need an application base class for things like this...
	if {[component::exists Sounds]} {
	    ::Sounds::Create swash [file join [GetThis soundsPath] swash.wav]
	    set sound 1
	}
	::WB::RegisterHandler CARDGAME [code Handler]
	set inited 1
    }
    
    body CardGame::Handler {w type cmd args} {
	
	::Debug 4 "CardGame::Handler w=$w, type=$type, cmd=$cmd"
	
	switch -- [lindex $cmd 1] {
	    picked {

		# The remote cardstack has picked this card. Remove from stack!
		set utag [lindex $cmd 2]
		set card [lindex $cmd 3]
		
		# Need to backtrace from utag to actual object.
		set obj [GetThisFromStackUtag $utag]
		if {$obj != ""} {
		    $obj InvokeCardStack DrawCard $card
		    $obj CheckIfEmptyStack
		}
	    }
	}
    }
    
    # GetThisFromStackUtag --
    # 
    #   Static method to map from a stacks utag to the actual object.
    #   Needed since utags are the only globally uniqe identifier here.

    body CardGame::GetThisFromStackUtag {utag} {
	
	set ansObj ""
	foreach obj [itcl::find objects -class CardGame] {
	    set tmputag [$obj GetValue utagstack]
	    if {[string equal $utag $tmputag]} {
		set ansObj $obj
		break
	    }
	}
	return $ansObj
    }

    body CardGame::GetValue {name} {
	return [set $name]
    }
    
    body CardGame::InvokeCardStack {args} {
	eval {$csObj} $args
    }
    
    body CardGame::DrawCardStack {x y args} {
	
	array set argsArr $args
	if {[info exists argsArr(-tags)]} {
	    set utag $argsArr(-tags)
	} else {
	    set utag [NewUtag]
	}
	set utagstack $utag
	set im [$csObj Image cardpile]
	
	# Note that the object name $this is only defined locally!
	# Use $utagstack for globally identfying the stack.
	set idstack [$tkCanvas create image $x $y -image $im -anchor nw  \
	  -tags [list image cardstack object:${this} $utag]]

	foreach {key value} $args {
	    switch -- $key {
		-topcard {
		    $csObj MakeTopmost $value
		}
		-cards {
		    foreach cmd $value {
			set id [eval {$tkCanvas} $cmd]
			$tkCanvas addtag cardstackutag:${utagstack} withtag $id 
			$tkCanvas addtag [NewUtag] withtag $id 
		    }
		}
	    }
	}
    }
    
    body CardGame::CheckIfEmptyStack {} {

	if {[$csObj NumberOfCards] == 0} {
	    RegisterCanvasInstBinds CardGame $emptyPointStackBinds
	    ItemConfigure $idstack -image [$csObj Image black]
	}
    }

    body CardGame::MakeMenus {} {
	
	# Only a single set per canvas.
	set cardstackMenu ${tkCanvas}.csmenu
	if {![winfo exists $cardstackMenu]} {
	    menu $cardstackMenu -tearoff 0
	    if {0} {
		$cardstackMenu add command -label [mc "Mix Stack"]  \
		  -command [code $this MixStack]
		$cardstackMenu add command -label [mc "New Card"]  \
		  -command [code $this NewCardAutoPlace]
	    }
	    set cardMenu [menu ${tkCanvas}.camenu -tearoff 0]
	    $cardMenu add radiobutton -label [mc "Show Me"]  \
	      -command [code $this ShowMe] -variable [scope cardStatePopup] \
	      -value half
	    $cardMenu add radiobutton -label [mc "Show All"]  \
	      -command [code $this ShowAll] -variable [scope cardStatePopup] \
	      -value up
	    $cardMenu add radiobutton -label [mc Hide]  \
	      -command [code $this Hide] -variable [scope cardStatePopup] \
	      -value back
	}
    }

    body CardGame::PointPress {x y} {
	
	# New anonymous card. True card created on button release.
	NewBlankCard
	set off 3
	$tkCanvas move $idcard $off $off
	set move(x) [$tkCanvas canvasx $x]
	set move(y) [$tkCanvas canvasy $y]
	set move(x0) $move(x)
	set move(y0) $move(y)
	set move(id) [$tkCanvas find withtag $idcard]
	
	# Shadow to highlight that a new card has been created.
	foreach {x1 y1 x2 y2} [$tkCanvas bbox $idcard] {
	    incr x1 $off
	    incr y1 $off
	    incr x2 $off
	    incr y2 $off
	}
	set move(idshadow) [$tkCanvas create rectangle $x1 $y1 $x2 $y2  \
	  -outline {} -fill gray60]
	$tkCanvas lower $move(idshadow) $idcard
    }

    body CardGame::PointMotion {x y} {
	
	set x [$tkCanvas canvasx $x]
	set y [$tkCanvas canvasy $y]
	set dx [expr {$x - $move(x)}]
	set dy [expr {$y - $move(y)}]
	$tkCanvas move $move(id) $dx $dy
	$tkCanvas move $move(idshadow) $dx $dy
	set move(x) $x
	set move(y) $y
	
	if {$sound && !$played && \
	  [expr {hypot($x - $move(x0), $y - $move(y0))}] > $stickyDistance} {
	    ::Sounds::Play swash
	    set played 1
	}
	CancelBox
    }

    body CardGame::PointRelease {x y} {
	
	$tkCanvas delete $move(idshadow)
	set x [$tkCanvas canvasx $x]
	set y [$tkCanvas canvasy $y]
	if {[expr {hypot($x - $move(x0), $y - $move(y0))}] < $stickyDistance} {
	    $tkCanvas delete $idcard
	} else {
	    set coo [$tkCanvas coords $idcard]
	    $tkCanvas delete $idcard
	    
	    # Pick a new card.
	    eval {NewCard} $coo
	    if {[$csObj NumberOfCards] == 0} {
		ItemConfigure $idstack -image [$csObj Image black]
	    }	    
	    set imhalf [$csObj HalfImage $currentCard]
	    $tkCanvas itemconfigure $idcard -image $imhalf
	    set imback [$csObj Image back]
	    set cmd [list create image [$tkCanvas coords $idcard] \
	      -image $imback -anchor nw -tags [$tkCanvas gettags $idcard]]
	    Command $cmd remote
	    
	    # We must tell the remote cardstack to remove this card from stack.
	    GenCommand "CARDGAME: picked $utagstack $currentCard" remote
	    CheckIfEmptyStack
	}
	set played 0
    }

    body CardGame::MoveInitStack {x y} {  
	InitMoveCurrent $x $y
    }
    
    body CardGame::MoveMotionStack {x y} {
	DragMoveCurrent $x $y
    }
    
    body CardGame::MoveReleaseStack {x y} {
	FinalMoveCurrent $x $y
	set utag [GetUtag current]
	Command [list raise $utag]
    }
    
    body CardGame::MoveInitCard {x y} {
	InitMoveCurrent $x $y
    }
    
    body CardGame::MoveMotionCard {x y} {    
	DragMoveCurrent $x $y
    }
    
    body CardGame::MoveReleaseCard {x y} {
	
	FinalMoveCurrent $x $y
	set utag [GetUtag current]
	Command [list raise $utag]
    }
    
    body CardGame::DeleteStack {} {

	set cmdList [list [list delete $utagstack]]
	DeregisterCanvasInstBinds CardGame:$this
	
	# Delete all cards as well.
	foreach id [$tkCanvas find withtag cardstackutag:${utagstack}] {
	    lappend cmdList [list delete [GetUtag $id]]
	}
	CommandList $cmdList
    }
    
    body CardGame::DeleteCard {} {

	# We could try having an undo command as well...
	set utag [GetUtag current]
	Command [list delete $utag]

    }
    
    body CardGame::StackPopup {x y} {
	
	set idpopup [$tkCanvas find withtag current]
	tk_popup $cardstackMenu [expr {int($x) - 10}] [expr {int($y) - 10}] 
    }

    body CardGame::CardPopup {x y} {
	
	set idpopup [$tkCanvas find withtag current]
	set im [$tkCanvas itemcget $idpopup -image]
	set state [$csObj CardSideFromImage $im]
	set cardStatePopup $state
	tk_popup $cardMenu [expr {int($x) - 10}] [expr {int($y) - 10}]   
    }
    
    body CardGame::PopupRelease {} {
	CancelBox
    }
    
    body CardGame::NewCard {x y} {
	
	set card [$csObj PopAndMix]
	set currentCard $card
	if {$card != ""} {
	    set im [$csObj Image back]

	    # We use cardstackutag:.. to indicate which stack
	    # a card comes from.
	    set tags [list image playcard cardstackutag:${utagstack} \
	      card:${card} [NewUtag]]
	    set idcard [$tkCanvas create image $x $y -image $im -anchor nw \
	      -tags $tags]
	}
    }
    
    body CardGame::NewBlankCard {} {
	
	foreach {x y} [$tkCanvas coords $idstack] break
	set im [$csObj Image back]
	set idcard [$tkCanvas create image $x $y -image $im -anchor nw]
    }

    body CardGame::NewCardAutoPlace {} {
	
	# This one does not yet work properly!	
	NewCard
	if {$idcard != ""} {
	    foreach {xstack ystack} [$tkCanvas coords $idstack] break
	    set x [expr {$xstack + $stickyDistance + 20}]
	    set y $ystack	    
	    set cmd [list create image $x $y \
	      -image [$tkCanvas itemcget $idcard -image] -anchor nw \
	      -tags [$tkCanvas gettags $idcard]]
	    Command $cmd
	}
    }
    
    body CardGame::MixStack {} {
	# We do this when drawing cards
	#$csObj MixCards
    }
    
    body CardGame::ShowMe {} {
	
	CancelBox
	set tags [$tkCanvas gettags $idpopup]
	if {[regexp {card:([a-z0-9]{2})} $tags match card]} {
	    $tkCanvas itemconfigure $idpopup -image [$csObj HalfImage $card]
	}
	set utag [GetUtag $idpopup]
	Command [list raise $utag]
    }
    
    body CardGame::ShowAll {} {
	
	CancelBox
	set tags [$tkCanvas gettags $idpopup]
	if {[regexp {card:([a-z0-9]{2})} $tags match card]} {
	    ItemConfigure $idpopup -image [$csObj Image $card]
	}
	set utag [GetUtag $idpopup]
	Command [list raise $utag]
    }
    
    body CardGame::Hide {} {
	
	CancelBox
	set tags [$tkCanvas gettags $idpopup]
	if {[regexp {card:([a-z0-9]{2})} $tags match card]} {
	    ItemConfigure $idpopup -image [$csObj Image back]
	}
    }
    
    # CardGame::Save --
    #
    #       Returns a oneline import command. Used from app.
    #       
    # Arguments:
    #       id          item id or tag
    #       args:
    #           -basepath absolutePath    translate image -file to a relative path.
    #           -uritype ( file | http )
    #           -keeputag 0|1
    #       
    # Results:
    #       a single command line.

    body CardGame::Save {id args} {
	
	# Seemed to be the only way :-(
	upvar [namespace current]::infoScript infoScript

	set tags [$tkCanvas gettags $id]
	if {[lsearch $tags cardstack] < 0} {
	    return
	}
	array set argsArr {
	    -uritype file
	}
	array set argsArr $args
	set uriopts [eval {
	    ::CanvasUtils::GetImportOptsURI $argsArr(-uritype) $infoScript
	} $args]

	set impcmd [concat "import" [$tkCanvas coords $id] $uriopts]
	set im [$csObj Image cardpile]
	lappend impcmd -mime application/x-itcl
	lappend impcmd -width [image width $im] -height [image height $im]
	
	# Get topmost card.
	lappend impcmd -topcard [$csObj TopCard]
	set allcards {}
	
	# Find all cards.
	set tagsearch playcard&&cardstackutag:${utagstack}
	foreach idc [$tkCanvas find withtag $tagsearch] {
	    set ctags [$tkCanvas gettags $idc]
	    set savetags {image playcard}
	    if {[regexp {card:([a-z0-9]{2})} $ctags match card]} {
		lappend savetags card:${card}
	    }
	    if {[regexp {(state:([a-z]+))} $ctags match stag state]} {
		lappend savetags state:${state}
	    }
	    set im [$tkCanvas itemcget $idc -image]
	    set cardspec [concat {create image} [$tkCanvas coords $idc] \
	      -anchor nw -tags [list $savetags] -image $im]
	    lappend allcards $cardspec
	}
	lappend impcmd -cards $allcards
	return $impcmd
    }


    body CardGame::Delete {id} {
		
	switch -- $id $idstack { 
	    DeleteStack
	} default {
	    
	    # never used it seems...
	    set utag [GetUtag $id]
	    return [list [list delete $utag] {}]
	}
    }
}

# We must instantiate ourself...

eval {CardGame #auto $w $x $y} $args