
    AHjK                    ~   d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZmZmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl m!Z!m"Z" ddl#m$Z$ ddl%m&Z&m'Z' ddl(m)Z) ddl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 e G d d             Z1dZ2dZ3dZ4e2e3e4dZ5 G d dejl                        Z7 G d dejp                        Z9 G d d e&      Z: G d! d"ejl                  d#$      Z; G d% d&ejp                        Z< G d' d(e      Z=e>d)k(  r)dd*lm?Z?  G d+ d,e?      Z@ e@       ZAeAj                          y-y-).zz
An implementation of the "Sliding Tile" puzzle.

Textual isn't a game engine exactly, but it wasn't hard to build this.

    )annotations)sleep)defaultdict)	dataclass)product)choice)	monotonic)ConsoleRenderable)Syntax)
containerseventsonwork)	loop_last)ComposeResult)Binding)
PageScreen)OffsetSize)reactive)ModalScreenScreen)Timer)ButtonDigitsFooterMarkdownSelectStaticc                  0    e Zd ZU dZded<   ded<   ded<   y)NewGamez,A dataclass to report the desired game type.strlanguagecodetuple[int, int]sizeN)__name__
__module____qualname____doc____annotations__     I/root/tools/cai/cai_env/lib/python3.12/site-packages/textual/demo/game.pyr!   r!       s    6M
I
r-   r!   a  class SpatialMap(Generic[ValueType]):
    """A spatial map allows for data to be associated with rectangular regions
    in Euclidean space, and efficiently queried.

    When the SpatialMap is populated, a reference to each value is placed into one or
    more buckets associated with a regular grid that covers 2D space.

    The SpatialMap is able to quickly retrieve the values under a given "window" region
    by combining the values in the grid squares under the visible area.
    """

    def __init__(self, grid_width: int = 100, grid_height: int = 20) -> None:
        """Create a spatial map with the given grid size.

        Args:
            grid_width: Width of a grid square.
            grid_height: Height of a grid square.
        """
        self._grid_size = (grid_width, grid_height)
        self.total_region = Region()
        self._map: defaultdict[GridCoordinate, list[ValueType]] = defaultdict(list)
        self._fixed: list[ValueType] = []

    def _region_to_grid_coordinates(self, region: Region) -> Iterable[GridCoordinate]:
        """Get the grid squares under a region.

        Args:
            region: A region.

        Returns:
            Iterable of grid coordinates (tuple of 2 values).
        """
        # (x1, y1) is the coordinate of the top left cell
        # (x2, y2) is the coordinate of the bottom right cell
        x1, y1, width, height = region
        x2 = x1 + width - 1
        y2 = y1 + height - 1
        grid_width, grid_height = self._grid_size

        return product(
            range(x1 // grid_width, x2 // grid_width + 1),
            range(y1 // grid_height, y2 // grid_height + 1),
        )
aj  <?xml version="1.0" encoding="UTF-8"?>
<movies>
    <movie>
        <title>Back to the Future</title> <year>1985</year> <director>Robert Zemeckis</director>
        <genre>Science Fiction</genre> <rating>PG</rating>
        <cast>
            <actor> <name>Michael J. Fox</name> <role>Marty McFly</role> </actor>
            <actor> <name>Christopher Lloyd</name> <role>Dr. Emmett Brown</role> </actor>
        </cast>
    </movie>
    <movie>
        <title>The Breakfast Club</title> <year>1985</year> <director>John Hughes</director>
        <genre>Drama</genre> <rating>R</rating>
        <cast>
            <actor> <name>Emilio Estevez</name> <role>Andrew Clark</role> </actor>
            <actor> <name>Molly Ringwald</name> <role>Claire Standish</role> </actor>
        </cast>
    </movie>
    <movie>
        <title>Ghostbusters</title> <year>1984</year> <director>Ivan Reitman</director>
        <genre>Comedy</genre> <rating>PG</rating>
        <cast>
            <actor> <name>Bill Murray</name> <role>Dr. Peter Venkman</role> </actor>
            <actor> <name>Dan Aykroyd</name> <role>Dr. Raymond Stantz</role> </actor>
        </cast>
    </movie>
    <movie>
        <title>Die Hard</title> <year>1988</year> <director>John McTiernan</director>
        <genre>Action</genre> <rating>R</rating>
        <cast>
            <actor> <name>Bruce Willis</name> <role>John McClane</role> </actor>
            <actor> <name>Alan Rickman</name> <role>Hans Gruber</role> </actor>
        </cast>
    </movie>
    <movie>
        <title>E.T. the Extra-Terrestrial</title> <year>1982</year> <director>Steven Spielberg</director>
        <genre>Science Fiction</genre> <rating>PG</rating>
        <cast>
            <actor> <name>Henry Thomas</name> <role>Elliott</role> </actor>
            <actor> <name>Drew Barrymore</name> <role>Gertie</role> </actor>
        </cast>
    </movie>
</movies>a  [life.b -- John Horton Conway's Game of Life
(c) 2021 Daniel B. Cristofani
]

>>>->+>+++++>(++++++++++)[[>>>+<<<-]>+++++>+>>+[<<+>>>>>+<<<-]<-]>>>>[
  [>>>+>+<<<<-]+++>>+[<+>>>+>+<<<-]>>[>[[>>>+<<<-]<]<<++>+>>>>>>-]<-
]+++>+>[[-]<+<[>+++++++++++++++++<-]<+]>>[
  [+++++++++.-------->>>]+[-<<<]>>>[>>,----------[>]<]<<[
    <<<[
      >--[<->>+>-<<-]<[[>>>]+>-[+>>+>-]+[<<<]<-]>++>[<+>-]
      >[[>>>]+[<<<]>>>-]+[->>>]<-[++>]>[------<]>+++[<<<]>
    ]<
  ]>[
    -[+>>+>-]+>>+>>>+>[<<<]>->+>[
      >[->+>+++>>++[>>>]+++<<<++<<<++[>>>]>>>]<<<[>[>>>]+>>>]
      <<<<<<<[<<++<+[-<<<+]->++>>>++>>>++<<<<]<<<+[-<<<+]+>->>->>
    ]<<+<<+<<<+<<-[+<+<<-]+<+[
      ->+>[-<-<<[<<<]>[>>[>>>]<<+<[<<<]>-]]
      <[<[<[<<<]>+>>[>>>]<<-]<[<<<]]>>>->>>[>>>]+>
    ]>+[-<<[-]<]-[
      [>>>]<[<<[<<<]>>>>>+>[>>>]<-]>>>[>[>>>]<<<<+>[<<<]>>-]>
    ]<<<<<<[---<-----[-[-[<->>+++<+++++++[-]]]]<+<+]>
  ]>>
]

[This program simulates the Game of Life cellular automaton.

Type e.g. "be" to toggle the fifth cell in the second row, "q" to quit,
or a bare linefeed to advance one generation.

Grid wraps toroidally. Board size in parentheses in first line (2-166 work).

This program is licensed under a Creative Commons Attribution-ShareAlike 4.0
International License (http://creativecommons.org/licenses/by-sa/4.0/).]
)PythonXMLBFc                  p     e Zd ZU dZdZ ee      Zded<   	 	 	 	 	 	 	 	 	 	 d	 fdZ	d
dZ
ddZddZ xZS )TilezAn individual tile in the puzzle.

    A Tile is a container with a static inside it.
    The static contains the code (as a Rich Syntax object), scrolled so the
    relevant portion is visible.
    z
    Tile {
        position: absolute;
        Static {
            width: auto;
            height: auto;
            &:hover { tint: $primary 30%; }
        }       
        &#blank { visibility: hidden; }
    }
    zreactive[Offset]positionc                    || _         || _        || _        || _        t        |   |dnd| j                          | j                  t        j                  |       y )Nblanktileid)	
