Skip to main content

Sponsors

Software

Reversi in Java: The first presentable board game

Posted in

I believe you'll not want to use command interface to play board game Reversi. Try this out, Reversi in Java xversi-java-v0.6b under GPL. The package includes both source codes and .class files. To play, simply extract files in the package and open the test.html using appletviewer or a browser with Java support. The implementation is lightweight, all the drawings are generated real-time, without using any picture files.

This had been further extended to use RMI (remote method invocation) to support parallel evaluation. However, it's troublesome to run and requires some security setting of the Java applet to be able to access host file. If you think it's interesting, stay tuned. :)

REVERSI: Yet another program that I had put in storeroom for a long time

Posted in

I started with writing a Reversi board game in Java. Then I ported it to C++, called xversi-c-v0.1 which is under GPL and hope that it will run much faster. The implementation ideas are simple:

  • Generate all possible moves.
  • For each of the moves generated above, evaluate and keep the best move.
  • The real question is, how do we evaluate each of the possible moves?
  • Just use your imagination, to determine whether a move is good, just find out what are all the next possible moves? what are all the next next possible moves? ...... eventually, the board will be filled up with all the possible moves :)
  • Practically, we cannot imagine too many moves. At one point, we will want to use some criteria to determine whether a move is good. I have use some simple heuristics to calculate a score for each move.
    • Count number of pieces. When game started, we dont want to have many pieces. But as game closer to end game, we want more pieces.
    • Count mobility, that's the number of moves that each player has. Having more moves, probably means having more controlling power over opponent.
    • Count the number of corners obtained.
  • As the game closer to the end, number of possible moves are limited. Thus, when game is near end, I set it to compute all the possible moves till the end. At the end, evaluation is simple, simply count the number of pieces each player has.
  • For more information about evaluation, search for Game tree generation with alpha-beta prunning.

Phew..... no point having too many explainations. :) Read the codes if you care. :) I hope it's readable enough. :p

My first open source program: Linux Utility

Posted in

Have been writing many toy programs which end up in the recycle bin, and then flush to no place. I hope from now onwards, my programs can have longer livespan. Let me start with some bash scripts, xman utility under GPL:

  • xman_rm: Move given files into the folder ".deleted". So that I can recover the files in the future if we need to.
  • xman_list_rb: List files deleted using xman_rm.
  • xman_clean_rb: Delete all files found by xman_list_rb permanently.
  • xman_create_pdfdb: Process given folder recursively for .pdf files. Convert all .pdf files into .txt and store in database folder.
  • xman_lowercase: Convert all given file names to lowercase.
  • xman_uppercase: Convert all given file names to uppercase.
  • xman_chext: Convert file extension to another extension.
  • xman_tolower_filter: Convert strings from stdin to lowercase.
  • xman_toupper_filter: Convert strings from stdin to uppercase.

Hope these scripts may help you for your work. If not, you may still learn some bash scripts from these. :) You may also suggest useful scripts for routine work.

Python

If you can learn a language by example, this is a place for you to learn the core of python programming. However, some statements are mis-indented. But indentation should not be a problem to you if you are familiar with structured programming.

# Getting started.
>>> print "hello world"
hello world

xman@sai python $ cat hello.py
#!/usr/bin/python
# hello world comment
print "hello world"

>>> execfile("hello.py")
hello world

>>> import sys
>>> sys.exit()
xman@sai python $

>>> while x <= y:
... print x,y
... x=x+1
>>> x = 0 ; y = 1 ; z = 2
>>> print "%4d %0.2f" % (x,y)
100 5.00

# Conditional.
>>> if x < z =" x"> y:
... z = y
... elif x == y:
... pass
... else:
... raise RuntimeError, "Unknown"
...

# Keywords: and assert break class continue def del elif else except exec finally for from global
if import in is lambda not or pass print raise return try while
# Operators: + - * ** / % << >> < > <= >= == != <> & | ^ ~ not and or

# File.
>>> f = open("hello.py")
>>> line = f.readline()
>>> while line:
... print line
... line = f.readline()
...
>>> f.close()

# File methods
f.read([n])
f.readline()
f.readlines()
f.write(s) # Write string s.
f.writelines(l) # Write all strings in list l.
f.close()
f.tell()
f.seek(offset [,where])
f.isatty()
f.flush()
f.truncate([size])
f.fileno()
f.readinto(buffer, nbytes)

