view src/sim.tp @ 8:5941e6b3684c

Read map file in simulator
author Mike Pavone <pavone@retrodev.com>
date Sat, 14 Jul 2012 01:42:05 -0700
parents 86cdb799f950
children 66ea6fdd3fcb
line wrap: on
line source

#{
	true <- #{
	  if:else <- :self trueblock :elseblock {
		trueblock:
	  }
	}

	false <- #{
	  if:else <- :self trueblock :elseblock {
		elseblock:
	  }
	}

	cellType <- #{
		robot       <- ("R"  byte: 0)
		wall        <- ("#"  byte: 0)
		rock        <- ("*"  byte: 0)
		lambda      <- ("\\" byte: 0)
		closedlift  <- ("L"  byte: 0)
		openlift    <- ("O"  byte: 0)
		earth       <- ("."  byte: 0)
		empty       <- (" "  byte: 0)
		newline     <- ("\n" byte: 0)
    }

	state <- #{
		new <- :in_grid in_width in_height { 
			next_grid <- #[]
			foreach: in_grid :index el{
				next_grid append: el
			}
			#{
				grid <- in_grid
				width <- in_width
				height <- in_height
				address <- :x y { x + y * width }
				setCell <- :x y cell {
					grid set: (address: x y) cell
				}
				getCell <- :x y {
					grid get: (address: x y)
				}
				collected <- 0
				moves <- 0
				ended <- false
				doMove <- :roboMove {
					ended <- roboMove = "A"
				}
				advance <- :roboMove {
					doMove: roboMove
					moves <- moves + 1
					self
				}
				
			}
		}
		fromStr <- :str {
			strLen <- str byte_length:
			index <- 0
			maxRow <- 0
			curRow <- 0
			while: {index < strLen} do: {
				curByte <- str byte: index
				if: curByte = (cellType newline) {
					maxRow <- if: curRow > maxRow {curRow} else: {maxRow}
				} else: {
					curRow = curRow + 1
				}
			}
			grid <- #[ ("#" byte: 0) ("#" byte: 0) ("#" byte: 0)  (			                 "#" byte: 0) (" " byte: 0) ("#" byte: 0)  (			                 "#" byte: 0) ("#" byte: 0) ("#" byte: 0)] 
			fresh <- new: grid 3 3
			fresh
		}
	}

	testMoves <- {
		myStep <- 0
		{
			print: (string: myStep)
			myStep <- myStep + 1
			if: myStep > 5 {"A"} else: {"W"}
		}
	}
	
	readFile <- :path {
		fd <- os open: path (os O_RDONLY)
		print: "fd: " . fd . "\n"
		if: fd < 0 { "" } else: {
			cur <- ""
			part <- ""
			while: { 
				part <- os read: fd 128
				print: "read: " . part . "\n"
				part != ""
			} do: {
				cur <- cur . part
			}
			os close: fd
			cur
		}
	}
	
	getMove <- {
		os read: 0 1
	}

	main <- :args {
		if: (args length) < 2 {
			print: "usage: sim filename\n"
		} else: {
			print: (args get: 1) . "\n"
			text <- readFile: (args get: 1)
			simState <- state fromStr: text
			while: { if: (simState ended) {false} else: {true} } do: {
				print: "step...\n"
				simState advance: (getMove: )
			}
		}
	}

}