Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS 

Langton's Ant in Python

The following code simulates Langton's Ant using Python and PyGame.

A full explanation is given here.

#************************************************
# Rules of the game
#	1. If the ant is on a black square, it turns
#		right 90 and moves forward one unit
#	2. If the ant is on a white square, it turns
# 		left 90 and moves forward one unit
#	3. When the ant leaves a square, it inverts
#		colour
#
# SEE: http://mathworld.wolfram.com/LangtonsAnt.html
#************************************************

import sys, pygame
from pygame.locals import *
import time

dirs = (
		(-1, 0),
		(0, 1),
		(1, 0),
		(0, -1)
		)

cellSize = 12 # size in pixels of the board (4 pixels are used to draw the grid)
numCells = 64 # length of the side of the board
background = 0, 0, 0 # background colour; black here
foreground = 23, 23, 23 # foreground colour; the grid's colour; dark gray here
textcol = 177, 177, 177 # the colour of the step display in the upper left of the screen
antwalk = 44, 88, 44 # the ant's trail; greenish here
antant = 222, 44, 44 # the ant's colour; red here
fps = 1.0 / 40 # time between steps; 1.0 / 40 means 40 steps per second

def main():
	pygame.init()

	size = width, height = numCells * cellSize, numCells * cellSize

	pygame.display.set_caption("Langton's Ant")

	screen = pygame.display.set_mode(size) # Screen is now an object representing the window in which we paint
	screen.fill(background)
	pygame.display.flip() # IMPORTANT: No changes are displayed until this function gets called

	for i in xrange(1, numCells):
		pygame.draw.line(screen, foreground, (i * cellSize, 1), (i * cellSize, numCells * cellSize), 2)
		pygame.draw.line(screen, foreground, (1, i * cellSize), (numCells * cellSize, i * cellSize), 2)
	pygame.display.flip() # IMPORTANT: No changes are displayed until this function gets called

	font = pygame.font.Font(None, 36)

	antx, anty = numCells / 2, numCells / 2
	antdir = 0
	board = [[False] * numCells for e in xrange(numCells)]

	step = 1
	pause = False
	while True:
		for event in pygame.event.get():
				if event.type == QUIT:
					return
				elif event.type == KEYUP:
					if event.key == 32: # If space pressed, pause or unpause
						pause = not pause
					elif event.key == 115:
						pygame.image.save(screen, "Step%d.tga" % (step))

		if pause:
			time.sleep(fps)
			continue

		text = font.render("%d " % (step), True, textcol, background)
		screen.blit(text, (10, 10))
		
		if board[antx][anty]:
			board[antx][anty] = False # See rule 3
			screen.fill(background, pygame.Rect(antx * cellSize + 1, anty * cellSize + 1, cellSize - 2, cellSize - 2))
			antdir = (antdir + 1) % 4 # See rule 1
		else:
			board[antx][anty] = True # See rule 3
			screen.fill(antwalk, pygame.Rect(antx * cellSize + 1, anty * cellSize + 1, cellSize - 2, cellSize - 2))
			antdir = (antdir + 3) % 4 # See rule 2

		antx = (antx + dirs[antdir][0]) % numCells
		anty = (anty + dirs[antdir][1]) % numCells

		# The current square (i.e. the ant) is painted a different colour
		screen.fill(antant, pygame.Rect(antx * cellSize + 1, anty * cellSize + 1, cellSize -2, cellSize -2))

		pygame.display.flip() # IMPORTANT: No changes are displayed until this function gets called

		step += 1
		time.sleep(fps)

if __name__ == "__main__":
	main()

'ant' build file for HelloWorldServlet and JettyLauncher

A pretty straightforward 'ant' build file. You will need to edit the jetty.home property to indicate where you installed Jetty.