renderabler7   	tile_sizestart_positionsuper__init__set_reactiver3   r4   )selfr:   r7   r&   r4   	__class__s        r.   r>   zTile.__init__   sW     %	&t|G4		{9KL$--2r-   c              #  ^  K   t        | j                  d| j                  dnt        | j                              }| j                  J | j                  j
                  j                  |j
                  _        | j                  j
                  j                  |j
                  _        | y w)Nr7   r6   )classesname)r   r:   r7   r"   parentstyleswidthheight)r@   statics     r.   composezTile.compose   s     OO II-3tyy>

 {{&&&"kk0066#{{1188s   B+B-c                   | j                   X| j                  \  }}|| j                  _        || j                  _        | j
                  \  }}| j                  ||z  ||z         | j
                  | j                  z  | _        y N)r7   r;   rF   rG   rH   r4   
set_scrolloffset)r@   rG   rH   columnrows        r.   on_mountzTile.on_mount   sh    99  NNME6 %DKK!'DKK--KFCOOFUNC&L9mmdnn4r-   c                F    | j                  d|| j                  z  d       y)zdThe 'position' is in tile coordinate.
        When it changes we animate it to the cell coordinates.rN   g?)durationN)animater;   r@   r4   s     r.   watch_positionzTile.watch_position   s     	Xx$..83Gr-   )