# String & Char
>>> a = "hello world"
>>> print a[4]
o
>>> a = 'hello world'
>>> b = "hello world"
>>> c = """hello world"""
>>> d = """hello
... world
... """

>>> print d
hello
world

# Slice
>>> x = a[0:5]
>>> y = a[1:]
>>> z = a[:4]

# String
>>> a = "hello" ; b = "world"
>>> c = a + b ; print c
helloworld

# List
>>> data = ["a", "b", "c"]
>>> data.append("d")
>>> data = data + ['e','f']

# Reference count
>>> a = [1,3,5]
>>> b = a
>>> a, b
([1, 3, 5], [1, 3, 5])
>>> b[1] = 100
>>> a, b
([1, 100, 5], [1, 100, 5])

# Nested list.
>>> data = ['a' , ['b','c' ]]
>>> print data[1][1]
c

# Map.
>>> import string
>>> import sys
>>> f = open("data.dat")
>>> svalues = f.readlines()
>>> f.close()
>>> fvalues = map(string.atof, svalues)
>>> print svalues
['0.1\n', '0.4\n', '0.2\n', '0.3\n', '0.24\n']
>>> print fvalues
[0.10000000000000001, 0.40000000000000002, 0.20000000000000001, 0.29999999999999999, 0.2399999999
9999999]
>>> print min(fvalues)
0.1
>>> print max(fvalues)
0.4

# Tuple (Create once, no modifications allowed)
>>> a = (1,3)
>>> b = (2,4)
>>> c = (4,)
>>> print a,b,c
(1, 3) (2, 4) (4,)
>>> print a[0], a[1]

# Range.
>>> print range(3)
[0, 1, 2]
>>> print range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print range(1,10,2)
[1, 3, 5, 7, 9]
>>> for i in range(1,10,2):
... print i
...
1
3
5
7
9
a = xrange(0,10000000) # Recompute to save memory.

# Dictionary (associative array).
>>> a = {
... "a" : "va" ,
... "b" : "vb"
... }
>>> print a["a"], a["b"]
>>> a.keys()
>>> a.has_key("a")
>>> del a["a"]

# Function. Local scope by default.
>>> def swap(a,b,c=0):
... "SWAP: Documentation string"
... global msg
... if c != 0 : print msg
... return (b,a)
...
>>> a,b=swap(a,b)
>>> a,b=swap(a,b,1)

# Variable-length argument, keyword argument.
# args: Additional variables in a tuple.
# kw: Additional keyword arguments in a table.
>>> def func(x, *args, **kw):

# Class.
# def: Define a method.
# First argument of a method: the object.
>>> class stack:
... "Stack data structure"
... name = "Stack"
... def __init__(self):
... self.stack = []
... def push(self,object):
... "Append object to the end"
... self.stack.append(object)
... def pop(self):
... "Remove an object from the end and return it"
... return self.stack.pop()
... def length(self):
... "Number of objects in stack"
... return len(self.stack)
>>> s = stack()
>>> s.push("data1")
>>> s.push("data2")
>>> x = s.pop()

# Inheritance.
>>> class C(A,B):
# Encapsulation.
>>> class C:
... __x = 500

# Class relationship
>>> isinstance(c,C)
>>> issubclass(C,A)

# Exception.
>>> try:
... f = open("data.txt")
... except IOError, e:
... print "My error:" , e
...
My error: [Errno 2] No such file or directory: 'data.txt'

# Module.
# Import the module hello.py.
>>> import hello
>>> import string
>>> dir(string) # List contents of module string.

# Syntax.
# Multi-line.
>>> c = a + \
... b

# Consistent indentation.
# Codes in the same block must uses the same indentation.

# Documentation strings.
>>> def func(n):
... "Documentation string"
... return n

# Type & ID
>>> type(a)

>>> id(a)
5280552
>>> a is b
>>> a is not b
>>> type(a) == type(b)

# Copy.
>>> import copy
>>> b = [1,2,3]
>>> a = copy.deepcopy(b)

# List:
list(s)
s.append(x)
s.extend(x)
s.count(x)
s.index(x)
s.insert(i,x)
s.pop([i])
s.remove(x)
s.reverse()
s.sort([cmpfunc])

# Mapping types:
len(m)
m[k]
del m[k]
m.clear()
m.copy()
m.has_key(k)
m.items()
m.keys()
m.update(b)
m.values()
m.get(k,[,f]) # Return m[k] if found; otherwise return f.