<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="compile" name="hello-servlet">
  <property name="build.dir"	location="classes" />
  <property name="src.dir"	location="src/main/java" />
  <property name="jetty.home"	location="/home/mrw/projects/jetty-6.1.3" />
  <property name="jetty.lib"	location="${jetty.home}/lib" />

  <path id="jetty.lib.path">
    <pathelement path="${jetty.lib}/jetty-6.1.3.jar" />
    <pathelement path="${jetty.lib}/jetty-util-6.1.3.jar" />
    <pathelement path="${jetty.lib}/servlet-api-2.5-6.1.3.jar" />
  </path>

  <target name="compile" description="Compile the project">
    <mkdir dir="${build.dir}" />
    <javac debug="true" destdir="${build.dir}" srcdir="${src.dir}"
	classpathref="jetty.lib.path">
      <compilerarg value="-Xlint:unchecked" />
      <compilerarg value="-Xlint:deprecation" />
    </javac>
  </target>

  <target name="all"  depends="clean,compile"
      description="Recompile from scratch"/>

  <target name="server" depends="compile" description="Launch the server">
    <java classname="com.babblemind.JettyLauncher" fork="true"
	classpathref="jetty.lib.path">
      <classpath>
	<pathelement path="${build.dir}" />
      </classpath>
    </java>
  </target>

  <target name="clean" description="Delete all files created by compile">
    <delete dir="${build.dir}" />
    <delete dir="docs/api" />
  </target>
</project>

Sample Ant script for building a webapp.

// Sample ant script to build a webapp.

<project name="Combine Enrolments" default="dist" basedir=".">
<!-- Note that you'll need ant 1.7 for this build, as 1.6.5 doesn't have comprehensive filelist support -->
	
	<!-- Pull in properties -->
	<property file="build.properties" />
	
	<!-- DEFINITIONS -->
	<!-- Run time jars. These ones will get distributed alongside this app -->
	<filelist id="dist_jars" dir="${lib.dir}"> 
		<file name="${commons-cli.jar}" />
		<file name="${log4j.jar}" />
	</filelist>

	<!-- Build time jars -->
	<filelist id="misc_jars">
		<file name="${servlet-api.jar}" />
	</filelist> 

	<path id="classpath">
        <pathelement location="${build.classes.dir}"/>
 		<filelist refid="dist_jars" />
		<filelist refid="misc_jars" /> 
	 </path>
	
	<!-- TARGETS -->
	<target name="javadoc" depends="init" description="Generate javadoc">
		<echo>Generating javadoc</echo>
		<javadoc packagenames="au.edu.qut.*"
				sourcepath="${src.dir}"
				destdir="${doc.dir}" >
			<classpath refid="classpath"/>
		</javadoc>
	</target>
	
	<target name="dist" depends="build,copy_libs" description="Generate an executable jar, ready for distribution">
		<copy file="log4j.properties" todir="${build.classes.dir}"  />

		<pathconvert property="jar.classpath" pathsep=" ">
		    <mapper>
		      <chainedmapper>
			    <!-- remove absolute path -->
		        <flattenmapper />

		        <!-- add lib/ prefix -->
		        <globmapper from="*" to="lib/*" />
		      </chainedmapper>
		    </mapper>

	    	<path>
		  	<!-- lib.home contains all jar files, in several subdirectories -->
	    		<filelist refid="dist_jars" />
			</path>
		</pathconvert>
		
		<jar basedir="${build.classes.dir}" destfile="${dist.dir}/${jar.name}">
			<manifest>
				<attribute name="Main-Class" value="${jar.main.class}"/>
			</manifest>
		</jar>
	</target>

	<target name="build" depends="init,copy_libs" description="Compile the thing already">
		<echo>Building ${ant.project.name}</echo>
		<javac srcdir="${src.dir}" destdir="${build.classes.dir}" debug="${build.debug}" >
			<classpath refid="classpath"/>
		</javac>
	</target>
	
	<target name="copy_libs" depends="init" description="Copy runtime  dependencies to the dist directory">
		<echo>Copying Dependencies</echo>
		<copy todir="${dist.lib.dir}" >
			<filelist refid="dist_jars" />
			<mapper type="flatten" />
		</copy>
		<copy todir="${build.lib.dir}" >
			<filelist refid="dist_jars" />
			<mapper type="flatten" />
		</copy>
	</target>
	
	<target name="clean" depends="init"  description="Clean up build structure">
		<echo>Cleaning...</echo>
		<delete dir="${build.dir}" includeEmptyDirs="true"/>
		<delete dir="${dist.dir}" includeEmptyDirs="true" />
		<delete dir="${doc.dir}" includeEmptyDirs="true" />
	</target>
	
	<target name="init" description="Initialise build process">
		<tstamp/>
		<echo> Building ${ant.project.name} with Ant Version ${ant.version}</echo>
		<mkdir dir="${build.classes.dir}" />
		<mkdir dir="${build.lib.dir}"/>
		<mkdir dir="${doc.dir}"/>
		<mkdir dir="${dist.dir}" />
		<mkdir dir="${dist.lib.dir}" />
	</target>
