カテゴリー
C

独習C#第3版 P276 Setクラスを作成する

C#のこーどならシンタックスハイライターが効きますか?

/* 
   例7-1 
 
   char型データ用のSetクラス
*/ 
using System;  
  
class Set {     
  char[] members; // この配列がセットの値を保持する

  // 実質的に読み取り専用の、自動実装する Length プロパティ 
  public int Length { get; private set; }

  // ヌルのセット(配列の実体がないセット)を作る
  public Set() {  
    Length = 0; 
  }

  // 指定されたサイズの領域を持つ空のセットを作る
  public Set(int size) {     
    members = new char[size]; // セットのためにメモリを確保
    Length = 0; // 実質的な要素はない
  }     
   
  // セットから別のセットを作る
  public Set(Set s) {     
    members = new char[s.Length]; // セットのためにメモリ確保    
    for(int i=0; i < s.Length; i++) members[i] = s[i];
    Length = s.Length; // 実質的な要素の数 
  }     
 
  // 読み取り専用のインデクサ
  public char this[int idx]{  
    get {  
      if(idx >= 0 & idx < Length) return members[idx];
      else return (char)0; 
    }  
  }  
 
  /* 引数で指定されたデータがセットの中に
     存在するかチェックする
     あればそのインデックスを返し、なければ-1を返す */ 
  int find(char ch) {  
    int i; 
     
    for(i=0; i < Length; i++)
      if(members[i] == ch) return i; 
 
    return -1; 
  }

  // ユニークな要素をセットに追加する
  public static Set operator +(Set ob, char ch)
  {

    // もし、セットの中にchと同じものが既に存在していた場合は、
    // 元のセットのコピーを返す
    if (ob.find(ch) != -1)
    {

      // 元のセットのコピーを返す
      return new Set(ob);

    } else { // 新しい要素を含む新しいセットを返す

      // 元のセットよりも、要素1つ分だけ大きいセットを新規作成する
      Set newset = new Set(ob.Length + 1);

      // 新しいセットに要素をコピーする 
      for (int i = 0; i < ob.Length; i++)
        newset.members[i] = ob.members[i];

      // Length プロパティを設定する
      newset.Length = ob.Length + 1;

      // 新しいセットに新しい要素を追加する
      newset.members[newset.Length - 1] = ch;

      return newset; // 新しいセットを返す
    }
  } 
 
  // セットから要素を取り除く
  public static Set operator -(Set ob, char ch) {   
    Set newset = new Set();
    int i = ob.find(ch); // もし見つからなければ、変数iは-1になる
 
    // 残りの要素をコピーする
    for(int j=0; j < ob.Length; j++)
      if(j != i) newset = newset + ob.members[j]; 
 
    return newset; 
  }     
 
  // 和集合
  public static Set operator +(Set ob1, Set ob2) {
    Set newset = new Set(ob1); // 1番目のセットをコピーする
 
    // 2番目のセットの要素を追加する
    for(int i=0; i < ob2.Length; i++)
        newset = newset + ob2[i]; 
 
    return newset; // 更新されたセットを返す
  }  
 
  // 差集合
  public static Set operator -(Set ob1, Set ob2) {
    Set newset = new Set(ob1); // 1番目のセットをコピーする 
 
    // 2番目のセットの要素を1番目のセットから引く 
    for(int i=0; i < ob2.Length; i++)
        newset = newset - ob2[i]; 
 
    return newset; // 更新されたセットを返す
  }  
}     
  
