2
$\begingroup$

I would like to change the colour of different regions if both are clicked. I can work around this with

j = 1; DynamicModule[{col = Green}, 
 EventHandler[
  Graphics[{EdgeForm[Black], White, Rectangle[{0, 0}, {3, 3}], 
    EdgeForm[None], Dynamic@col, Rectangle[{0, 0}, {1, 1}], 
    Rectangle[{2, 2}, {3, 3}]}, 
   ImageSize -> 300], {"MouseDown" :> 
    If[Or[MousePosition["Graphics"][[1]] > 0 && 
        MousePosition["Graphics"][[1]] < 1 && 
        MousePosition["Graphics"][[2]] > 0 && 
        MousePosition["Graphics"][[2]] < 1, 
       MousePosition["Graphics"][[1]] > 2 && 
        MousePosition["Graphics"][[1]] < 3 && 
        MousePosition["Graphics"][[2]] > 2 && 
        MousePosition["Graphics"][[2]] < 3] && 
      j == 2, (col = 
       col /. {Red -> Green, Green -> Red}), ++j]}]]

but it isn't stable. I would like to only change the colour if both regions are clicked.

Ideally, I would also like j to reset to 0 if the white area is clicked.

$\endgroup$

1 Answer 1

3
$\begingroup$
DynamicModule[{colors = {Green, Green, Red}, i = 1, j = 0, r1 = False, r2 = False}, 
 EventHandler[
  Graphics[{EdgeForm[Black], White, Rectangle[{0, 0}, {3, 3}], 
    EdgeForm[None], Dynamic@colors[[i]], Rectangle[{0, 0}, {1, 1}], 
    Rectangle[{2, 2}, {3, 3}]}, ImageSize -> 300],
  {"MouseDown" :>
    Which[
     RegionMember[Rectangle[{0, 0}, {1, 1}], 
       MousePosition["Graphics"]] && ! r1 && ! r2, {i++, r1 = True},
     RegionMember[Rectangle[{2, 2}, {3, 3}], 
       MousePosition["Graphics"]] && r1 && ! r2, {i++, r2 = True},
     RegionMember[Rectangle[{2, 2}, {3, 3}], 
       MousePosition["Graphics"]] && ! r1 && ! r2, {i++, r2 = True},
     RegionMember[Rectangle[{0, 0}, {1, 1}], 
       MousePosition["Graphics"]] && r2 && ! r1, {i++, r1 = True},
     !RegionMember[
        RegionUnion[Rectangle[{0, 0}, {1, 1}], 
         Rectangle[{2, 2}, {3, 3}]], MousePosition["Graphics"]] && i == 3,
     {i = 1; r1 = False; r2 = False}
     ]}]]

enter image description here

$\endgroup$
1
  • $\begingroup$ Thak you - this is great $\endgroup$
    – martin
    Commented Aug 14 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.