</project>

Converting file list into a class list

Converting file list into a class list - this is particularly useful for include-classes attribute of compc task in Flex, but may be useful for Java. The <chainmapper> is most probably pleonastic but it works for me this way, and I don't feel like trying it without it...

   <path id="xmlrpc_class_list_1">
      <fileset dir="${user.dir}/xmlrpc">
         <include name="com/mattism/**"/>
         <exclude name="**/Test*"/>
      </fileset>
   </path>
   <pathconvert 
      property="xmlrpc_class_list_2" 
      pathsep=" " 
      dirsep="." 
      refid="xmlrpc_class_list_1">
      <map from="${user.dir}/xmlrpc/" to=""/>
      <mapper>
         <chainedmapper>
            <globmapper from="*.as" to="*"/>
         </chainedmapper>
      </mapper>
</pathconvert>

Getting build number for Ant build in Continuum

Getting build number for Ant build in Continuum

   
<timestampselector property="mostrecentlog">
<path>
<fileset dir="${user.dir}/../../cont-output/1">
<include name="*.log.txt" />
</fileset>
</path>
</timestampselector>			

<basename property="reportsDirName" file="${mostrecentlog}" suffix=".log.txt">
</basename>

Basic ant script with vim & jikes

Apache ant build XML. This will use jikes in place of javac. Any compiler error output is formatted so that vim can parse it.

ant is a modern alternative to make. The build script is an XML file. It works particularly well with java. Download it for free from the Apache ant site. Most people find ant a lot nicer to live with than make.

<?xml version="1.0"?>

<project name="Hello" default="compile" basedir=".">
  <property name="name" value="Hello"/>
  <property name="version" value="1.0"/>

  <!-- Project directories.
  -->

  <property name="build" value="build"/>
  <property name="dist" value="dist"/>
  <property name="src" value="src"/>

  <!-- Compiler directives.
  -->

  <property name="optimize" value="off"/>
  <property name="deprecation" value="on"/>
  <property name="debug" value="on"/>

  <property name="build.compiler" value="jikes"/>
  <property name="build.compiler.emacs" value="true"/>

  <target name="init">
    <tstamp/>
    <mkdir dir="${build}"/>
  </target>

  <!-- Compile all the .java files from the source directory into
       the build directory.
  -->

  <target name="compile" depends="init">
    <javac srcdir="${src}" destdir="${build}" includes="**/*.java"
      debug="${debug}" deprecation="${deprecation}" optimize="${optimize}">
    </javac>
  </target>

  <target name="clean" depends="init">
    <delete dir="${build}"/>
    <delete dir="${dist}"/>
  </target>

  <target name="test" depends="compile">
    <java classname="HelloWorld" fork="yes">
      <classpath>
        <pathelement location="${build}"/>
      </classpath>
    </java>
  </target>
</project>

Ant 101

// Ah Ant. How I love thee, how much better a build tool
// than my ex build tool Make.
//
// This is my current starting build.xml Ant script for any
// Java project. It specifies my usual directories, it will
// build source code, make a Jar, build a War, clean up build
// products, create Javadoc, and even run unit tests.
//
// Notice that I use the JReleaseInfo library to automatically
// generate a Java class that contains version numbers, build
// numbers, etc. Be sure to put the Jar from that library in
// the library directory to get that feature:
// http://jreleaseinfo.sourceforge.net/