// セットクラスの使用例
class SetDemo {     
  static void Main() {     
    // ヌルのセットを作成する
    Set s1 = new Set();    
    Set s2 = new Set(); 
    Set s3 = new Set(); 
  
    s1 = s1 + 'A'; 
    s1 = s1 + 'B'; 
    s1 = s1 + 'C'; 
 
    Console.Write("s1 after adding A B C: ");  
    for(int i=0; i<s1.Length; i++)
      Console.Write(s1[i] + " ");    
    Console.WriteLine(); 
 
    s1 = s1 - 'B'; 
    Console.Write("s1 after s1 = s1 - 'B': ");  
    for(int i=0; i<s1.Length; i++)
      Console.Write(s1[i] + " ");    
    Console.WriteLine(); 
 
    s1 = s1 - 'A'; 
    Console.Write("s1 after s1 = s1 - 'A': ");  
    for(int i=0; i<s1.Length; i++)
      Console.Write(s1[i] + " ");    
    Console.WriteLine(); 
 
    s1 = s1 - 'C'; 
    Console.Write("s1 after s1 = s1 - 'C': ");  
    for(int i=0; i<s1.Length; i++)   
      Console.Write(s1[i] + " ");    
    Console.WriteLine("\n"); 
 
    s1 = s1 + 'A'; 
    s1 = s1 + 'B'; 
    s1 = s1 + 'C'; 
    Console.Write("s1 after adding A B C: ");  
    for(int i=0; i<s1.Length; i++)   
      Console.Write(s1[i] + " ");    
    Console.WriteLine(); 
 
    s2 = s2 + 'A'; 
    s2 = s2 + 'X'; 
    s2 = s2 + 'W'; 
 
    Console.Write("s2 after adding A X W: ");  
    for(int i=0; i<s2.Length; i++)
      Console.Write(s2[i] + " ");    
    Console.WriteLine(); 
 
    s3 = s1 + s2; 
    Console.Write("s3 after s3 = s1 + s2: ");  
    for(int i=0; i<s3.Length; i++)
      Console.Write(s3[i] + " ");    
    Console.WriteLine(); 
 
    s3 = s3 - s1; 
    Console.Write("s3 after s3 - s1: ");  
    for(int i=0; i<s3.Length; i++)
      Console.Write(s3[i] + " ");    
    Console.WriteLine("\n"); 
 
    s2 = s2 - s2;  // s2のクリア
    s2 = s2 + 'C'; // 逆の順番にABCを加える
    s2 = s2 + 'B'; 
    s2 = s2 + 'A'; 
 
    Console.Write("s1 is now: ");  
    for(int i=0; i<s1.Length; i++)
      Console.Write(s1[i] + " ");    
    Console.WriteLine(); 
 
    Console.Write("s2 is now: ");  
    for(int i=0; i<s2.Length; i++)
      Console.Write(s2[i] + " ");    
    Console.WriteLine(); 
 
    Console.Write("s3 is now: ");  
    for(int i=0; i<s3.Length; i++)
      Console.Write(s3[i] + " ");    
    Console.WriteLine(); 
   }     
}
カテゴリー
C

C#コードを張り付ける、その2

using System;
namespace Chapter01All
{
    class IntNijigenAry
    {
        static void Main()
        {
            int r = 5; int c = 10;
            int[,] ary = new int[5, 10];
            for(int i = 0; i < r; i++)
            {
                for(int j = 0; j < c; j++)
                {
                    ary[i, j] = i * 10 + j;
                }
            }
            for (int i = 0; i < r; i++)
            {
                for (int j = 0; j < c; j++)
                {
                    Console.Write(ary[i, j] + " ");
                }
                Console.WriteLine();
            }
        }
    }
}

中々思ったようには行かないもののようです。パソコン全てそう、と言ってしまえばそれまでですが。((+_+))

カテゴリー
C

C#コードを張り付ける

using System;
namespace Chapter01All
{   class NigenAry
    {
        int[,] ary;
        public NigenAry(int r, int c)
        {
            ary = new int[r, c];
        }
        public int this[int indexr, int indexc]
        {
            get
            {
                return ary[indexr, indexc];
            }
            set
            {
                ary[indexr, indexc] = value;
            }
        }
    }
    class NigenAryIndex
    {
        static void Main()
        {
            int r = 5; int c = 10;
            NigenAry obj = new NigenAry(r, c);
            for(int i=0; i<r * c; i++)
            {
                obj[i / c, i % c] = i;
            }
            for (int i = 0; i < r * c; i++)
            {
                if (i % c == 0)
                    Console.WriteLine();
                Console.Write(obj[i / c, i % c] + " ");
            }
            Console.WriteLine();
        }
    }
}
カテゴリー
Rubyスクリプト

