# Rock–Paper–Scissors mechanics implementation using bit flags and pattern matching
# It also can be easily extended to game modifications with more signs
from flags import Flags
import random
# rules are presented as a set of (winner_flag, loser) pairs
def play(signs, rules, p1_sign, p2_sign):
signs_flags = {}
for i in range(0, len(signs)):
signs_flags[signs[i]] = 1 << i
chosen_flags = signs_flags[p1_sign] | signs_flags[p2_sign]
flags_rules = {}
for sign in signs:
flags_rules[signs_flags[sign]] = 0
for rule in rules:
flags_rules[signs_flags[rule[0]] | signs_flags[rule[1]]] = signs_flags[rule[0]]
winner_flag = flags_rules[chosen_flags]
outcomes = {
signs_flags[p1_sign] : 'player 1 wins: ' + p1_sign + ' beats ' + p2_sign,
signs_flags[p2_sign] : 'player 2 wins: ' + p2_sign + ' beats ' + p1_sign,
0 : 'draw: ' + p1_sign + ' & ' + p2_sign
}
result = outcomes[winner_flag]
print(result)
# simple Rock–Paper–Scissors
signs = ('rock', 'paper', 'scissors')
rules = (('rock', 'scissors'),
('scissors', 'paper'),
('paper', 'rock'))
play(signs, rules, random.choice(signs), random.choice(signs))
# extended Rock-Paper-Scissors-Fire-Water
signs = ('rock', 'paper', 'scissors', 'fire', 'water')
rules = (('rock', 'scissors'),
('scissors', 'paper'),
('paper', 'rock'),
('scissors', 'water'),
('rock', 'water'),
('paper', 'water'),
('fire', 'scissors'),
('fire', 'rock'),
('fire', 'paper'),
('water', 'fire'))
play(signs, rules, random.choice(signs), random.choice(signs))
import random
flatten = lambda l: [item for sublist in l for item in sublist]
class Sign():
sign_names = ()
rules = {}
def init(self, name):
if name in self.sign_names:
self.name = name
else:
raise NotImplementedError("sign is not supported")
def repr(self):
return self.name
@classmethod
def set_sign_names(cls, sign_names):
cls.sign_names = sign_names
#create dict {sign
list of signs it beats]}
@classmethod
def prepare_rules(cls, sign_names, rule_pairs):
result = {sign_name: [] for sign_name in sign_names}
for rp in rule_pairs:
if rp[1] not in result[rp[0]]:
result[rp[0]].append(rp[1])
return result
#assuming that every sign is used in at least one rule
@classmethod
def set_rules(cls, rule_pairs):
sign_names = sorted(set(flatten(rule_pairs)))
cls.set_sign_names(sign_names)
rules = cls.prepare_rules(sign_names, rule_pairs)
cls.rules = rules
@classmethod
def get_random(cls):
return cls(random.choice(cls.sign_names))
#assuming that every two signs are comparable
def compare(self, other):
return other.name in self.rules[self.name]
def eq(self, other):
return (self.name == other.name)
def ne(self, other):
return not(self == other)
def gt(self, other):
return(self.compare(other))
def ge(self, other):
return(self > other or self == other)
def lt(self, other):
return (other.compare(self))
def le(self, other):
return(self < other or self == other)
rule_pairs = (
('rock', 'scissors'),
('scissors', 'paper'),
('paper', 'rock')
)
Sign.set_rules(rule_pairs)
print(Sign.rules)
sign1 = Sign('rock')
sign2 = Sign.get_random()
print(sign2)
print(sign1 > sign2)
~/tmp $ cat > prog.c
#include "stdio.h"
void main() {
printf("sosi pisos");
}
~/tmp $ cc prog.c
~/tmp $ ./a.out
sosi pisos⏎ ~/tmp $
.model tiny
.stack
.data
message db 'sosi pisos','$'
.code
org 100h
main proc near
mov ax,0b800h ; video memory
mov es,ax
mov di,320 ; line 3, column 1
mov si,offset message
mov ax,@data
mov ds,ax
loop_write:
mov al,[si] ; take character
cmp al,'$' ; check end-of-line '$'
je l1out ; jump away
mov es
di],al ; write to Video memory
inc si ; next character
inc di
inc di ; next position on the display
jmp loop_write
l1out:
mov ah,4ch ; terminate dos program
mov al,00
int 21h
endp
end main
.model tiny
.stack
.data
message db 'sosi pisos ','$'
.code
org 100h
main proc near
mov ax,0b800h ; video memory
mov es,ax
mov di,0 ; line 1, column 1
mov ax,@data
mov ds,ax
mov bx,10000 ; 10 000 pisosov na otsos
mov cl,1 ; color
loop_otsos:
mov si,offset message
loop_write:
mov al,[si] ; take character
cmp al,'$' ; check end-of-line '$'
je loop_write_out ; jump away
mov es
di],al ; write char to video memory
inc si ; next character
inc di
mov es
di],cl ; write color to video memory
inc di ; next position on the display
jmp loop_write
loop_write_out:
cmp di,3900
jle have_more_space
mov di,0
have_more_space:
inc cl ; next color
dec bx ; decreas pisos counter
cmp bx,0 ; do we have more pisos'es to suck?
jne loop_otsos
mov ah,4ch ; terminate dos program
mov al,00
int 21h
endp
end main
.model tiny
.stack
.data
message db 'sosi pisos ','$'
.code
org 100h
main proc near
mov ax,0b800h ; video memory
mov es,ax
mov di,0 ; line 1, column 1
mov ax,@data ; data segment
mov ds,ax
mov bx,10000 ; 10 000 pisosov na otsos
mov cl,1 ; color
loop_otsos:
mov si,offset message ; load address of string
loop_write:
lodsb ; take next character
cmp al,'$' ; check end-of-line '$'
je loop_write_out ; jump away
stosb ; write char to video memory
mov al,cl ; take color
stosb ; write color to video memory
jmp loop_write
loop_write_out:
cmp di,3900 ; check if we are near the botton of the screen
jle have_more_space
mov di,0 ; start from the beginning
have_more_space:
inc cl ; next color
dec bx ; decrease pisos counter
cmp bx,0 ; do we have more pisos'es to suck?
jne loop_otsos
mov ah,4ch ; terminate dos program
mov al,00
int 21h
endp
end main
mov ah,4ch ; terminate dos program
mov al,00
int 21h
.model tiny
.stack
.data
message db 'sosi pisos ',0
.code
org 100h
main proc near
mov ax,0b800h ; video memory
mov es,ax
mov di,0 ; line 1, column 1
mov ax,@data ; data segment
mov ds,ax
mov bx,10000 ; 10 000 pisosov na otsos
mov ah,1 ; color
loop_otsos:
mov si,offset message ; load address of string
loop_write:
lodsb ; take next character
test al,al ; check end-of-line '$'
je loop_write_out ; jump away
stosw ; write 2 bytes (char and color) to video memory
jmp loop_write
loop_write_out:
cmp di,3900 ; check if we are near the botton of the screen
jle have_more_space
mov di,0 ; start from the beginning
have_more_space:
inc ah ; next color
dec bx ; decrease pisos counter
cmp bx,0 ; do we have more pisos'es to suck?
jne loop_otsos
mov ah,4ch ; terminate dos program
mov al,00
int 21h
endp
end main
mov bx, 10000
…
dec bx ; decrease pisos counter
cmp bx,0 ; do we have more pisos'es to suck?
jne loop_otsos
mov cx, 10000
….
loop loop_otsos
.model tiny
.code
org 100h
…
main:
mov ax,0b800h ; video memory
mov es,ax
mov di,0 ; line 1, column 1
mov bx,10000 ; 10 000 pisosov na otsos
mov ah,1 ; color
…
ret
message db 'sosi pisos ',0
end main
.model tiny
.code
org 100h
main:
mov ax,0b800h ; video memory
mov es,ax
mov di,0 ; line 1, column 1
mov cx,10000 ; 10 000 pisosov na otsos
mov ah,1 ; color
loop_otsos:
lea si,message ; load address of string
loop_write:
lodsb ; take next character
test al,al ; check end-of-line '$'
je loop_write_out ; jump away
stosw ; write 2 bytes (char and color) to video memory
jmp loop_write
loop_write_out:
cmp di,3900 ; check if we are near the botton of the screen
jle have_more_space
mov di,0 ; start from the beginning
have_more_space:
inc ah ; next color
loop loop_otsos
ret
message db 'sosi pisos ',0
end main
$ cat a.s
.globl _start
_start:
mov $1, %eax
int $0x80
$ as –32 -c -o a.o a.s
$ ld -melf_i386 a.o
$ strip -s a.out
$ ./a.out
$ ls -l a.out
-rwxrwxr-x 1 root root 228 Apr 5 00:29 a.out
$
$ cat a.s
.globl _start
.text
_start:
mov $(message_end-message), %edx
mov $message, %ecx
mov $1, %ebx
mov $4, %eax
int $0x80
jmp _start
message: .ascii "sosi pisos\n"
message_end:
$ as –32 -c -o a.o a.s
$ ld -melf_i386 a.o
$ ./a.out
sosi pisos
sosi pisos
sosi pisos
sosi pisos
sosi pisos
sosi pisos
sosi pisos
sosi pisos
sosi pisos
sosi pisos
…
$ cat a.s
.globl _start
.text
_start:
mov $180, %ecx
pisos:
mov %cl, %al
shr $3, %al
and $1, %al
or $0x30, %al
mov %al, bold
mov %cl, %al
shr $4, %al
and $7, %al
or $0x30, %al
mov %al, bg
mov %cl, %al
and $7, %al
or $0x30, %al
mov %al, fg
push %ecx
mov $(message_end-message), %edx
mov $message, %ecx
mov $1, %ebx
mov $4, %eax
int $0x80
pop %ecx
loop pisos
mov $1, %eax
int $0x80
.data
message:
.ascii "\x1b["
bold: .ascii "0;4"
bg: .ascii "1;3"
fg: .byte '1'
.byte 'm'
.ascii "sosi pisos "
message_end:
/Times-Roman findfont
32 scalefont
setfont
/rnd {
rand 16#7fffffff div
} def
/pisos {
initmatrix
rnd 100 mul cvi 200 add rnd 100 mul cvi 400 add moveto
rnd 360 mul cvi rotate
rnd rnd rnd setrgbcolor
( sosi pisos) show
} def
120 { pisos } repeat
main :: IO ()
main = putStrLn "Sosi pisos"
#include <windows.h>
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
MessageBox(NULL, "Sosi pisos!", "Otsos", 0);
}
#include <stdio.h>
int main(void)
{
unsigned int a;
unsigned int b;
unsigned int p;
unsigned int y;
puts("Расчет православной Пасхи.");
printf("%s", "Введите год: ");
scanf("%u", &y);
// самый православный алгоритм от Гаусса
a = (19 * (y % 19) + 15) % 30;
b = (2 * (y % 4) + 4 * (y % 7) + 6 * a + 6) % 7;
p = 22 + a + b + 13 - 31;
if (p <= 30)
{
printf("%u апреля\n", p);
}
else
{
printf("%u мая\n", p - 30);
}
}
<html>
<head>
<title>PISOS</title>
<link rel="stylesheet" type="text/css" href="pisos.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="screen" class="screen">
</div>
</body>
<script src="pisos.js"></script>
</html>
body {
margin: 0px;
padding: 0px;
}
.screen {
position: absolute;
box-sizing: border-box;
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
border: 0px;
}
"use strict";
var screen = document.getElementById("screen");
var screenW = 1200;
var screenH = 600;
var blockW = 200;
var blockH = 70;
var blockIndex;
function addBlock() {
var newBlockTag = document.createElement("DIV");
var style = '';
var bgColor, fgColor;
newBlockTag.setAttribute("id", "block" + blockIndex);
bgColor = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";
fgColor = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")";
style += 'background-color: ' + bgColor + ';';
style += 'color: ' + fgColor + ';';
style += 'border: 1px solid black; ';
style += 'position: fixed; ';
style += 'left: ' + Math.floor(Math.random()*screenW) + 'px; ';
style += 'top: ' + Math.floor(Math.random()*screenH) + 'px; ';
style += 'width: ' + blockW +'px; ';
style += 'height: ' + blockH + 'px; ';
style += 'text-align: center; ';
style += 'vertical-align: middle; ';
style += 'line-height: ' + blockH + 'px';
newBlockTag.setAttribute("style", style);
screen.appendChild(newBlockTag);
newBlockTag.innerHTML = 'SOSI PISOS';
}
for (blockIndex = 1; blockIndex < 200; blockIndex+
{
addBlock();
}
/Times-Roman findfont
32 scalefont
setfont
/rnd { rand 16#7fffffff div } def
/rndmod { rand exch mod } def
120 {
initmatrix
100 rndmod 200 add 100 rndmod 400 add moveto
360 rndmod rotate
rnd rnd rnd setrgbcolor
( sosi pisos) show
} repeat
<html>
<body>
<svg id="canvas">
</svg>
</body>
<script>
function intRnd(max) {
return Math.floor(Math.random() * max);
}
var maxX = 1350;
var maxY = 655;
var minSize = 10;
var maxSize = 50;
var pisosNaOtsos = 300;
var canvas = document.getElementById("canvas");
canvas.setAttribute("width", maxX + 'px');
canvas.setAttribute("height", maxY + 'px');
var code = '';
var n ;
var x, y, size, colorRect, colorText, angle;
for (n = 0; n < pisosNaOtsos; n+
{
x = intRnd(max
;
y = intRnd(maxY);
size = intRnd(maxSize - minSize) + minSize;
angle = intRnd(120) - 60;
colorRect = 'rgb(' + intRnd(255) + ', ' + intRnd(255) + ',' + intRnd(255) + ')';
colorText = 'rgb(' + intRnd(255) + ', ' + intRnd(255) + ',' + intRnd(255) + ')';
code += '<rect x="' + x + '" y="' + y + '" height="' + size + '" width="' + size * 5 + '" style="stroke
000; fill: ' + colorRect + '" transform="rotate(' + angle + ' ' + x + ',' + y + ')"></rect>';
code += '<text x="' + x + '" y="' + (y + size - 3) + '" font-size="' + (size-1) + '" fill="' + colorText + '" transform="rotate(' + angle + ' ' + x + ',' + y + ')">SOSI PISOS</text>';
}
canvas.innerHTML = code;
</script>
</html>
package com.example.sosipisos;
import java.util.Random;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class PisosActivity extends Activity {
private LinearLayout layout;
private TextView pisosView;
private Random rand;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rand = new Random();
layout = new LinearLayout(this);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, Gravity.CENTER);
pisosView = new TextView(this);
pisosView.setLayoutParams(params);
pisosView.setTextSize(30);
pisosView.setText("Sosi pisos!");
pisosView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
layout.setBackgroundColor(Color.rgb(rand.nextInt(255),
rand.nextInt(255),
rand.nextInt(255)));
Toast.makeText(PisosActivity.this, "Sosi pisos!", Toast.LENGTH_LONG)
.show();
}
});
layout.addView(pisosView);
setContentView(layout);
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sosipisos"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="24" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".PisosActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SosiPisos</string>
</resources>
#include <msp430g2452.h>
int main(void) {
volatile unsigned int i;
WDTCTL = WDTPW | WDTHOLD;
P1DIR = 1;
for (;
{
P1OUT ^= 1;
for (i = 0; i < 0x6000; i+
;
}
}
$ cat pilimage.py
import PIL
import PIL.ImageFont
import PIL.ImageDraw
PIL.Image.init()
txt = 'SOSI PISOS'
size=16
font = PIL.ImageFont.truetype('arial.ttf', size)
tsx, tsy = font.getsize(txt)
tsy=size
im = PIL.Image.new('RGBA', (tsx, tsy))
draw = PIL.ImageDraw.Draw(im)
draw.text((0, 0), txt, font=font)
z=im.tobytes()[::4]
z=[ord(x) > 0x80 for x in z]
z=[['0', '1'][x] for x in z]
z=[z[i*tsx
i+1)*tsx] for i in range(tsy)]
for x in z:
print ''.join(x)
$ python pilimage.py
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00011111000000011110000000111110000100000011111110000100001111100000001111000000011111000
00100000100001100001100001000001000100000010000001100100010000010000110000110000100000100
01000000010001000000100010000000100100000010000000100100100000001000100000010001000000010
01000000000010000000010010000000000100000010000000100100100000000001000000001001000000000
00110000000010000000010001100000000100000010000000000100011000000001000000001000110000000
00001111000010000000010000011110000100000011111110000100000111100001000000001000001111000
00000000100010000000010000000001000100000010000000000100000000010001000000001000000000100
00000000010010000000010000000000100100000010000000000100000000001001000000001000000000010
01000000010001000000100010000000100100000010000000000100100000001000100000010001000000010
00100000100001100001100001000001000100000010000000000100010000010000110000110000100000100
00011111000000011110000000111110000100000010000000000100001111100000001111000000011111000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
$ cat pilimage2.py
rows=[
'00011111000000011110000000111110000100000011111110000100001111100000001111000000011111000',
'00100000100001100001100001000001000100000010000001100100010000010000110000110000100000100',
'01000000010001000000100010000000100100000010000000100100100000001000100000010001000000010',
'01000000000010000000010010000000000100000010000000100100100000000001000000001001000000000',
'00110000000010000000010001100000000100000010000000000100011000000001000000001000110000000',
'00001111000010000000010000011110000100000011111110000100000111100001000000001000001111000',
'00000000100010000000010000000001000100000010000000000100000000010001000000001000000000100',
'00000000010010000000010000000000100100000010000000000100000000001001000000001000000000010',
'01000000010001000000100010000000100100000010000000000100100000001000100000010001000000010',
'00100000100001100001100001000001000100000010000000000100010000010000110000110000100000100',
'00011111000000011110000000111110000100000010000000000100001111100000001111000000011111000',
]
xs=len(rows[0])
ys=len(rows)
for x in range(xs):
w=''.join([rows[y][x] for y in range(ys)])
w=eval('0b'+w)
print ' 0x%04x,' % w
$ python pilimage2.py >> pisos.c
#include <msp430g2452.h>
const unsigned short int pisos[] = {
0x0000, 0x0184, 0x0242, 0x0441, 0x0421, 0x0421, 0x0421, 0x0421, 0x0212,
0x010c, 0x0000, 0x0000, 0x00f8, 0x0306, 0x0202, 0x0401, 0x0401, 0x0401,
0x0401, 0x0202, 0x0306, 0x00f8, 0x0000, 0x0000, 0x0184, 0x0242, 0x0441,
0x0421, 0x0421, 0x0421, 0x0421, 0x0212, 0x010c, 0x0000, 0x0000, 0x07ff,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x07ff, 0x0420, 0x0420,
0x0420, 0x0420, 0x0420, 0x0420, 0x0200, 0x0380, 0x0000, 0x0000, 0x07ff,
0x0000, 0x0000, 0x0184, 0x0242, 0x0441, 0x0421, 0x0421, 0x0421, 0x0421,
0x0212, 0x010c, 0x0000, 0x0000, 0x00f8, 0x0306, 0x0202, 0x0401, 0x0401,
0x0401, 0x0401, 0x0202, 0x0306, 0x00f8, 0x0000, 0x0000, 0x0184, 0x0242,
0x0441, 0x0421, 0x0421, 0x0421, 0x0421, 0x0212, 0x010c, 0x0000,
};
int main(void) {
volatile unsigned int i, j;
WDTCTL = WDTPW | WDTHOLD;
P1DIR = 0xff;
P2DIR = 0x7;
for (j
;;j+
{
j %= sizeof(pisos)/sizeof(*pisos);
P1OUT = pisos[j] & 0xff;
P2OUT = (pisos[j] >> 8) & 0x7;
for (i = 0; i < 0x60; i+
;
}
}
P2OUT = 0x18 | ((w >> 8) & 0x7); // turn off both low keys, set P2 portion of high keys
P1OUT = w & 0xff; // set P1 portion of high keys
P2OUT &= redgreen ? ~0x10 : ~0x8; // set low key
keys(0, 1);
keys(0, 0);
keys(sosi[x], 1);
keys(pisos[x], 0);
$ msp430-gcc -O99 -Wall -mmcu=msp430g2452 pisos.c
$ sudo mspdebug rf2500 'prog a.out'
MSPDebug version 0.22 - debugging tool for MSP430 MCUs
Copyright (C) 2009-2013 Daniel Beer <[email protected]>
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Trying to open interface 1 on 068
Initializing FET…
FET protocol version is 30394216
Set Vcc: 3000 mV
Configured for Spy-Bi-Wire
Device ID: 0x2553
Code start address: 0xc000
Code size : 16384 byte = 16 kb
RAM start address: 0x200
RAM end address: 0x3ff
RAM size : 512 byte = 0 kb
Device: MSP430G2553/G2403
Number of breakpoints: 2
fet: FET returned NAK
warning: device does not support power profiling
Chip ID data: 25 53
Erasing…
Programming…
Writing 318 bytes at e000 [section: .text]…
Writing 192 bytes at e13e [section: .rodata]…
Writing 32 bytes at ffe0 [section: .vectors]…
Done, 542 bytes total
.post-table textarea {
max-width: 1000px;
}
#!/bin/bash
# usage: alarm [time] [soundfile]
# script sleeps $time minutes, then plays $soundfile
PLAYER="mplayer -loop 0 -really-quiet"
WAIT=30
SOUND='/usr/share/sounds/freedesktop/stereo/phone-incoming-call.oga'
if [ ! -z "$1" ]; then WAIT=$1; fi
if [ ! -z "$2" ]; then SOUND=$2; fi
if [ ! -f "$SOUND" ]; then echo 'Error: alarm sound not found!'; exit 1; fi
echo -n 'Now ——- '
date +'%H:%M'
echo 'Sleep —– '$WAIT' minutes'
echo -n 'Wake up — '
date -d "now $WAIT minutes" +'%H:%M'
echo 'Play —— '$SOUND
sleep $WAIT'm'
$PLAYER "$SOUND"
echo 'mplayer -loop 0 -really-quiet /usr/share/sounds/freedesktop/stereo/phone-incoming-call.oga' | at 8:00
var s = {f=10, lolka="yes"};
function n() {
}
Советуем какой первый ЯП учить.
Поясняем за парадигмы программирования.
Обсуждаем ООП.
Вскользь упоминаем ML.
Сыплем баззвордами.
Вангуем кто кого убьет.