<?xml version="1.0"?>
<project name="New Project" basedir="." default="all">
    <target name="init">
        <property name="appName" value="newProject"/>
    
        <property name="buildDir" value="${basedir}/build"/>
        <property name="libDir" value="${basedir}/lib"/>
        <property name="javaSourceDir" value="${basedir}/src"/>
        <property name="testDir" value="${basedir}/test"/>
        <property name="webSourceDir" value="${basedir}/web"/>
        <property name="etcDir" value="${basedir}/etc"/>
        <property name="tempDir" value="${basedir}/tmp"/>
        <property name="classDir" value="${buildDir}/classes"/>

        <!-- This may get overridden when we are called from Anthill. -->
        <property name="version" value="Local Build"/>
        <property name="deployDir" value="${buildDir}"/>

        <property name="distDir" value="${deployDir}/dist"/>
        <property name="junitDir" value="${deployDir}/JUnit"/>
        <property name="javadocDir" value="${deployDir}/apidoc"/>

        <!-- Create the directories where we put all the build products. -->    
        <mkdir dir="${buildDir}"/>
        <mkdir dir="${classDir}"/>
        <mkdir dir="${distDir}"/>
        <mkdir dir="${junitDir}"/>
        <mkdir dir="${javadocDir}"/>

        <path id="compileClasspath">
            <fileset dir="${libDir}"/>
        </path>

        <!-- Make available build info in such a way that we can display it to the user. -->
        <taskdef name="jreleaseinfo" classname="ch.oscg.jreleaseinfo.anttask.JReleaseInfoAntTask">
            <classpath refid="compileClasspath"/>
        </taskdef>

        <jreleaseinfo className="MyReleaseInfo" packageName="com.johnmunsch.${appName}"
                targetDir="${javaSourceDir}" project="${appName}" version="${version}" 
                buildNumFile="buildnum.properties" buildNumProperty="buildnum">
            <parameter name="VersionNum" type="int" value="1" />
            <parameter name="RevisionNum" type="Integer" value="0" />
        </jreleaseinfo>
    </target>

    <target name="compile" depends="init">
        <javac srcdir="${javaSourceDir}" destdir="${classDir}" debug="true" deprecation="true">
            <classpath refid="compileClasspath"/>
        </javac>

        <!-- Copy files needed to run the software to destinations in the 
         build directory. I do this because I usually pull all binary files like
         this from inside the Jar files that make up my application rather than
         having them loose. So they need to be copied to the class dir so they
         get included in the Jar file for the application. -->
        <copy todir="${classDir}" >
            <fileset dir="${javaSourceDir}">
                <include name="**/*.gif"/>
                <include name="**/*.jpg"/>
                <include name="**/*.png"/>
                <include name="**/*.wav"/>
                <include name="**/*.dtd"/>
                <include name="**/*.properties"/>
            </fileset>
        </copy>
    </target>

    <target name="jar" depends="init,compile">
        <jar jarfile="${distDir}/${appName}.jar" compress="true" 
            basedir="${classDir}"/>
    </target>

    <target name="war" depends="jar">
        <war destfile="${distDir}/${appName}.war" webxml="${etcDir}/WEB-INF/web.xml">
            <fileset dir="web"/>
            <lib dir="${libDir}">
                <include name="jstl.jar"/>
                <include name="standard.jar"/>
            </lib>
            <lib dir="${libDir}">
                <include name="*.jar"/>
            </lib>
            <lib dir="${distDir}">
                <include name="${appName}.jar"/>
            </lib>
        </war>
    </target>

    <target name="all" depends="war" description="Build everything.">
        <echo message="Application built."/>
    </target>

    <target name="javadoc" depends="init" description="Javadoc for the code.">
        <javadoc packagenames="*" sourcepath="${javaSourceDir}" 
	        destdir="${javadocDir}"/>
    </target>

    <target name="clean" depends="init" description="Clean all build products.">
        <delete dir="${tempDir}"/>
        <delete dir="${javadocDir}"/>
        <delete dir="${junitDir}"/>
        <delete dir="${distDir}"/>
        <delete dir="${classDir}"/>
        <delete dir="${buildDir}"/>
    </target>

    <target name="junit" depends="jar" description="Performs unit tests.">
        <javac srcdir="test" destdir="${classDir}" debug="true" deprecation="true">
            <classpath refid="compileClasspath"/>
        </javac>

        <mkdir dir="${tempDir}"/>

        <junit failureproperty="junit.failed">
            <formatter type="xml"/>
            <batchtest todir="${tempDir}">
                <fileset dir="${classDir}">
                   <include name="**/*Test.class"/>
                   <include name="**/Test*.class"/>
                </fileset>
            </batchtest>
            <classpath>
                <path refid="compileClasspath"/>
                <pathelement location="${classDir}"/>
            </classpath>
        </junit>

        <mkdir dir="${buildDir}/JUnit"/>

        <junitreport tofile="TESTS-TestSuites.xml" todir="${tempDir}">
            <fileset dir="${tempDir}">
                <include name="TEST-*.xml"/>
            </fileset>
            <report todir="${junitDir}"/>
        </junitreport>
  	
        <fail message="JUnit test failure." if="junit.failed"/>  	
    </target>
</project>
« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS