hello.cmt7 lines
Hello: the smallest program, one line of output.
// hello.cmt — the smallest program
use basic
fun main() {
printl("Hello, comet!")
}
main is where every program starts, and printl writes a line. The use basic line says the program needs only the everyday module; leave it out and the program still works.
Commands in this program (3)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
variables.cmt12 lines
Variables: numbers, text and true/false values.
// Variables: numbers need no type word, text and true/false do
use basic
fun main() {
age = 17
height = 1.75
string name = "Dan"
bool student = true
age = age + 1
printl(name, "is", age, "and", height, "m tall")
printl("student:", student, "| half the age:", age / 2)
}
A number variable is just a name and a value, no type word. Text needs the word string and true/false needs bool. A variable keeps its kind: age stays a number, and age / 2 is exact (9), not rounded.
Commands in this program (3)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
input.cmt8 lines
Input: ask the user two things and answer back.
// Input: ask the user something and answer back
use basic
fun main() {
name = input("What is your name? ")
years = input("How old are you? ")
printl("Hi {name}! In 10 years you will be {num(years) + 10}.")
}
input() shows a prompt and returns what the user typed as text. Inside a string, {curly braces} insert values; num(years) turns the text into a number before adding 10. In the playground the answers come from the Input box.
Commands in this program (4)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.input(prompt) Shows the prompt, waits until the user types a line and presses Enter, and gives that line back as text. The answer is always text, so use num() when you need a number. In the playground you type the answer right in the console.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
conditions.cmt15 lines
Conditions: if, else if, else and the ?: short form.
// Conditions: if, else if, else
use basic
fun main() {
score = 72
if (score >= 90) {
printl("A")
} else if (score >= 70) {
printl("B")
} else {
printl("try again")
}
passed = score >= 50 ? "passed" : "failed"
printl(passed, score > 50 and score < 100)
}
An if / else if / else chain runs the first branch whose test is true, so the order matters. Comparisons give true or false, and and/or/not combine them. x = test ? a : b is the short form for choosing one of two values.
Commands in this program (4)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.if / else if / else Runs a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
loops.cmt13 lines
Loops: a range, a list, a counter loop and while.
// Loops: a range, a list, a counter and while
use basic
fun main() {
for (i in 1 to 4) { print(i, end=" ") }
printl()
for (color in ["red", "green", "blue"]) { printl(color) }
for (i = 10; i > 0; i -= 3) { print(i, end=" ") }
printl()
n = 1
while (n < 100) { n = n * 2 }
printl("first power of 2 above 100:", n)
}
Four ways to loop: a range (1 to 4 stops before 4), the items of a list, a counter loop with a step of -3, and while, which repeats until its test fails. print with end=" " stays on the same line; printl() ends it.
Commands in this program (7)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.for (i in a to b) Repeats a block for every whole number from a up to, but not including, b. Add step to count in other steps (also backwards). for (x in list) goes through a list, a map's keys or a text's characters.print(a, b, …) Works like printl but stays on the same line, so the next print continues right after it. Use it to build one line out of several steps, for example inside a loop. Nothing is added between two separate print calls.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.list [a, b, c] A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.while (condition) Repeats a block as long as the condition is true. break leaves the loop at once, continue skips to the next round.
functions.cmt16 lines
Functions: define them, call them, return values.
// Functions: define them, call them, return values
use basic
fun greet(name) {
printl("Hello,", name)
}
fun area(width, height) {
return width * height
}
fun main() {
greet("comet")
printl("area:", area(3, 4))
printl("twice:", area(2, 5) * 2)
}
fun defines a function; parameters have no type words, so area works for any numbers. return gives a value back to the caller. Functions can be declared in any order, and a function that only prints returns nothing.
Commands in this program (3)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
lists.cmt13 lines
Lists: add, index, sort, search, join.
// Lists: add, index, sort, search
use basic
fun main() {
nums = [5, 3, 8]
nums.add(1)
printl(nums, "first:", nums[0], "last:", nums[-1], "count:", nums.len())
nums.sort()
printl("sorted:", nums, "sum:", nums.sum())
printl("has 8?", 8 in nums, "where?", nums.index_of(8))
names = ["mia", "bob"]
printl(names.join(" and "))
}
A list keeps values in order. add appends, nums[0] and nums[-1] read the first and last item, len counts, sort changes the list in place, sum adds it up, in and index_of search, join glues text items together.
Commands in this program (10)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.list [a, b, c] A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.l.add(x) Adds an item to the end of the list. push and append are other names for the same thing. An empty list [] takes its kind from the first thing you add.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.s.len() The number of characters in the text, counting letters from any language as one each. Spaces count as well.l.sort() / l.sort_desc() Puts the list itself in order, smallest first, or biggest first with sort_desc. Text sorts alphabetically, with capitals before small letters.l.sum() / l.min() / l.max() Add up the list, or find its smallest or biggest item, without writing a loop.l.contains(x) / l.index_of(x) / l.count(x) contains says whether x is in the list, index_of gives its position (or -1), and count says how many times it appears. x in l is the same as contains.l.join(sep) Glues the items into one text with sep between them. It is the opposite of split, and works for numbers too.
maps.cmt12 lines
Maps: values stored under keys (use map).
// Maps: values stored under keys
use map
fun main() {
ages = {"dan": 17, "bob": 20}
ages["eve"] = 30
printl(ages["dan"], ages.len(), ages.has("zoe"))
for (name in ages) {
printl(name, "is", ages[name])
}
printl(ages.get("zoe", 0), ages.keys())
}
A map stores a value under a key. ages["eve"] = 30 adds a key, ages["dan"] reads one, has checks, get gives a fallback for a missing key, keys lists them, and a for loop visits the keys in sorted order. Maps need use map.
Commands in this program (10)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.map {key: value} A map stores values under keys, like a dictionary: m["apple"] is the value saved under "apple". Keys are text or numbers. See comet help has, comet help keys, comet help get.list [a, b, c] A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.s.len() The number of characters in the text, counting letters from any language as one each. Spaces count as well.m.has(key) true when the key is in the map. key in m means the same.for (i in a to b) Repeats a block for every whole number from a up to, but not including, b. Add step to count in other steps (also backwards). for (x in list) goes through a list, a map's keys or a text's characters.m.get(key, fallback) Like m[key], but gives the fallback when the key is missing instead of stopping the program. It is the classic way to count things.m.keys() / m.values() Lists of all keys and all values, always in sorted key order. for (k in m) walks the keys directly.
structs.cmt19 lines
Structs: your own kind of value with fields and methods.
// Structs: your own kind of value with fields and methods
use basic
struct Player {
string name = "guest"
score = 0
fun hit(points) {
score += points
}
}
fun main() {
p = Player("dan")
p.hit(10)
p.hit(5)
printl(p.name, "has", p.score, "points")
printl(p)
}
A struct bundles named fields with methods that work on them. Player("dan") fills the fields in order and keeps the starting values for the rest. Inside hit, score is the field of the player you called it on. Printing a struct prints all its fields.
Commands in this program (4)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.struct Name Makes your own kind of value with named fields (and functions inside it, called methods). Name(...) makes one; the values fill the fields in order, missing ones keep their starting value.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
strings.cmt12 lines
Strings: the most useful text methods.
// Strings: the most useful text methods
use basic
fun main() {
s = " Hello World "
t = s.trim()
printl(t.upper(), "|", t.len(), "letters")
printl(t.contains("World"), t.starts_with("He"), t.find("o"))
printl(t.replace("World", "comet"), t.substr(0, 5), t[0])
parts = "a,b,c".split(",")
printl(parts, parts.join(" + "), "-" * 10)
}
trim removes spaces at both ends, upper changes case, len counts characters, contains/starts_with/find search, replace swaps text, substr cuts a piece, s[0] is one character, split turns text into a list and join does the reverse, and "-" * 10 repeats text.
Commands in this program (14)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.s.trim() A copy without spaces, tabs and new lines at both ends; spaces in the middle stay. Use it on everything a user types.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.s.upper() / s.lower() Copies of the text in capitals or small letters. The original does not change. lower() is the easy way to compare answers without caring how the user typed them.s.len() The number of characters in the text, counting letters from any language as one each. Spaces count as well.s.contains(t) true when t appears anywhere in the text. "x" in s means the same and reads nicely in an if. The match is exact, capitals included.s.starts_with(t) / s.ends_with(t) Check how the text begins or ends. Useful for commands typed by a user, or for checking a file's type.s.find(t) The position where t first appears, counting from 0, or -1 when it is not there. Check for -1 before you use the result.s.replace(a, b) A copy with every a swapped for b. Give an empty b to remove something.s.substr(from, to) / s.substr(from) The piece of text from index from up to, but not including, to. Without to it goes to the end. Negative numbers count from the end, so -2 means the last two characters. slice is another name for it.list [a, b, c] A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.s.split(sep) / s.split() Cuts the text into a list of pieces at every sep. Without an argument it cuts at any spaces and ignores extras, which is perfect for words. join does the opposite.l.join(sep) Glues the items into one text with sep between them. It is the opposite of split, and works for numbers too.
random.cmt12 lines
Random numbers: dice, decimals, picking from a list (use random).
// Random numbers: dice, decimals and picking from a list
use random
fun main() {
dice = random(1 to 6)
printl("you rolled", dice)
printl("a price:", round(float.random(4.5 to 10), 2))
names = ["dan", "mia", "bob"]
printl("picked:", random(names))
names.shuffle()
printl("shuffled:", names)
}
random(1 to 6) gives a whole number with both ends included, float.random(4.5 to 10) a decimal, random(names) picks an item and shuffle mixes a list in place. The file needs use random; without it the compiler names the missing line.
Commands in this program (8)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.random(a to b) A whole number from a to b, and both ends can come up. This is the one you want for dice, for picking a position, or any "choose a number" job. Every run gives different results.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.round(x) / round(x, n) Rounds to the nearest whole number. With a second number it keeps that many decimals, which is the usual way to print prices or results neatly.float.random(a to b) A decimal number between a and b. Use it for smooth values such as a speed or a price. float.random() with nothing gives a number from 0 up to 1.list [a, b, c] A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.l.reverse() / l.shuffle() Change the list itself: reverse flips the order and shuffle mixes it randomly. shuffle needs use random.
fizzbuzz.cmt17 lines
FizzBuzz: the classic counting exercise.
// FizzBuzz — the classic
use basic
fun main() {
for (i in 1 to 31) {
if (i % 15 == 0) {
printl("FizzBuzz")
} else if (i % 3 == 0) {
printl("Fizz")
} else if (i % 5 == 0) {
printl("Buzz")
} else {
printl(i)
}
}
}
Count from 1 to 30 and print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for both. % gives the remainder of a division, and the test for 15 has to come first.
Commands in this program (5)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.for (i in a to b) Repeats a block for every whole number from a up to, but not including, b. Add step to count in other steps (also backwards). for (x in list) goes through a list, a map's keys or a text's characters.if / else if / else Runs a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
guess.cmt25 lines
Guess the number: a game that reads your guesses.
// Guess the number — reading input in a loop
use random
fun main() {
secret = random(1 to 100)
tries = 0
printl("I picked a number from 1 to 100.")
while (true) {
answer = input("Your guess: ")
if (not answer.is_num()) {
printl("Please type a number.")
continue
}
guess = num(answer)
tries += 1
if (guess < secret) {
printl("Higher!")
} else if (guess > secret) {
printl("Lower!")
} else {
printl("Correct! You needed {tries} tries.")
break
}
}
}
The secret comes from random(1 to 100). The loop asks until the guess is right: is_num checks the input, continue skips a bad round, num converts, break ends the game. Try it with the sample input or type your own guesses.
Commands in this program (9)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.random(a to b) A whole number from a to b, and both ends can come up. This is the one you want for dice, for picking a position, or any "choose a number" job. Every run gives different results.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.while (condition) Repeats a block as long as the condition is true. break leaves the loop at once, continue skips to the next round.input(prompt) Shows the prompt, waits until the user types a line and presses Enter, and gives that line back as text. The answer is always text, so use num() when you need a number. In the playground you type the answer right in the console.if / else if / else Runs a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.s.is_num() true when the text is a number, decimals and minus sign included. Always check user input with it before calling num().num(text) Turns text into a number. You need it because input() and split() give you text, and text cannot do math. If the text is not a number the program stops with a clear error, so check with .is_num() first when the text comes from a user.
calculator.cmt22 lines
Calculator: reads lines like 12 * 3 until you type q.
// Calculator: type lines like 12 * 3, q quits
use basic
fun main() {
while (true) {
line = input("> ").trim()
if (line == "q" or line == "") { break }
parts = line.split(" ")
if (parts.len() != 3 or not parts[0].is_num() or not parts[2].is_num()) {
printl("type: number operator number")
continue
}
a = num(parts[0])
b = num(parts[2])
op = parts[1]
if (op == "+") { printl("=", a + b) }
else if (op == "-") { printl("=", a - b) }
else if (op == "*") { printl("=", a * b) }
else if (op == "/") { printl("=", a / b) }
else { printl("unknown operator", op) }
}
}
Each round reads a line, splits it into number, operator and number, checks that the numbers are really numbers, and prints the result. break on q ends the loop, continue skips a bad line.
Commands in this program (12)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.while (condition) Repeats a block as long as the condition is true. break leaves the loop at once, continue skips to the next round.input(prompt) Shows the prompt, waits until the user types a line and presses Enter, and gives that line back as text. The answer is always text, so use num() when you need a number. In the playground you type the answer right in the console.s.trim() A copy without spaces, tabs and new lines at both ends; spaces in the middle stay. Use it on everything a user types.if / else if / else Runs a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.s.split(sep) / s.split() Cuts the text into a list of pieces at every sep. Without an argument it cuts at any spaces and ignores extras, which is perfect for words. join does the opposite.s.len() The number of characters in the text, counting letters from any language as one each. Spaces count as well.list [a, b, c] A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.s.is_num() true when the text is a number, decimals and minus sign included. Always check user input with it before calling num().printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.num(text) Turns text into a number. You need it because input() and split() give you text, and text cannot do math. If the text is not a number the program stops with a clear error, so check with .is_num() first when the text comes from a user.
primes.cmt22 lines
Primes: finds the first 20 prime numbers.
// Functions and loops: prime numbers
use basic
fun is_prime(n) {
if (n < 2) { return false }
for (d = 2; d * d <= n; d++) {
if (n % d == 0) { return false }
}
return true
}
fun main() {
found = []
n = 2
while (found.len() < 20) {
if (is_prime(n)) { found.add(n) }
n++
}
printl("first 20 primes:", found)
printl("sum:", found.sum(), "biggest:", found.max())
}
is_prime tries every divisor while d * d <= n and returns false as soon as one divides n. main keeps adding primes to a list until it holds 20, then prints the list, its sum and its biggest item.
Commands in this program (10)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.if / else if / else Runs a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.for (i in a to b) Repeats a block for every whole number from a up to, but not including, b. Add step to count in other steps (also backwards). for (x in list) goes through a list, a map's keys or a text's characters.list [a, b, c] A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.while (condition) Repeats a block as long as the condition is true. break leaves the loop at once, continue skips to the next round.s.len() The number of characters in the text, counting letters from any language as one each. Spaces count as well.l.add(x) Adds an item to the end of the list. push and append are other names for the same thing. An empty list [] takes its kind from the first thing you add.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.l.sum() / l.min() / l.max() Add up the list, or find its smallest or biggest item, without writing a loop.
recursion.cmt17 lines
Recursion: factorial and Fibonacci.
// Recursion: functions that call themselves
use basic
fun factorial(n) {
if (n <= 1) { return 1 }
return n * factorial(n - 1)
}
fun fib(n) {
if (n < 2) { return n }
return fib(n - 1) + fib(n - 2)
}
fun main() {
printl("10! =", factorial(10))
printl("fib(20) =", fib(20))
}
A recursive function calls itself with a smaller problem until it reaches a simple case: factorial stops at 1, fib at 0 and 1. Put the simple case first, so the compiler can tell what the function returns.
Commands in this program (4)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.if / else if / else Runs a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
matrix.cmt54 lines
Matrix rain: goto and color make a console animation.
// Matrix rain: goto moves the cursor anywhere, color changes the text colour
use random, chrono
fun main() {
width = screen_width()
height = screen_height() - 1
trail = 10
letters = "abcdefghijklmnopqrstuvwxyz0123456789".chars()
// one drop in every second column; each has its own place and speed
columns = []
drops = []
speeds = []
for (x in 0 to width step 2) {
columns.add(x)
drops.add(random(-height to 0))
speeds.add(random(1 to 4))
}
command("cls")
cursor(false)
for (frame in 1 to 500) {
// the old heads turn green, the tails disappear, the drops move down
color("green")
for (i in 0 to columns.len()) {
if (frame % speeds[i] == 0) {
y = drops[i]
if (y >= 0 and y < height) {
goto(columns[i], y)
print(random(letters))
}
if (y - trail >= 0 and y - trail < height) {
goto(columns[i], y - trail)
print(" ")
}
drops[i] = y + 1
if (y - trail > height) { drops[i] = random(-height to 0) }
}
}
// the new heads are white
color("white")
for (i in 0 to columns.len()) {
if (frame % speeds[i] == 0 and drops[i] >= 0 and drops[i] < height) {
goto(columns[i], drops[i])
print(random(letters))
}
}
sleep(0.03)
}
color("reset")
cursor(true)
command("cls")
printl("wake up, neo")
}
screen_width and screen_height say how big the console is. There is a drop in every second column, each with its own speed, and only the drops that move this frame write anything, so the screen stays calm and smooth. The old head turns green, a space erases the tail 10 lines above, and a new white letter is the head. goto jumps to each spot, color is set only twice per frame, cursor(false) hides the cursor, and sleep(0.03) sets the speed. It stops after 500 frames.
Commands in this program (17)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.screen_width() / screen_height() How many characters fit across the terminal, and how many lines fit down it. Use them so that your drawing fits any window instead of guessing a size.s.lines() / s.chars() lines() gives a list with one item per line, and chars() a list with one item per character. Looping for (c in s) also walks the characters.list [a, b, c] A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.for (i in a to b) Repeats a block for every whole number from a up to, but not including, b. Add step to count in other steps (also backwards). for (x in list) goes through a list, a map's keys or a text's characters.l.add(x) Adds an item to the end of the list. push and append are other names for the same thing. An empty list [] takes its kind from the first thing you add.random(a to b) A whole number from a to b, and both ends can come up. This is the one you want for dice, for picking a position, or any "choose a number" job. Every run gives different results.command("cls") Clears the whole screen and puts the cursor at the top-left. "cls" and "clear" do the same on every system, also in the playground. Use it at the start of a text game or between the frames of an animation.cursor(on) cursor(false) hides the blinking cursor and cursor(true) shows it again. Hide it while an animation runs so it does not flicker around the screen, and always bring it back at the end.color("name") Changes the colour of all text printed after it, until the next color call. The names are red, green, blue, yellow, white, black, gray, orange, purple, pink, brown, cyan, dark and light, or any colour written like #ff8800. color("reset") goes back to the terminal's normal colour; do it before your program ends.s.len() The number of characters in the text, counting letters from any language as one each. Spaces count as well.if / else if / else Runs a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.goto(x, y) Moves the cursor to a place on the screen, and the next print starts there. x counts characters from the left and y counts lines from the top; the top-left corner is 0, 0. It lets you draw anywhere, which is what animations and text games need.print(a, b, …) Works like printl but stays on the same line, so the next print continues right after it. Use it to build one line out of several steps, for example inside a loop. Nothing is added between two separate print calls.sleep(seconds) Pauses the program. Decimals are fine, so sleep(0.1) waits a tenth of a second. It also sends everything printed so far to the screen, which makes it the heart of every console animation.printl(a, b, …) Prints values and then ends the line, so the next print starts on a new line. You can give it as many values as you like, of any kind: text, numbers, true/false, lists. It puts one space between them. printl() with nothing prints an empty line.
window.cmt20 lines
Window: text, an input box, buttons and a message box (use gui).
// A first window: text, an input box, buttons, a message box
use gui
fun main() {
window = new.window("Hello window", 500, 320)
window.print("Hello from comet!")
window.print("What is your name?", 20, 60)
string name = window.input("name: ", 20, 90)
window.color("green")
window.print("Nice to meet you, " + name + "!", 20, 140)
window.color("light")
window.button("Say hi", 20, 190)
window.button("Quit", 120, 190)
while (window.open()) {
if (window.clicked("Say hi")) { window.alert("Hi, " + name + "!") }
if (window.clicked("Quit")) { break }
window.sleep(0.02)
}
window.close()
}
new.window makes a window; print writes at a position; input shows a box in the window and waits for Enter; button makes buttons and clicked checks them inside the loop, which runs while window.open() is true. Say hi pops up a message box, Quit ends the program. In the playground the window is drawn right in the page.
Commands in this program (12)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.new.window(title, width, height) Opens a new window on the screen and gives it back to you. title is the text in the window's top bar, width and height are its size in pixels (the tiny dots of the screen); leave them out for 640 wide and 480 high. Keep the window in a variable, usually called window: every other window command is written after it, like window.print(...), window.rect(...).window.print(text) / window.print(text, x, y) Writes text inside the window, like printl does in the console. With x and y you choose where: x is how many pixels from the left edge, y how many pixels down from the top edge, and that point is the top-left corner of the text. Without x and y, each print goes on the next line under the last one (or where window.goto said). The text stays there until window.clear().window.input(prompt) / window.input(prompt, x, y) Asks the user to type something. It shows the prompt text with a typing box next to it, waits until the user presses Enter, and gives back what they typed, as text. Your program stops on this line until then. x and y choose where the prompt and box appear.window.color(name) Picks the colour for everything you draw after it: text, lines, rectangles and circles. Think of it as picking up a different pen; it stays until you pick another. The name is a colour word like "red" or "green" (see the colour table), or your own colour as "#rrggbb".window.button(text, x, y) / window.clicked(text) window.button puts a clickable button in the window, with text written on it, at x pixels from the left and y pixels from the top; you make it once. window.clicked("text") tells you whether that button was clicked: it is true one time after each click and false otherwise, so you ask it again and again inside a loop.while (condition) Repeats a block as long as the condition is true. break leaves the loop at once, continue skips to the next round.window.open() / window.wait() / window.close() window.open() is true while the window is still there and turns false when the user closes it; that is why loops say while (window.open()). window.wait() just waits until the user closes the window, for programs that show something and are done. window.close() closes the window from your program.if / else if / else Runs a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.window.alert(text) / window.ask(text) Pop-up messages. window.alert shows a small box with your text and an OK button, and waits until OK is pressed. window.ask shows your question with Yes and No buttons, waits for the answer, and gives back true for Yes and false for No.window.sleep(seconds) Waits a short time while keeping the window alive, and shows what you have drawn so far. In a window loop always use this one, never plain sleep(), because plain sleep freezes the window. window.sleep(0.02) waits 0.02 seconds, which makes 50 pictures (frames) a second: a smaller number makes a game faster.
snake.cmt52 lines
Snake: a whole game in a window (use gui, random).
// Snake: a small game in a window. Arrow keys steer, Escape quits.
use gui, random
fun main() {
size = 20 // one cell in pixels
cols = 24
rows = 18
window = new.window("Snake", cols * size, rows * size)
window.background("black")
snake = [[5, 9], [4, 9], [3, 9]] // head first, each cell is [x, y]
dx = 1
dy = 0
food = [random(0 to cols - 1), random(0 to rows - 1)]
score = 0
while (window.open()) {
if (window.key_down("left") and dx != 1) { dx = -1; dy = 0 }
if (window.key_down("right") and dx != -1) { dx = 1; dy = 0 }
if (window.key_down("up") and dy != 1) { dx = 0; dy = -1 }
if (window.key_down("down") and dy != -1) { dx = 0; dy = 1 }
if (window.key_down("escape")) { break }
head = [snake[0][0] + dx, snake[0][1] + dy]
hit_wall = head[0] < 0 or head[0] >= cols or head[1] < 0 or head[1] >= rows
hit_self = false
for (part in snake) {
if (part[0] == head[0] and part[1] == head[1]) { hit_self = true }
}
if (hit_wall or hit_self) {
window.alert("Game over! Score: " + score)
break
}
snake.insert(0, head)
if (head[0] == food[0] and head[1] == food[1]) {
score += 1
food = [random(0 to cols - 1), random(0 to rows - 1)]
} else {
snake.pop()
}
window.clear()
window.color("red")
window.circle(food[0] * size + size / 2, food[1] * size + size / 2, size / 2 - 2)
window.color("green")
for (part in snake) {
window.rect(part[0] * size + 1, part[1] * size + 1, size - 2, size - 2)
}
window.color("white")
window.print("Score: " + score, 6, 4)
window.sleep(0.12)
}
window.close()
}
The snake is a list of [x, y] cells. Each round reads the arrow keys with key_down, moves the head, checks walls and self-collision, grows or drops the tail, then redraws: clear, a circle for the food, rectangles for the body, the score as text, and window.sleep sets the speed. Click the window first so the keys reach the game.
Commands in this program (20)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.new.window(title, width, height) Opens a new window on the screen and gives it back to you. title is the text in the window's top bar, width and height are its size in pixels (the tiny dots of the screen); leave them out for 640 wide and 480 high. Keep the window in a variable, usually called window: every other window command is written after it, like window.print(...), window.rect(...).window.background(name) Paints the whole window in one colour, behind everything else. Without it the window is dark. Usually you set it once, right after new.window.list [a, b, c] A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.random(a to b) A whole number from a to b, and both ends can come up. This is the one you want for dice, for picking a position, or any "choose a number" job. Every run gives different results.while (condition) Repeats a block as long as the condition is true. break leaves the loop at once, continue skips to the next round.window.open() / window.wait() / window.close() window.open() is true while the window is still there and turns false when the user closes it; that is why loops say while (window.open()). window.wait() just waits until the user closes the window, for programs that show something and are done. window.close() closes the window from your program.if / else if / else Runs a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.window.key_down(name) Tells you whether one key is being held down right now: true while it is held, false when it is not. Use it for movement, so holding an arrow keeps moving. The name is the key's lowercase name, like "left", "up", "space" or "a".for (i in a to b) Repeats a block for every whole number from a up to, but not including, b. Add step to count in other steps (also backwards). for (x in list) goes through a list, a map's keys or a text's characters.window.alert(text) / window.ask(text) Pop-up messages. window.alert shows a small box with your text and an OK button, and waits until OK is pressed. window.ask shows your question with Yes and No buttons, waits for the answer, and gives back true for Yes and false for No.l.insert(i, x) Puts x at position i and moves the rest one step right. insert(0, x) puts it at the front.l.pop() / l.pop(i) Removes an item and gives it back: the last one, or the one at position i. pop with add makes a stack; pop(0) with add makes a queue.window.clear() Wipes the window clean: all text, shapes, pictures and buttons disappear, and only the background colour is left. Moving pictures use it at the start of every frame: clear, draw everything at its new place, then window.sleep shows the new picture all at once, so nothing flickers.window.color(name) Picks the colour for everything you draw after it: text, lines, rectangles and circles. Think of it as picking up a different pen; it stays until you pick another. The name is a colour word like "red" or "green" (see the colour table), or your own colour as "#rrggbb".window.circle(x, y, radius) Draws a filled circle (a disc) in the current colour. x and y are the centre of the circle (not its corner, unlike rect), and radius is how far the edge is from the centre, so the circle is radius * 2 pixels wide. Example: window.circle(200, 150, 30) draws a circle 60 wide around the point 200, 150.window.rect(x, y, width, height) Draws a filled rectangle (a box), filled with the current colour (window.color). x and y say where its top-left corner is: x pixels from the left edge, y pixels down from the top. width says how wide the box is and height how tall, in pixels. Example: window.rect(10, 20, 100, 50) draws a box 100 wide and 50 tall whose corner is 10 from the left and 20 from the top. Use it for walls, bars, buttons, a player, the ground.window.print(text) / window.print(text, x, y) Writes text inside the window, like printl does in the console. With x and y you choose where: x is how many pixels from the left edge, y how many pixels down from the top edge, and that point is the top-left corner of the text. Without x and y, each print goes on the next line under the last one (or where window.goto said). The text stays there until window.clear().window.sleep(seconds) Waits a short time while keeping the window alive, and shows what you have drawn so far. In a window loop always use this one, never plain sleep(), because plain sleep freezes the window. window.sleep(0.02) waits 0.02 seconds, which makes 50 pictures (frames) a second: a smaller number makes a game faster.
flappy.cmt56 lines
Flappy bird: a game with a background image and a bird image (use gui, random).
// Flappy bird: a background image, a bird image and pipes. Space or a click flaps, Escape quits.
use gui, random
struct Pipe {
x = 0
gap = 0
}
fun main() {
width = 480
height = 640
window = new.window("Flappy comet", width, height)
bird_y = 300.0
speed = 0.0
started = false
score = 0
pipes = [Pipe(500, 260)]
while (window.open()) {
key = window.key()
if (key == "escape") { break }
if (key == "space" or window.mouse_down()) {
speed = -6.5
started = true
}
if (started) {
speed += 0.45
bird_y += speed
for (pipe in pipes) { pipe.x -= 3 }
if (pipes[-1].x < 260) { pipes.add(Pipe(500, random(120 to 400))) }
if (pipes[0].x < -60) {
pipes.pop(0)
score += 1
}
}
window.clear()
window.image("city.png", 0, 0, width, height)
window.color("green")
hit = bird_y < 0 or bird_y > height - 36
for (pipe in pipes) {
window.rect(pipe.x, 0, 60, pipe.gap)
window.rect(pipe.x, pipe.gap + 160, 60, height)
if (pipe.x < 108 and pipe.x > 12 and (bird_y < pipe.gap or bird_y + 36 > pipe.gap + 160)) { hit = true }
}
window.image("bird.png", 60, bird_y, 48, 36)
window.color("white")
window.print("Score: {score}", 10, 10)
if (not started) { window.print("Press space or tap to start", 120, 200) }
if (hit) {
window.alert("Game over! Score: {score}")
break
}
window.sleep(0.02)
}
window.close()
}
window.image draws the city as the background and the bird on top with its transparent corners; the files city.png and bird.png sit next to the program (in the playground they are ready to use). key() flaps once per press, gravity adds to the speed each frame, pipes are a list of structs that scroll left, and a hit ends the game with an alert.
Commands in this program (21)
use basic, map, random, chrono, gui The first line of a file says which parts of the language it needs: basic (printing, input, text, numbers, lists, files), map, random, chrono (time and sleep) and gui (windows). A file without any use line gets everything except gui. Fewer modules = a faster compile.struct Name Makes your own kind of value with named fields (and functions inside it, called methods). Name(...) makes one; the values fill the fields in order, missing ones keep their starting value.fun name(a, b) Makes your own function: a named block you can call again and again. Parameters receive the values you call it with; return gives a value back. Every program needs a fun main(), where it starts.new.window(title, width, height) Opens a new window on the screen and gives it back to you. title is the text in the window's top bar, width and height are its size in pixels (the tiny dots of the screen); leave them out for 640 wide and 480 high. Keep the window in a variable, usually called window: every other window command is written after it, like window.print(...), window.rect(...).list [a, b, c] A list holds many values of one kind in order. [] is an empty list, l[0] is the first value, l[-1] the last, len(l) how many there are. See comet help add, comet help pop, comet help sort and friends.while (condition) Repeats a block as long as the condition is true. break leaves the loop at once, continue skips to the next round.window.open() / window.wait() / window.close() window.open() is true while the window is still there and turns false when the user closes it; that is why loops say while (window.open()). window.wait() just waits until the user closes the window, for programs that show something and are done. window.close() closes the window from your program.window.key() Tells you which key was pressed: it gives back the key's name, like "a", "space" or "left", or "" (empty text) if nothing was pressed since you last asked. Each press is given only once, which is right for single actions like jump, pause or quit. Key names are lowercase: letters, digits, enter, space, escape, left, right, up, down, backspace, tab, shift, ctrl, alt, delete, home, end, f1 and so on.if / else if / else Runs a block only when a condition is true. else if tries another condition when the first was false, else runs when none was true. The condition goes in ( ), the block in { }.window.mouse_x() / window.mouse_y() / window.mouse_down() Tell you about the mouse: mouse_x is how many pixels the pointer is from the window's left edge, mouse_y how many from the top edge, and mouse_down is true while the left mouse button is held down. On a phone, a finger touching the window counts as the mouse.for (i in a to b) Repeats a block for every whole number from a up to, but not including, b. Add step to count in other steps (also backwards). for (x in list) goes through a list, a map's keys or a text's characters.l.add(x) Adds an item to the end of the list. push and append are other names for the same thing. An empty list [] takes its kind from the first thing you add.random(a to b) A whole number from a to b, and both ends can come up. This is the one you want for dice, for picking a position, or any "choose a number" job. Every run gives different results.l.pop() / l.pop(i) Removes an item and gives it back: the last one, or the one at position i. pop with add makes a stack; pop(0) with add makes a queue.window.clear() Wipes the window clean: all text, shapes, pictures and buttons disappear, and only the background colour is left. Moving pictures use it at the start of every frame: clear, draw everything at its new place, then window.sleep shows the new picture all at once, so nothing flickers.window.image(file, x, y, width, height) Draws a picture (a png, jpg, bmp or gif file next to your program) in the window. x and y are where its top-left corner goes; width and height stretch it to that size, or leave them out to get the picture's own size. Transparent parts stay see-through. In the playground city.png and bird.png are ready to use, and the Add image button brings in your own.window.color(name) Picks the colour for everything you draw after it: text, lines, rectangles and circles. Think of it as picking up a different pen; it stays until you pick another. The name is a colour word like "red" or "green" (see the colour table), or your own colour as "#rrggbb".window.rect(x, y, width, height) Draws a filled rectangle (a box), filled with the current colour (window.color). x and y say where its top-left corner is: x pixels from the left edge, y pixels down from the top. width says how wide the box is and height how tall, in pixels. Example: window.rect(10, 20, 100, 50) draws a box 100 wide and 50 tall whose corner is 10 from the left and 20 from the top. Use it for walls, bars, buttons, a player, the ground.window.print(text) / window.print(text, x, y) Writes text inside the window, like printl does in the console. With x and y you choose where: x is how many pixels from the left edge, y how many pixels down from the top edge, and that point is the top-left corner of the text. Without x and y, each print goes on the next line under the last one (or where window.goto said). The text stays there until window.clear().window.alert(text) / window.ask(text) Pop-up messages. window.alert shows a small box with your text and an OK button, and waits until OK is pressed. window.ask shows your question with Yes and No buttons, waits for the answer, and gives back true for Yes and false for No.window.sleep(seconds) Waits a short time while keeping the window alive, and shows what you have drawn so far. In a window loop always use this one, never plain sleep(), because plain sleep freezes the window. window.sleep(0.02) waits 0.02 seconds, which makes 50 pictures (frames) a second: a smaller number makes a game faster.