r:   r
   r7   
int | Noner&   r   r4   r   returnNonerX   r   rX   rY   )r4   r   rX   rY   )r'   r(   r)   r*   DEFAULT_CSSr   r   r4   r+   r>   rJ   rQ   rV   __classcell__rA   s   @r.   r3   r3      sf    
K "*&!1H13%3 3 	3
 3 
3	5Hr-   r3   c                  N    e Zd ZdZdZddZ eej                        dd       Z	y)
GameDialogz9A dialog to ask the user for the initial game parameters.an  
        GameDialog {
            background: $boost;
            border: thick $primary-muted;
            padding: 0 2;
            width: 50;
            #values {
                width: 1fr;
                Select { margin: 1 0;}
            }
            Button {
                margin: 0 1 1 1;
                width: 1fr;
            }
        }        
    c              #    K   t        j                  d      5  t        j                  t        j                         dddd       t        g dd	d
dd       d d d        t        dd       y # 1 sw Y   xY ww)Nvaluesr8   Languager/   r#   F)promptvaluer9   allow_blank))z
Easy (3x3))   rg   )zMedium (4x4)   ri   )z
Hard (5x5))   rj   Levelrh   levelStartprimary)variant)r   VerticalGroupr   from_valuesLEVELSkeysr   r@   s    r.   rJ   zGameDialog.compose   s     %%2 	$$!!  
 !
 
	& Wi00'	 	s   B AA4B 4A=9B c                    | j                  dt              j                  }| j                  dt              j                  }||J | j                  j	                  t        |t        |   |             y )Nz	#languagez#level)	query_oner   	selectionscreendismissr!   rr   )r@   r#   rl   s      r.   on_button_pressedzGameDialog.on_button_pressed  s_    >>+v6@@x0::#(999GHfX.>FGr-   NrZ   r[   )
r'   r(   r)   r*   r\   rJ   r   r   Pressedrz   r,   r-   r.   r`   r`      s0    CK"1, H Hr-   r`   c                  "    e Zd ZdZdZdgZddZy)GameDialogScreenz#Modal screen containing the dialog.zT
    GameDialogScreen {      
        align: center middle;              
    }
    )escapery   c              #  $   K   t                y wrL   )r`   rt   s    r.   rJ   zGameDialogScreen.compose)  s     ls   NrZ   )r'   r(   r)   r*   CSSBINDINGSrJ   r,   r-   r.   r}   r}     s    -C &&Hr-   r}   c            	          e Zd ZU dZdZdZ edddd       edd	dd       ed
dd
d       edddd      gZ ed      Z	 ee
      Zded<    edd      Z ed      Z e edd            Z ed      Z ed      Z	 	 	 	 	 	 	 	 	 	 d& fdZd'dZd(dZd)dZd*dZd+dZd,dZd-dZd.dZd/dZd0dZd1d Zd2d!Z ed"      d3d4d#       Z  e!e"jF                  d$      d5d%       Z$ xZ%S )6GamezWidget for the game board.Fa  
    Game {
        visibility: hidden;
        align: center middle;
        hatch: right $panel;
        border: heavy transparent;
        &:focus {
            border: heavy $success;
        }
        #grid {
            border: heavy $primary;           
            hatch: right $panel;
            box-sizing: content-box;
        }
        Digits {
            width: auto;
            color: $foreground;
        }
    }
    upz