filefind3.rb

require 'fileutils'
# ファイルの情報を表示 netから拾いました。
def stat(path)
s = File::Stat.new(path)
begin
puts " : #{s.birthtime} (ファイル作成日時)"
rescue NotImplementedError => e
puts e.inspect
end
puts " : #{s.mtime} (最終更新日時 modify time)"
puts " : #{s.ctime} (最終状態変更日時 change time)"
puts " : #{s.atime} (最終アクセス日時 access time)"
end

def getallfiles(filename,desc)
print filename,"を探します。","\n"
Dir.glob('**/*') do |item|
ary = item.split("/")

if ary[1] == nil
#.txtがprintされるのを防ぐ
if !ary[0].include?(".")
print ary[0],"\n"
end
elsif File.fnmatch?(filename,ary[1])
print " /"
printf("%-20s\n", ary[1])
stat(item)if desc == true #--descの指定があるとき
end
end
end

begin
if ARGV[0]==nil
print ("[USEAGE]findfile [--name] name [--desc]")
exit(1)
end
op = ARGV
desc = op[2] == "--desc" ? true : false
if op[0] == "--name"
filename = op[1]
#ファイル名で検索します。正規表現も使える
getallfiles(filename,desc)
else
print("--name filename.ext --descと指定します。")
#上以外は無しです
1 / 0
end

rescue
print("エラーが起きました。")
exit(1)
else
print("処理を終わります。")
end
カテゴリー
Python

mine_sweeper.py

[python]
""" mine_sweeper.py – Copyright 2016 Kenichiro Tanaka """
import sys
from math import floor
from random import randint
import pygame
from pygame.locals import QUIT, MOUSEBUTTONDOWN

WIDTH = 20
HEIGHT = 15
SIZE = 50
NUM_OF_BOMBS = 20
EMPTY = 0
BOMB = 1
OPENED = 2
OPEN_COUNT = 0
CHECKED = [[0 for _ in range(WIDTH)] for _ in range(HEIGHT)]

pygame.init()
SURFACE = pygame.display.set_mode([WIDTH*SIZE, HEIGHT*SIZE])
FPSCLOCK = pygame.time.Clock()

def num_of_bomb(field, x_pos, y_pos):
""" 周囲にある爆弾の数を返す """
count = 0
for yoffset in range(-1, 2):
for xoffset in range(-1, 2):
xpos, ypos = (x_pos + xoffset, y_pos + yoffset)
if 0 <= xpos < WIDTH and 0 <= ypos < HEIGHT and \
field[ypos][xpos] == BOMB:
count += 1
return count

def open_tile(field, x_pos, y_pos):
""" タイルをオープン """
global OPEN_COUNT
if CHECKED[y_pos][x_pos]: # 既にチェック済みのタイル
return

CHECKED[y_pos][x_pos] = True

for yoffset in range(-1, 2):
for xoffset in range(-1, 2):
xpos, ypos = (x_pos + xoffset, y_pos + yoffset)
if 0 <= xpos < WIDTH and 0 <= ypos < HEIGHT and \
field[ypos][xpos] == EMPTY:
field[ypos][xpos] = OPENED
OPEN_COUNT += 1
count = num_of_bomb(field, xpos, ypos)
if count == 0 and \
not (xpos == x_pos and ypos == y_pos):
open_tile(field, xpos, ypos)

def main():
""" メインルーチン """
smallfont = pygame.font.SysFont(None, 36)
largefont = pygame.font.SysFont(None, 72)
message_clear = largefont.render("!!CLEARED!!",
True, (0, 255, 225))
message_over = largefont.render("GAME OVER!!",
True, (0, 255, 225))
message_rect = message_clear.get_rect()
message_rect.center = (WIDTH*SIZE/2, HEIGHT*SIZE/2)
game_over = False

field = [[EMPTY for xpos in range(WIDTH)]
for ypos in range(HEIGHT)]

# 爆弾を設置
count = 0
while count < NUM_OF_BOMBS:
xpos, ypos = randint(0, WIDTH-1), randint(0, HEIGHT-1)
if field[ypos][xpos] == EMPTY:
field[ypos][xpos] = BOMB
count += 1