# Unbound method object, bound method object.
# C is a class, c is an instance of class C.
>>> c.work()
hello world
>>> C.work(c)
hello world

# Functional programming
>>> a = lambda x,y : x+y
>>> print a(2,5)

# map(), reduce(), filter().
# Apply func to elements in s.
>>> t = map(func,s)
# Reduce a using sum function.
>>> b = reduce(sum, a)
# Filter objects which satisfy the conditions.
>>> b = filter(lambda x: x < style="font-weight: bold;"># Execution.
# eval(str, [,globals [,locals]])
>>> c = eval('a+b')
>>> exec "print 4+3"
# execfile(filename [,globals [,locals]])
>>> execfile("hello.py")
# compile(str,filename,kind)
>>> c = compile(str, '', 'single')
>>> c = compile(str, '', 'exec')
>>> c = compile(str, '', 'eval')

# Input, Output
>>> s = raw_input("type something")
>>> c = sys.stdin.read(1)
>>> sys.stdout = open("output.txt", "w")

# Serialize
>>> f = open("save.dat", "w")
>>> pickle.dump(a,f)
>>> pickle.dump(b,f)
>>> f.close()
>>> f = open("save.dat", "r")
>>> obj = pickle.load(f)
>>> obj
2

# Built-in Functions
abs(x)
apply(func [,args [,keywords]])
buffer(object [,offset [,size]])
callable(obj)
chr(i)
cmp(x,y)
coerce(x,y)
compile(string, filename, kind)
complex(real [,img])
delattr(obj, attr)
dir([obj])
divmod(a,b)
eval(expr [, globals [,locals]])
execfile(filename [,globals [,locals]])
filter(function, list)
float(x)
getattr(obj,name)
globals()
hasattr(obj,name)
hash(obj)
hex(x)
id(obj)
input([prompt])
intern(string)
isinstance(obj,class)
issubclass(subclass,class)
len(s)
list(s)
locals()
long(x)
map(function, list, ...)
max(s [,args, ...])
min(s [,args, ...])
oct(x)
open(fname [, mode [, bufsize]])
ord(c)
power(x, y, [,z])
range([start,] stop [,step])
raw_input([prompt])
reduce(func, seq [,initializer])
reload(module)
repr(obj)
round(x [,n])
setattr(obj, name, value)
slice([start,] stop [,step])
str(obj)
tuple(s)
type(obj)
vars([obj])
xrange([start,] stop [, step])

# Built-in Exceptions
Exception
StandardError
ArithmeticError
LookupError
EnvironmentError
AssertionError
AttributeError
EOFError
FloatingPointError
IOError
ImportError
IndexError
KeyError
KeyboardInterrupt
MemoryError
NameError
NotImplementedError
OSError
OverflowError
RuntimeError
SyntaxError
SystemError
SystemExit
TypeError
ValueError
ZeroDivisionError

# Internal.
>>> a = [1,4,6]
>>> a.__doc__
"list() -> new list\nlist(sequence) -> new list initialized from sequence's items"
>>> class C:
... a = 0
... def work(self):
... print("hello world")
...
>>> c = C()
>>> c.__dict__
{}
>>> C.__dict__
{'a': 0, '__module__': '__main__', 'work': , '__doc__': None}
# There are many other built-in attributes for classes, instances, modules ...

Reference: Python Essential Reference by David M. Beazley

Make

Inside Makefile:

TARGET: DEPENDENCY LINE OR RULES LINE
COMMAND
COMMAND
...

A command line (with TAB in front) is running in a subshell by itself.

Awk

By default, a record is a line. A line is made up of fields with default delimiter. Main programs are mainly based on C program syntax.

Sed

Generic command format:

[address]command

command = d, a, i, c, r, w, q, ... d: Delete. a: Append. i: Insert. c: Change. r: Read. w: Write. q: Quit.

Group command format:

address{
command1
command2
command3
}

Substitution format:

[address]s/pattern/replacement/flags

flags = n, g, p, or w file. n: A number n represents nth occurrence. g: Global. p: Print. w file: Write to file.

Transform format:

[address]y/abc/xyz/

Translate a->x, b->y, and c->z.

[address] can be lines found by regular expression matches, range of lines.

Quick Reference

Posted in

The world is getting populated with more and more information. We cannot afford to consistently memorized all the given information such as programming languages, commands, ... Hence, quick references become useful for us to recall our memory before we intended to use them.

In this book page, I intended to create and consolidate quick references that I found useful.

Syndicate content