move('up')T)prioritydownzmove('down')leftzmove('left')rightzmove('right')waitingzreactive[float]play_start_timeg        )init rg   c                   | j                  t        j                  |       | j                  t        j                  |       t	        d       | _        t        |           t        | | _	        t        | | _
        d | _        y rL   )r?   r   r$   r#   r   	locationsr=   r>   r   
dimensionsr;   
play_timer)r@   r$   r#   r   r;   rA   s        r.   r>   zGame.__init__U  sc     	$))T*$--2:Ed:K
+y)(,r-   c                L    t        d | j                  t              D              S )Nc              3  N   K   | ]  }|j                   |j                  k(    y wrL   )r<   r4   ).0r7   s     r.   	<genexpr>z!Game.check_win.<locals>.<genexpr>e  s     UD4&&$--7Us   #%)allqueryr3   rt   s    r.   	check_winzGame.check_wind  s    UDJJtDTUUUr-   c                    | j                   j                          |\  }}t        t        d||z              D ]*  \  }}t	        t        ||       }|rd n|| j                   |<   , y )Nr   )r   clearr   ranger   divmod)r@   r   
tile_widthtile_heightlasttile_nor4   s          r.   watch_dimensionszGame.watch_dimensionsg  se    ",
K&uQ
[0H'IJ 	AMD'vgz:;H/3tDNN8$	Ar-   c              #    K   t        | j                  | j                  j                         ddd      }| j                  \  }}d| _        t        d       t        j                  d      5 }|| j                  d   z  |j                  _        || j                  d	   z  |j                  _        t        t        |      t        |            D ]:  \  }}t        ||      }| j                   |   }t#        ||| j                  |       < 	 d d d        | j                  r| j%                  | j&                         y y # 1 sw Y   2xY ww)
NTmaterial)indent_guidesline_numbersthemer   r   gridr8   r      )r   r$   r#   lowerr   stater   r   HorizontalGroupr;   rF   rG   rH   r   r   r   r   r3   call_after_refreshshuffle)	r@   syntaxr   r   r   rP   rO   r4   r   s	            r.   rJ   zGame.composen  s"    IIMM!
 #'//
