Skip to content

Commit a36d188

Browse files
committed
Add sample python code to readme
1 parent 2463f17 commit a36d188

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

README.rst

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,3 +88,41 @@ There is also a command to remove the `bin` directory as well as the object
8888
files::
8989

9090
$ make remove
91+
92+
93+
Python
94+
------
95+
96+
The strategy functions are available from within a shared object file,
97+
`libstrategies.so` and can therefore be called from within Python. An example
98+
of how to call TitForTat::
99+
100+
.. code:: python
101+
102+
from ctypes import cdll, c_int, c_float, byref, POINTER
103+
# load the strategies library
104+
strategies = cdll.LoadLibrary('libstrategies.so')
105+
106+
# Use the titfortat strategy from the library
107+
tft = strategies.ktitfortatc_
108+
109+
# define the types of the function arguments and return value
110+
tft.argtypes = (
111+
POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int),
112+
POINTER(c_float))
113+
tft.restype = c_int
114+
115+
# Variables for the argument to pass
116+
my_previous = c_int(0) # 0 is cooperation, 1 is defection
117+
their_previous = c_int(1)
118+
move_number = c_int(1)
119+
my_score = c_int(0)
120+
their_score = c_int(0)
121+
noise = c_float(0)
122+
123+
# Call the strategy passing the arguments by reference
124+
result = tft(
125+
byref(their_previous), byref(move_number), byref(my_score),
126+
byref(their_score), byref(noise), byref(my_previous))
127+
128+
print(result)

0 commit comments

Comments
 (0)