2048/2048.bqn

41 lines
1.8 KiB
BQN
Raw Permalink Normal View History

2023-01-03 20:46:46 +01:00
#!/usr/bin/env BQN
2023-01-03 22:17:28 +01:00
# 2048 game
2023-01-03 20:46:46 +01:00
# The game is controlled with the vim movement keys:
2023-01-03 22:17:28 +01:00
# h: left, j: down, k: up, l: right, q: quit
# needs a VT-100 compatible terminal
2023-01-03 20:46:46 +01:00
Merge{𝕩 0/ m<`=«𝕩 4(¬»m)/𝕩×1+m} # Merge a single row to the right
StepMerge˘ # Merges each row of the board
UpStep() # Each direction merges the board
2023-01-03 22:42:12 +01:00
DownStep # by rotating it to the correct orientation, merging the rows
RightStep # and reversing the rotation
2023-01-03 20:46:46 +01:00
LeftStep(˘)
2023-01-03 22:42:12 +01:00
# Spawns a 2 or a 4 (10% chance) at a random empty position
Spawn{i•rand.Range(0= / )𝕩 (•rand.Range91/24)(i) 𝕩}
2023-01-03 20:46:46 +01:00
LoseLeftRightDownUp # Losing condition, no moves change the board
Win´·˝2048= # Winning condition, 2048!
2023-01-03 22:17:28 +01:00
Quit{•Out e"[?12l"e"[?25h" •Exit 𝕩} # Restores the terminal and exits
2023-01-03 22:42:12 +01:00
Display{ # Displays the board, score and controls
•Out e"[H"e"[2J" # Cursor to origin and clear screen
2023-01-03 20:46:46 +01:00
•Out "Controls: h: left, j: down, k: up, l: right, q: quit"
2023-01-03 22:42:12 +01:00
•Show 𝕩
•Out "score: "•Repr ´˝ 𝕩
}
2023-01-03 22:42:12 +01:00
boardSpawn 440
e@+27 # Escape character for the ANSI escape codes
•term.RawMode 1
•Out e"[?25l"e"[2J"e"[H" # Cursor to origin, hide it and clear screen
{𝕤
Display board
{𝕤•Out "You win!" Quit 0}Win board
{𝕤•Out "You lose!" Quit 1}Lose board
key•term.CharB @ # Read key
key"hjklq"? # Valid key?
{𝕤 Quit 0}(key='q')@ # Quit key?
move(key="hjkl")/LeftDownUpRight # Get movement function from the key
{𝕤boardSpawnMove 𝕩}(Move) board # Generate the next board if the move is valid
; @
2023-01-03 22:17:28 +01:00
}•_While_{𝕤1}@