K
Rj''62 	Fd *T^^A-> >DKK!,t~~a/@!@DKK&uZ'8%:LM FV!#v...267DNNHEEF	F ==##DLL1 	F 	Fs   A,E
.BD>1E
>EE
c                `    | j                   dk(  rt               | j                  z
  }|| _        y y )Nplaying)r   r	   r   	play_time)r@   elapseds     r.   update_clockzGame.update_clock  s,    ::"kD$8$88G$DN #r-   c                    t        |d      \  }}t        |d      \  }}| j                  t              j                  |dd|dd|d       y )N<   z02,.0f:z02.0fz04.1f)r   rv   r   update)r@   r   minutessecondshourss        r.   watch_play_timezGame.watch_play_time  sR    !)R0,wv%%vaaPU&WXr-   c                    | j                   | j                   j                          |dk(  r1t               | _        | j	                  d| j
                        | _         y y )Nr   g?)r   stopr	   r   set_intervalr   )r@   	old_state	new_states      r.   watch_statezGame.watch_state  sM    ??&OO  "	!#,;D "//8I8IJDO "r-   c                N    | j                  |dt              S d| t              S )z%Get a tile (int) or the blank (None).z#blankz#tile)rv   r3   )r@   r7   s     r.   get_tilezGame.get_tile  s'    ~~$,hDQQeD6NDQQr-   c                p    || j                   vrt        d      | j                  | j                   |         S )z9Get a tile at the given position, or raise an IndexError.zNo tile)r   
IndexErrorr   rU   s     r.   get_tile_atzGame.get_tile_at  s1    4>>)Y''}}T^^H566r-   c                V   | j                  |      }| j                  d      }|j                  }d| j                  |j                  <   |j                  |_        || j                  |<   ||_        | j                  dk(  r,| j	                         rd| _        | j                  dd       yyy)z_Move a tile to the blank.
        Note: this doesn't do any validation of legal moves.
        Nr   wonzYou won!zSliding Tile Puzzle)title)r   r4   r   r   r   notify)r@   r   r7   r6   blank_positions        r.   	move_tilezGame.move_tile  s     }}W%d#(,t}}%)0~&&::"t~~'7DJKK
*?K@ (8"r-   c                    | j                  d      j                  }| j                  |      j                  }||dz   |dz
  |dz   |dz
  fv S )zCheck if a tile may move.Nr   r   r   r   )r   r4   )r@   r7   r   tile_positions       r.   can_movezGame.can_move  s\    t,55d+44F"F"F"F"	"
 
 	
r-   c                \   | j                   dk7  r| j                  j                          y | j                  d       j                  }|dk(  r|dz   }n |dk(  r|dz   }n|dk(  r|dz   }n
|dk(  r|d	z   }	 | j                        }| j                  |j                         y # t        $ r Y y w xY w)
Nr   r   r   r   r   r   r   r   r   r   )	r   appbellr   r4   r   r   r   r7   )r@   	directionr6   r4   r7   s        r.   action_movezGame.action_move  s    ::"HHMMOd#,,wH& wH& wH'!wH	##H-D 	tyy!  		s   2B 	B+*B+c                    | j                  d      j                  }g }g d}|D cg c]  }||z   | j                  v r||z    }}|D ch c]  }| j                  |      j                   c}S c c}w c c}w )z-Get the positions of all tiles that can move.N)r   r   r   r   )r   r4   r   r   )r@   r6   moves
DIRECTIONSr   r4   s         r.   get_legal_moveszGame.get_legal_moves  s    d#,, :
 (
	!dnn4 I
 

 EJJ  *33JJ

 Ks   A.	"A3)	exclusivec                4  K   d| _         | j                  | j                  j                          d| j                  d      _        d| _        t        dd      }t        |      D ]  }| j                         }|j                  |       | j                  d      j                  }t        t        |            }| j                  |      }| j                  |j                          t#        d       d{     d| j                  d      _        d	| _        y7 $w)
zA worker to do the shuffling.TNz'[reverse bold] SHUFFLING - Please Wait z#grid	shufflingr   g?r   r   )visibler   r   rv   border_titler   r   r   r   discardr   r4   r   listr   r   r7   r   )r@   shufflesprevious_move_legal_movesmove_positionr   s          r.   r   zGame.shuffle  s      ??&OO  "/Xw, 
 &r2x 	A..0K. MM$/88M"4#45M((7INN9>>*+	 02w,
 s   C/D1D2%Dz.tilec                    |j                   J t        |j                   j                  xs d      }| j                  dk7  s| j	                  |      s| j
                  j                          y | j                  |       y )Nr   r   )widgetintrD   r   r   r   r   r   )r@   eventr7   s      r.   on_tile_clickedzGame.on_tile_clicked  s^    ||'''5<<$$)*::"$--*=HHMMOtr-   )
r$   r"   r#   r"   r   r%   r;   r%   rX   rY   )rX   bool)r   r   rX   rY   rZ   r[   )r   floatrX   rY   )r   r"   r   r"   rX   rY   )r7   rW   rX   r3   )r4   r   rX   r3   )r   rW   rX   rY   )r7   r   rX   r   )r   r"   rX   rY   )rX   zset[Offset])   )r   r   rX   rY   )r   zevents.ClickrX   rY   )&r'   r(   r)   r*   ALLOW_MAXIMIZEr\   r   r   r   r   r	   r   r+   r   r$   r   r   r#   r>   r   r   rJ   r   r   r   r   r   r   r   r   r   r   r   r   r   Clickr   r]   r^   s   @r.   r   r   -  sU   $NK, 	lD48>>'DA	H YE'/	':O_:5)IB<D$q!*%JB<D|H-- - $	-
 #- 
-VA2*%
Y
KR7A$	
"&K 
D & g r-   r   T)	can_focusc                      e Zd ZdZdZddZy)GameInstructionsz    GameInstructions {        
        layer: instructions;
        width: 60;
        background: $panel;
        border: thick $primary-darken-2; 
        Markdown {
            background: $panel;
        }
        
    }

am  # Instructions

This is an implementation of the *sliding tile puzzle*.

The board consists of a number of tiles and a blank space.
After shuffling, the goal is to restore the original "image" by moving a square either horizontally or vertically into the blank space.

This version is like the physical game, but rather than an image, you need to restore code.
    c              #     K   t        | j                         t        j                         5  t	        ddd       d d d        y # 1 sw Y   y xY ww)NNew Gamezscreen.new_gamesuccess)actionro   )r   INSTRUCTIONSr   Centerr   rt   s    r.   rJ   zGameInstructions.compose  sK     t(())  	R,=yQQ	R 	R 	Rs   ,AA	AAANrZ   )r'   r(   r)   r\   r   rJ   r,   r-   r.   r   r     s    K	LRr-   r   c                  B    e Zd ZdZdZdgZd
dZddZddZddZ	ddZ
y	)
GameScreenzThe screen containing the game.z
    GameScreen{       
        #container {
            align: center middle;
            layers: instructions game;     
        }
    }
    )nnew_gamer   c              #     K   t        j                  d      5  t                t        dddd       t	                d d d        y # 1 sw Y   y xY ww)N	containerr8   zd



































































































r   rh   )      )r   r;   )r   Verticalr   r   r   rt   s    r.   rJ   zGameScreen.compose'  sI       K0 	"$$z2&GLL(N	 	 	s   A*A	AAAc                J    | j                  t              j                          y rL   )rv   r   r   rt   s    r.   action_shufflezGameScreen.action_shuffle-  s    t$$&r-   c                b    | j                   j                  t               | j                         y )N)callback)r   push_screenr}   r   rt   s    r.   action_new_gamezGameScreen.action_new_game0  s!    -/$--Hr-   c                D  K   |y d| j                  t              _        | j                  t              }d|_        |j
                  |_        |j                  |_        t        |j                   |_	        |j                          d {    |j                          y 7 w)NFr   )rv   r   displayr   r   r$   r#   r   r&   r   	recomposefocus)r@   r   games      r.   r   zGameScreen.new_game3  s|     38'(0~~d#
MM	 )).nn

 	s   BB B	B c                T    |dk(  r#| j                  t              j                  dk(  ry y)Nr   r   T)rv   r   r   )r@   r   
parameterss      r.   check_actionzGameScreen.check_action?  s&    Y4>>$#7#=#=#Jr-   NrZ   r[   )r   zNewGame | NonerX   rY   )r   r"   r  ztuple[object, ...]rX   zbool | None)r'   r(   r)   r*   r\   r   rJ   r  r
  r   r  r,   r-   r.   r   r     s0    )K ..H'I
r-   r   __main__)Appc                      e Zd ZddZy)GameAppc                    t               S rL   )r   rt   s    r.   get_default_screenzGameApp.get_default_screenI  s
    <r-   N)rX   r   )r'   r(   r)   r  r,   r-   r.   r  r  H  s    	 r-   r  N)Cr*   
__future__r   asyncior   collectionsr   dataclassesr   	itertoolsr   randomr   timer	   rich.consoler
   rich.syntaxr   textualr   r   r   r   textual._loopr   textual.appr   textual.bindingr   textual.demo.pager   textual.geometryr   r   textual.reactiver   textual.screenr   r   textual.timerr   textual.widgetsr   r   r   r   r   r   r!   PYTHON_CODEXML_CODEBF_CODErr   r  r3   rp   r`   r}   r   r   r   r'   r  r  r   runr,   r-   r.   <module>r0     s(   #  # !    *  0 0 # % # ( ) % .  L L   ,\+Z#L  	@<H: <H~/H)) /Hd{ J:$ JZRz// R>) )X z #   )CGGI r-   