Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit bf4c926

Browse files
committed
Operator, Coroutines example
1 parent 1b04c2c commit bf4c926

File tree

2 files changed

+40
-40
lines changed

2 files changed

+40
-40
lines changed

README.md

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2142,10 +2142,10 @@ Operator
21422142
**Module of functions that provide the functionality of operators.**
21432143
```python
21442144
import operator as op
2145-
<el> = op.add/sub/mul/truediv/floordiv/mod(<el>, <el>) # +, -, *, /, //, %
2146-
<int/set> = op.and_/or_/xor(<int/set>, <int/set>) # &, |, ^
2147-
<bool> = op.eq/ne/lt/le/gt/ge(<sortable>, <sortable>) # ==, !=, <, <=, >, >=
2148-
<func> = op.itemgetter/attrgetter/methodcaller(<int/str>) # [<int/str>], .<str>, .<str>()
2145+
<el> = op.add/sub/mul/truediv/floordiv/mod(<el>, <el>) # +, -, *, /, //, %
2146+
<int/set> = op.and_/or_/xor(<int/set>, <int/set>) # &, |, ^
2147+
<bool> = op.eq/ne/lt/le/gt/ge(<sortable>, <sortable>) # ==, !=, <, <=, >, >=
2148+
<func> = op.itemgetter/attrgetter/methodcaller(<el>) # [index/key], .<str>, .<str>()
21492149
```
21502150

21512151
```python
@@ -2300,54 +2300,54 @@ Coroutines
23002300
#### Runs a terminal game where you control an asterisk that must avoid numbers:
23012301

23022302
```python
2303-
import asyncio, collections, curses, enum, random
2303+
import asyncio, collections, curses, curses.textpad, enum, random
23042304

23052305
P = collections.namedtuple('P', 'x y') # Position
23062306
D = enum.Enum('D', 'n e s w') # Direction
2307+
W, H = 15, 7 # Width, Height
23072308

23082309
def main(screen):
23092310
curses.curs_set(0) # Makes cursor invisible.
23102311
screen.nodelay(True) # Makes getch() non-blocking.
23112312
asyncio.run(main_coroutine(screen)) # Starts running asyncio code.
23122313