while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN and \
event.button == 1:
xpos, ypos = floor(event.pos[0] / SIZE),\
floor(event.pos[1] / SIZE)
if field[ypos][xpos] == BOMB:
game_over = True
else:
open_tile(field, xpos, ypos)

# 描画
SURFACE.fill((0, 0, 0))
for ypos in range(HEIGHT):
for xpos in range(WIDTH):
tile = field[ypos][xpos]
rect = (xpos*SIZE, ypos*SIZE, SIZE, SIZE)

if tile == EMPTY or tile == BOMB:
pygame.draw.rect(SURFACE,
(192, 192, 192), rect)
if game_over and tile == BOMB:
pygame.draw.ellipse(SURFACE,
(225, 225, 0), rect)
elif tile == OPENED:
count = num_of_bomb(field, xpos, ypos)
if count > 0:
num_image = smallfont.render(
"{}".format(count), True, (255, 255, 0))
SURFACE.blit(num_image,
(xpos*SIZE+10, ypos*SIZE+10))

# 線の描画
for index in range(0, WIDTH*SIZE, SIZE):
pygame.draw.line(SURFACE, (96, 96, 96),
(index, 0), (index, HEIGHT*SIZE))
for index in range(0, HEIGHT*SIZE, SIZE):
pygame.draw.line(SURFACE, (96, 96, 96),
(0, index), (WIDTH*SIZE, index))

# メッセージの描画
if OPEN_COUNT == WIDTH*HEIGHT – NUM_OF_BOMBS:
SURFACE.blit(message_clear, message_rect.topleft)
elif game_over:
SURFACE.blit(message_over, message_rect.topleft)

pygame.display.update()
FPSCLOCK.tick(15)

if __name__ == ‘__main__’:
main()
[/python]

カテゴリー
Python

cave.py

[python]
""" cave – Copyright 2016 Kenichiro Tanaka """
import sys
from random import randint
import pygame
from pygame.locals import QUIT, Rect, KEYDOWN, K_SPACE

pygame.init()
pygame.key.set_repeat(5, 5)
SURFACE = pygame.display.set_mode((800, 600))
FPSCLOCK = pygame.time.Clock()

def main():
""" メインルーチン """
walls = 80
ship_y = 250
velocity = 0
score = 0
slope = randint(1, 6)
sysfont = pygame.font.SysFont(None, 36)
ship_image = pygame.image.load("ship.png")
bang_image = pygame.image.load("bang.png")
holes = []
for xpos in range(walls):
holes.append(Rect(xpos * 10, 100, 10, 400))
game_over = False

while True:
is_space_down = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_SPACE:
is_space_down = True

# 自機を移動
if not game_over:
score += 10
velocity += -3 if is_space_down else 3
ship_y += velocity

# 洞窟をスクロール
edge = holes[-1].copy()
test = edge.move(0, slope)
if test.top <= 0 or test.bottom >= 600:
slope = randint(1, 6) * (-1 if slope > 0 else 1)
edge.inflate_ip(0, -20)
edge.move_ip(10, slope)
holes.append(edge)
del holes[0]
holes = [x.move(-10, 0) for x in holes]

# 衝突 ?
if holes[0].top > ship_y or \
holes[0].bottom < ship_y + 80:
game_over = True

# 描画
SURFACE.fill((0, 255, 0))
for hole in holes:
pygame.draw.rect(SURFACE, (0, 0, 0), hole)
SURFACE.blit(ship_image, (0, ship_y))
score_image = sysfont.render("score is {}".format(score),
True, (0, 0, 225))
SURFACE.blit(score_image, (600, 20))

if game_over:
SURFACE.blit(bang_image, (0, ship_y-40))

pygame.display.update()
FPSCLOCK.tick(15)

if __name__ == ‘__main__’:
main()
[/python]

カテゴリー
Python

draw_image_onkeydown.py

 