23132314
async def main_coroutine(screen):
2314-
state = {'*': P(0, 0), **{id_: P(30, 10) for id_ in range(10)}}
2315+
state = {'*': P(0, 0), **{id_: P(W//2, H//2) for id_ in range(10)}}
23152316
moves = asyncio.Queue()
23162317
coros = (*(random_controller(id_, moves) for id_ in range(10)),
2317-
human_controller(screen, moves),
2318-
model(moves, state, *screen.getmaxyx()),
2319-
view(state, screen))
2318+
human_controller(screen, moves), model(moves, state), view(state, screen))
23202319
await asyncio.wait(coros, return_when=asyncio.FIRST_COMPLETED)
23212320

23222321
async def random_controller(id_, moves):
23232322
while True:
23242323
d = random.choice(list(D))
23252324
moves.put_nowait((id_, d))
2326-
await asyncio.sleep(random.random() / 2)
2325+
await asyncio.sleep(random.triangular(0.01, 0.65))
23272326

23282327
async def human_controller(screen, moves):
23292328
while True:
23302329
ch = screen.getch()
23312330
key_mappings = {259: D.n, 261: D.e, 258: D.s, 260: D.w}
23322331
if ch in key_mappings:
23332332
moves.put_nowait(('*', key_mappings[ch]))
2334-
await asyncio.sleep(0.01)
2333+
await asyncio.sleep(0.005)
23352334

2336-
async def model(moves, state, height, width):
2335+
async def model(moves, state):
23372336
while state['*'] not in {p for id_, p in state.items() if id_ != '*'}:
23382337
id_, d = await moves.get()
2339-
p = state[id_]
2338+
x, y = state[id_]
23402339
deltas = {D.n: P(0, -1), D.e: P(1, 0), D.s: P(0, 1), D.w: P(-1, 0)}
2341-
new_p = P(p.x + deltas[d].x, p.y + deltas[d].y)
2342-
if 0 <= new_p.x < width-1 and 0 <= new_p.y < height:
2343-
state[id_] = new_p
2340+
state[id_] = P((x + deltas[d].x) % W, (y + deltas[d].y) % H)
23442341

23452342
async def view(state, screen):
2343+
offset = P(x=curses.COLS//2 - W//2, y=curses.LINES//2 - H//2)
23462344
while True:
2347-
screen.clear()
2345+
screen.erase()
2346+
curses.textpad.rectangle(screen, offset.y-1, offset.x-1, offset.y+H, offset.x+W)
23482347
for id_, p in state.items():
2349-
screen.addstr(p.y, p.x, str(id_))
2350-
await asyncio.sleep(0.01)
2348+
screen.addstr(offset.y + (p.y - state['*'].y + H//2) % H,
2349+
offset.x + (p.x - state['*'].x + W//2) % W, str(id_))
2350+
await asyncio.sleep(0.005)
23512351

23522352
if __name__ == '__main__':
23532353
curses.wrapper(main)

index.html

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@
5454

5555
<body>
5656
<header>
57-
<aside>January 6, 2022</aside>
57+
<aside>January 19, 2022</aside>
5858
<a href="https://gto76.github.io" rel="author">Jure Šorn</a>
5959
</header>
6060

@@ -1761,10 +1761,10 @@
17611761
&lt;el&gt; = &lt;Queue&gt;.get_nowait() <span class="hljs-comment"># Raises queue.Empty exception if empty.</span>
17621762
</code></pre>
17631763
<div><h2 id="operator"><a href="#operator" name="operator">#</a>Operator</h2><p><strong>Module of functions that provide the functionality of operators.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> operator <span class="hljs-keyword">as</span> op
1764-
&lt;el&gt; = op.add/sub/mul/truediv/floordiv/mod(&lt;el&gt;, &lt;el&gt;) <span class="hljs-comment"># +, -, *, /, //, %</span>
1765-
&lt;int/set&gt; = op.and_/or_/xor(&lt;int/set&gt;, &lt;int/set&gt;) <span class="hljs-comment"># &amp;, |, ^</span>
1766-
&lt;bool&gt; = op.eq/ne/lt/le/gt/ge(&lt;sortable&gt;, &lt;sortable&gt;) <span class="hljs-comment"># ==, !=, &lt;, &lt;=, &gt;, &gt;=</span>
1767-
&lt;func&gt; = op.itemgetter/attrgetter/methodcaller(&lt;int/str&gt;) <span class="hljs-comment"># [&lt;int/str&gt;], .&lt;str&gt;, .&lt;str&gt;()</span>
1764+
&lt;el&gt; = op.add/sub/mul/truediv/floordiv/mod(&lt;el&gt;, &lt;el&gt;) <span class="hljs-comment"># +, -, *, /, //, %</span>
1765+
&lt;int/set&gt; = op.and_/or_/xor(&lt;int/set&gt;, &lt;int/set&gt;) <span class="hljs-comment"># &amp;, |, ^</span>
1766+
&lt;bool&gt; = op.eq/ne/lt/le/gt/ge(&lt;sortable&gt;, &lt;sortable&gt;) <span class="hljs-comment"># ==, !=, &lt;, &lt;=, &gt;, &gt;=</span>
1767+
&lt;func&gt; = op.itemgetter/attrgetter/methodcaller(&lt;el&gt;) <span class="hljs-comment"># [index/key], .&lt;str&gt;, .&lt;str&gt;()</span>
17681768
</code></pre></div>
17691769

17701770

@@ -1876,54 +1876,54 @@
18761876
<li><strong><code class="python hljs"><span class="hljs-string">'asyncio.run(&lt;coroutine&gt;)'</span></code> is the main entry point for asynchronous programs.</strong></li>
18771877
<li><strong>Functions wait(), gather() and as_completed() can be used when multiple coroutines need to be started at the same time.</strong></li>
18781878
<li><strong>Asyncio module also provides its own <a href="#queue">Queue</a>, <a href="#semaphoreeventbarrier">Event</a>, <a href="#lock">Lock</a> and <a href="#semaphore-event-barrier">Semaphore</a> classes.</strong></li>
1879-
</ul><div><h4 id="runsaterminalgamewhereyoucontrolanasteriskthatmustavoidnumbers">Runs a terminal game where you control an asterisk that must avoid numbers:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> asyncio, collections, curses, enum, random
1879+
</ul><div><h4 id="runsaterminalgamewhereyoucontrolanasteriskthatmustavoidnumbers">Runs a terminal game where you control an asterisk that must avoid numbers:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> asyncio, collections, curses, curses.textpad, enum, random
18801880

18811881
P = collections.namedtuple(<span class="hljs-string">'P'</span>, <span class="hljs-string">'x y'</span>) <span class="hljs-comment"># Position</span>
18821882
D = enum.Enum(<span class="hljs-string">'D'</span>, <span class="hljs-string">'n e s w'</span>) <span class="hljs-comment"># Direction</span>
1883+
W, H = <span class="hljs-number">15</span>, <span class="hljs-number">7</span> <span class="hljs-comment"># Width, Height</span>
18831884

18841885
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">(screen)</span>:</span>
18851886
curses.curs_set(<span class="hljs-number">0</span>) <span class="hljs-comment"># Makes cursor invisible.</span>
18861887
screen.nodelay(<span class="hljs-keyword">True</span>) <span class="hljs-comment"># Makes getch() non-blocking.</span>
18871888
asyncio.run(main_coroutine(screen)) <span class="hljs-comment"># Starts running asyncio code.</span>
18881889

18891890
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main_coroutine</span><span class="hljs-params">(screen)</span>:</span>
1890-
state = {<span class="hljs-string">'*'</span>: P(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), **{id_: P(<span class="hljs-number">30</span>, <span class="hljs-number">10</span>) <span class="hljs-keyword">for</span> id_ <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)}}
1891+
state = {<span class="hljs-string">'*'</span>: P(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), **{id_: P(W//<span class="hljs-number">2</span>, H//<span class="hljs-number">2</span>) <span class="hljs-keyword">for</span> id_ <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)}}
18911892
moves = asyncio.Queue()
18921893
coros = (*(random_controller(id_, moves) <span class="hljs-keyword">for</span> id_ <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)),
1893-
human_controller(screen, moves),
1894-
model(moves, state, *screen.getmaxyx()),
1895-
view(state, screen))
1894+
human_controller(screen, moves), model(moves, state), view(state, screen))
18961895
<span class="hljs-keyword">await</span> asyncio.wait(coros, return_when=asyncio.FIRST_COMPLETED)
18971896

18981897
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">random_controller</span><span class="hljs-params">(id_, moves)</span>:</span>
18991898
<span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
19001899
d = random.choice(list(D))
19011900
moves.put_nowait((id_, d))
1902-
<span class="hljs-keyword">await</span> asyncio.sleep(random.random() / <span class="hljs-number">2</span>)
1901+
<span class="hljs-keyword">await</span> asyncio.sleep(random.triangular(<span class="hljs-number">0.01</span>, <span class="hljs-number">0.65</span>))
19031902

19041903
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">human_controller</span><span class="hljs-params">(screen, moves)</span>:</span>
19051904
<span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
19061905
ch = screen.getch()
19071906
key_mappings = {<span class="hljs-number">259</span>: D.n, <span class="hljs-number">261</span>: D.e, <span class="hljs-number">258</span>: D.s, <span class="hljs-number">260</span>: D.w}
19081907
<span class="hljs-keyword">if</span> ch <span class="hljs-keyword">in</span> key_mappings:
19091908
moves.put_nowait((<span class="hljs-string">'*'</span>, key_mappings[ch]))
1910-
<span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">0.01</span>)
1909+
<span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">0.005</span>)
19111910

1912-
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">model</span><span class="hljs-params">(moves, state, height, width)</span>:</span>
1911+
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">model</span><span class="hljs-params">(moves, state)</span>:</span>
19131912
<span class="hljs-keyword">while</span> state[<span class="hljs-string">'*'</span>] <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> {p <span class="hljs-keyword">for</span> id_, p <span class="hljs-keyword">in</span> state.items() <span class="hljs-keyword">if</span> id_ != <span class="hljs-string">'*'</span>}:
19141913
id_, d = <span class="hljs-keyword">await</span> moves.get()
1915-
p = state[id_]
1914+
x, y = state[id_]
19161915
deltas = {D.n: P(<span class="hljs-number">0</span>, <span class="hljs-number">-1</span>), D.e: P(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>), D.s: P(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>), D.w: P(<span class="hljs-number">-1</span>, <span class="hljs-number">0</span>)}
1917-
new_p = P(p.x + deltas[d].x, p.y + deltas[d].y)
1918-
<span class="hljs-keyword">if</span> <span class="hljs-number">0</span> &lt;= new_p.x &lt; width<span class="hljs-number">-1</span> <span class="hljs-keyword">and</span> <span class="hljs-number">0</span> &lt;= new_p.y &lt; height:
1919-
state[id_] = new_p
1916+
state[id_] = P((x + deltas[d].x) % W, (y + deltas[d].y) % H)
19201917

19211918
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">view</span><span class="hljs-params">(state, screen)</span>:</span>
1919+
offset = P(x=curses.COLS//<span class="hljs-number">2</span> - W//<span class="hljs-number">2</span>, y=curses.LINES//<span class="hljs-number">2</span> - H//<span class="hljs-number">2</span>)
19221920
<span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
1923-
screen.clear()
1921+
screen.erase()
1922+
curses.textpad.rectangle(screen, offset.y<span class="hljs-number">-1</span>, offset.x<span class="hljs-number">-1</span>, offset.y+H, offset.x+W)
19241923
<span class="hljs-keyword">for</span> id_, p <span class="hljs-keyword">in</span> state.items():
1925-
screen.addstr(p.y, p.x, str(id_))
1926-
<span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">0.01</span>)
1924+
screen.addstr(offset.y + (p.y - state[<span class="hljs-string">'*'</span>].y + H//<span class="hljs-number">2</span>) % H,
1925+
offset.x + (p.x - state[<span class="hljs-string">'*'</span>].x + W//<span class="hljs-number">2</span>) % W, str(id_))
1926+
<span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">0.005</span>)
19271927

19281928
<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
19291929
curses.wrapper(main)
@@ -2881,7 +2881,7 @@
28812881

28822882

28832883
<footer>
2884-
<aside>January 6, 2022</aside>
2884+
<aside>January 19, 2022</aside>
28852885
<a href="https://gto76.github.io" rel="author">Jure Šorn</a>
28862886
</footer>
28872887

0 commit comments

Comments
 (0)