[python]
""" draw_image_onkeydown.py """
import sys
import pygame
from pygame.locals import QUIT, KEYDOWN, K_LEFT, K_RIGHT, K_UP, K_DOWN

pygame.init()
pygame.key.set_repeat(5, 5)
SURFACE = pygame.display.set_mode((400, 300))
FPSCLOCK = pygame.time.Clock()

def main():
""" main routine """
logo = pygame.image.load("pythonlogo.jpg")
pos = [200, 150]
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_LEFT:
pos[0] -= 5
elif event.key == K_RIGHT:
pos[0] += 5
elif event.key == K_UP:
pos[1] -= 5
elif event.key == K_DOWN:
pos[1] += 5

pos[0] = pos[0] % 400
pos[1] = pos[1] % 300

SURFACE.fill((225, 225, 225))

rect = logo.get_rect()
rect.center = pos
SURFACE.blit(logo, rect)

pygame.display.update()
FPSCLOCK.tick(30)

if __name__ == ‘__main__’:
main()
[/python]

カテゴリー
Python

Eclipse でのpython(Anaconda) + pygame の状態

[python]

""" draw_rect1.py """
import sys
import pygame
from pygame.locals import Rect
from pygame.locals import QUIT

pygame.init()
SURFACE = pygame.display.set_mode((400, 300))
FPSCLOCK = pygame.time.Clock()

def main():
""" main routine """

while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()

SURFACE.fill((255, 255, 255))

# 赤:矩形(塗りつぶし)
pygame.draw.rect(SURFACE, (255, 0, 0), (10, 20, 100, 50))

# 赤:矩形(太さ3)
pygame.draw.rect(SURFACE, (255, 0, 0), (150, 10, 100, 30), 3)

# 緑:矩形
pygame.draw.rect(SURFACE, (0, 255, 0), ((100, 80), (80, 50)))

# 青:矩形、Rectオブジェクト
rect0 = Rect(200, 60, 140, 80)
pygame.draw.rect(SURFACE, (0, 0, 255), rect0)

# 黄:矩形、Rectオブジェクト
rect1 = Rect((30, 160), (100, 50))
pygame.draw.rect(SURFACE, (255, 255, 0), rect1)

pygame.display.update()
FPSCLOCK.tick(3)

if __name__ == ‘__main__’:
main()

[/python]

カテゴリー
Python

draw_image4.py

[python]
#""" draw_image4.py """
import sys
import pygame
from pygame.locals import QUIT

pygame.init()
SURFACE = pygame.display.set_mode((400, 300))
FPSCLOCK = pygame.time.Clock()

def main():
""" main routine """
logo = pygame.image.load("pythonlogo.jpg")
theta = 0

while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()

theta += 1

SURFACE.fill((225, 225, 225))

# ロゴを回転し、中心が(200, 150)の位置にロゴを描画
new_logo = pygame.transform.rotate(logo, theta)
rect = new_logo.get_rect()
rect.center = (200, 150)
SURFACE.blit(new_logo, rect)

pygame.display.update()
FPSCLOCK.tick(30)

if __name__ == ‘__main__’:
main()
[/python]

どうも少しおかしいようです。最初と最後にpreが付いてますが、これはいらないです。

カテゴリー
未分類

pythonでSyntaxhighlighter使ってみました。

[python]
# -*- coding: utf-8 -*-
import vpython as vs
import time

def main():
# シーンの範囲
vs.scene.range = 5

# 箱のサイズ
l, h, w = 2, 2, 2

# 箱の中心位置
x, y, z = 0, 0, 0

# 箱の定義
box = vs.box(color=vs.vector(255, 255, 255),
pos=vs.vector(x, y, z),
size=vs.vector(l, h, w),
axis=vs.vector(l, 0, 0)
)
# 回転角[deg]
deg = 0

while True:
# 360[deg]になったら初期化
if deg == 360:
deg = 0
# フレームレート
vs.rate(10)
# 軸を動かして回転
box.axis = l * vs.vector(vs.sin(deg), 0, vs.cos(deg))
# 0.1[degずつ動かす]
deg += 0.1

if __name__ == ‘__main__’:
main()
[/python]

inserted by FC2 system