Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- class Game2048
- {
- public class Coord {
- public int row, col;
- public Coord(int r, int c){
- row = r; col = c;
- }
- }
- public class Tile {
- public int number;
- private Coord location;
- public ConsoleColor color;
- public Tile(int number, Coord location, ConsoleColor color){
- this.number = number;
- this.location = location;
- this.color = color;
- }
- public void print() { // without static, this function needs an instance
- //# letters = "%5d" % board[row][col]
- string letters = string.Format("{0,5}", number);
- //# sys.stdout.write(letters)
- //Console.ForegroundColor = color;
- Console.Write(letters);
- //Console.ForegroundColor = ConsoleColor.Black;
- }
- }
- //# import random
- static Random random = new Random();
- /// <returns>a 2D array for the 2048 board, 4 rows and 4 columns per row.</returns>
- //# def makeBoard():
- public static Tile[][] makeBoard() {
- //# """return a 2D array for the 2048 board, 4 rows and 4 columns per row."""
- //# height, width = 4, 4
- int height = 4, width = 4;
- //# twoDlist = []
- Tile[][] twoDlist = new Tile[height][];
- //# for row in range(height):
- for (int row = 0; row < height; row++) {
- //# twoDlist.append([])
- twoDlist[row] = new Tile[width];
- //# for col in range(width):
- for (int col = 0; col < width; col++){
- //# twoDlist[row].append(0)
- twoDlist [row] [col] = null;
- }
- }
- //# return twoDlist
- return twoDlist;
- }
- //# def printBoard(board):
- /// <summary>print the 2048 board. Each value prints 4 characters wide.</summary>
- /// <param name="board">Board.</param>
- public static void printBoard(Tile[][] board){
- //# """print the 2048 board. Each value prints 4 characters wide."""
- //# import sys
- //# for row in range( len(board) ):
- for(int row = 0; row < board.Length; row++){
- //# for col in range( len(board[row]) ):
- for(int col=0; col < board[row].Length; col++){
- //# if board[row][col] == 0:
- if(board[row][col] == null){
- //# sys.stdout.write(" .")
- Console.Write(" .");
- }
- //# else:
- else {
- board[row][col].print();
- }
- }
- //# sys.stdout.write("\n\n")
- Console.Write("\n\n");
- }
- }
- //# def assignNumbers(board):
- /// <summary>fill the 2048 board with non-zero values, for testing purposes</summary>
- /// <param name="board">Board.</param>
- public static void assignNumbers(Tile[][] board){
- //# """fill the 2048 board with non-zero values, for testing purposes"""
- //# value = 0
- int value = 0;
- //# for row in range( len(board) ):
- for(int row = 0; row < board.Length; row++){
- //# for col in range( len(board[row]) ):
- for(int col = 0; col < board[row].Length; col++){
- //# board[row][col] = value
- board[row][col] = new Tile(value, new Coord(row, col), ConsoleColor.Black);
- //# value += 1
- value ++;
- }
- }
- }
- //# def flipHorizontal(board):
- /// <summary>reverses every row in the 2048 board, so the last elements are first</summary>
- /// <param name="board">Board.</param>
- public static void flipHorizontal(Tile[][] board){
- //# """reverses every row in the 2048 board, so the last elements are first"""
- //# for row in range(len(board)):
- for(int row = 0; row < board.Length; row++){
- //# board[row].reverse()
- System.Array.Reverse(board[row]);
- }
- }
- //# def flipXY(board):
- /// <summary>swaps columns and rows, flipping the board about the x/y diagonal, so upper-right becomes lower-left.</summary>
- /// <param name="board">Board.</param>
- public static void flipXY(Tile[][] board){
- //# """swaps columns and rows, flipping the board about the x/y diagonal, so upper-right becomes lower-left."""
- //# height = len(board)
- int height = board.Length;
- //# width = len(board[0])
- int width = board[0].Length;
- //# for row in range(height):
- for(int row = 0; row < height; row++){
- //# for col in range(row+1):
- for(int col = 0; col < row+1; col++){
- //# temp = board[row][col]
- Tile temp = board[row][col];
- //# board[row][col] = board[col][row]
- board[row][col] = board[col][row];
- //# board[col][row] = temp
- board[col][row] = temp;
- }
- }
- }
- //# def findEmptySpots(board, thingToLookFor = 0):
- /// <returns>a list of row/col pairs where board[row][col] == 0</returns>
- /// <param name="board">Board.</param>
- /// <param name="thingToLookFor">Thing to look for.</param>
- public static List<Coord> findEmptySpots(Tile[][] board, Tile thingToLookFor = null){
- //# """returns a list of row/col pairs where board[row][col] == 0"""
- //# locations = []
- List<Coord> locations = new List<Coord>();
- //# for row in range(len(board)):
- for(int row = 0; row < board.Length; row++){
- //# for col in range(len(board[row])):
- for(int col = 0; col < board[row].Length; col++){
- //# if board[row][col] == thingToLookFor:
- if(board[row][col] == thingToLookFor){
- //# locations.append([row, col]) # add a new list [row, col] to the list
- locations.Add(new Coord(row,col));
- }
- }
- }
- //# return locations
- return locations;
- }
- //# def findRandomEmptySpot(board):
- /// <returns>a randomly chosen row/col pair where board[row][col] == 0 using random.choice(list)
- /// if there is no empty spot in board, return None</returns>
- /// <param name="board">Board.</param>
- public static Coord findRandomEmptySpot(Tile[][] board){
- //# """returns a randomly chosen row/col pair where board[row][col] == 0 using random.choice(list)
- //# if there is no empty spot in board, return None"""
- //# spots = findEmptySpots(board)
- List<Coord> spots = findEmptySpots(board);
- //# if len(spots) == 0:
- if (spots.Count == 0){
- //# return None
- return null;
- }
- //# return random.choice(spots)
- return spots[random.Next(spots.Count)];
- }
- //# def addToRandomSpot(board, value):
- /// <summary>set a random empty spot (row/col) in board to value, and return True
- /// if there are no empty spots in board, return False</summary>
- /// <param name="board">Board.</param>
- /// <param name="value">Value.</param>
- public static bool addToRandomSpot(Tile[][] board, int value){
- //# """set a random empty spot (row/col) in board to value, and return True
- //# if there are no empty spots in board, return False"""
- //# spot = findRandomEmptySpot(board)
- Coord spot = findRandomEmptySpot(board);
- //# if spot != None:
- if (spot != null){
- //# board[spot[0]][spot[1]] = value
- ConsoleColor[] colors = {ConsoleColor.Red, ConsoleColor.Green, ConsoleColor.Blue};
- ConsoleColor color = colors[random.Next() % colors.Length];
- board[spot.row][spot.col] = new Tile(value, new Coord(spot.row, spot.col), color);
- //# return True
- return true;
- }
- //# return False
- return false;
- }
- //# def initializeBoardWith2RandomValues(board):
- public static void initializeBoardWith2RandomValues(Tile[][] board){
- //# import random
- int[] n = new int[]{2,4};
- //# addToRandomSpot(board, random.choice([2,4]))
- addToRandomSpot(board, n[random.Next(n.Length)]);
- //# addToRandomSpot(board, random.choice([2,4]))
- addToRandomSpot(board, n[random.Next(n.Length)]);
- }
- //# def pullRowLeft(row):
- /// <summary>if an element is 0 and the next one isn't 0:
- /// swap them, then return True
- /// if no element in the row could be pulled left, return False</summary>
- /// <returns>returns True if an element could be pulled left, as per rules of 2048.</returns>
- /// <param name="row">Row.</param>
- private static bool pullRowLeft(Tile[] row){
- //# """returns True if an element could be pulled left, as per rules of 2048.
- //# if an element is 0 and the next one isn't 0:
- //# swap them, then return True
- //# if no element in the row could be pulled left, return False"""
- //# for i in range(len(row)-1):
- for(int i = 0; i < row.Length-1; i++){
- //# if row[i] == 0 and row[i+1] != 0:
- if(row[i] == null && row[i+1] != null){
- //# temp = row[i]
- Tile temp = row[i];
- //# row[i] = row[i+1]
- row[i] = row[i+1];
- //# row[i+1] = temp
- row[i+1] = temp;
- //# return True
- return true;
- }
- }
- //# return False
- return false;
- }
- //# def mergeRowLeft(row, startIndex = 0):
- /// <summary>if an element is not 0 and the next element has the same value:
- /// double the element, set next element to 0, return the element index
- /// if no element in the row could be merged left, return -1</summary>
- /// <returns>the index that was merged left, as per the rules of 2048</returns>
- /// <param name="row">a list of elements</param>
- /// <param name="startIndex">which element to start trying to merge (usually 0)</param>
- public static int mergeRowLeft(Tile[] row, int startIndex = 0){
- //# """returns the index that was merged left, as per the rules of 2048
- //# row: a list of elements
- //# startIndex: which element to start trying to merge (usually 0)
- //# if an element is not 0 and the next element has the same value:
- //# double the element, set next element to 0, return the element index
- //# if no element in the row could be merged left, return -1"""
- //# for i in range(startIndex, len(row)-1):
- for(int i = startIndex; i < row.Length-1; i++){
- //# if row[i] != 0 and row[i+1] == row[i]:
- if(row[i] != null && row[i+1] != null && row[i+1].number == row[i].number) {
- //# row[i] = row[i] * 2
- ConsoleColor[] colors = {ConsoleColor.Red, ConsoleColor.Green, ConsoleColor.Blue};
- ConsoleColor color = colors[random.Next() % colors.Length]; // TODO function plz
- row[i] = new Tile(row[i].number * 2, new Coord(-1, i), color);
- //# row[i+1] = 0
- row[i+1] = null;
- //# return i #True
- return i;
- }
- }
- //# return -1 #False
- return -1;
- }
- //# def moveLeft(board):
- /// <summary>pulls and merges elements in the given board to the left, as per 2048.
- //# pull all elements as far left as possible
- //# merges two elements if possible. if a merge happens, pull again.
- //# the same element should never merge more than once during a move</summary>
- /// <returns><c>true</c> if an element could be pulled or merged
- /// <c>false</c> if no element could be pulled or merged</returns>
- /// <param name="board">Board.</param>
- public static bool moveLeft(Tile[][] board){
- //# """pulls and merges elements in the given board to the left, as per 2048.
- //# pull all elements as far left as possible
- //# merges two elements if possible. if a merge happens, pull again.
- //# the same element should never merge more than once during a move
- //# return True if an element could be pulled or merged
- //# return False if no element could be pulled or merged
- //# """
- //# elementCouldBeMergedOrPulled = False
- bool elementCouldBeMergedOrPulled = false;
- //# for r in range(0, len(board)):
- for(int r = 0; r < board.Length; r++){
- //# row = board[r]
- Tile[] row = board[r];
- //# mergeIndex = 0
- int mergeIndex = 0;
- //# aMergeCouldHappen = True
- bool aMergeCouldHappen = true;
- //# while aMergeCouldHappen:
- while (aMergeCouldHappen){
- //# while pullRowLeft(row): elementCouldBeMergedOrPulled = True
- while(pullRowLeft(row)) { elementCouldBeMergedOrPulled = true; }
- //# mergeIndex = mergeRowLeft(row, mergeIndex)
- mergeIndex = mergeRowLeft(row, mergeIndex);
- //# if mergeIndex >= 0:
- if(mergeIndex >= 0) {
- //# elementCouldBeMergedOrPulled = True
- elementCouldBeMergedOrPulled = true;
- }
- //# if mergeIndex == -1:
- if(mergeIndex == -1){
- //# aMergeCouldHappen = False
- aMergeCouldHappen = false;
- }
- //# while pullRowLeft(row): pass
- while(pullRowLeft(row));
- //# mergeIndex += 1
- mergeIndex ++;
- }
- }
- //# return elementCouldBeMergedOrPulled
- return elementCouldBeMergedOrPulled;
- }
- //# def moveRight(board):
- /// <summary>as moveLeft, except the board is flipped horizontally during the move</summary>
- /// <returns><c>true</c>, if right was moved, <c>false</c> otherwise.</returns>
- /// <param name="board">Board.</param>
- public static bool moveRight(Tile[][] board){
- //# """as moveLeft, except the board is flipped horizontally during the move"""
- //# result = False
- bool result = false;
- //# flipHorizontal(board); result = moveLeft(board); flipHorizontal(board)
- flipHorizontal(board); result = moveLeft(board); flipHorizontal(board);
- //# return result
- return result;
- }
- //# def moveUp(board):
- /// <summary>as moveLeft, except board flipped about the x/y diagonal during the move</summary>
- /// <returns><c>true</c>, if up was moved, <c>false</c> otherwise.</returns>
- /// <param name="board">Board.</param>
- public static bool moveUp(Tile[][] board){
- //# """as moveLeft, except board flipped about the x/y diagonal during the move"""
- //# result = False
- bool result = false;
- //# flipXY(board); result = moveLeft(board); flipXY(board)
- flipXY(board); result = moveLeft(board); flipXY(board);
- //# return result
- return result;
- }
- //# def moveDown(board):
- /// <summary>as moveLeft, except board flipped about the x/y diagonal AND horizontally</summary>
- /// <returns><c>true</c>, if down was moved, <c>false</c> otherwise.</returns>
- /// <param name="board">Board.</param>
- public static bool moveDown(Tile[][] board){
- //# """as moveLeft, except board flipped about the x/y diagonal AND horizontally"""
- //# result = False
- bool result = false;
- //# flipXY(board); flipHorizontal(board); result = moveLeft(board);
- flipXY(board); flipHorizontal(board); result = moveLeft(board);
- //# flipHorizontal(board); flipXY(board)
- flipHorizontal(board); flipXY(board);
- //# return result
- return result;
- }
- //# def isMergePossible(board):
- public static bool isMergePossible(Tile[][] board){
- //# height = len(board)
- int height = board.Length;
- //# width = len(board[0])
- int width = board[0].Length;
- //# for row in range(height-1):
- for(int row=0; row < height-1; row++){
- //# for col in range(width-1):
- for(int col=0; col < width-1; col++){
- //# if board[row][col] != 0 and board[row][col] == board[row ][col+1]:
- if(board[row][col] != null && board[row ][col+1] == null
- && board[row][col].number == board[row ][col+1].number) {
- //# return True
- return true;
- }
- //# if board[row][col] != 0 and board[row][col] == board[row+1][col ]:
- if(board[row][col] != null && board[row+1][col ] != null
- && board[row][col].number == board[row+1][col ].number){
- //# return True
- return true;
- }
- }
- }
- //# return False
- return false;
- }
- Tile[][] board;
- //# gameIsRunning = True
- public bool gameIsRunning = true;
- //# moves = {'w':moveUp, 'a':moveLeft, 's':moveDown, 'd':moveRight}
- Dictionary<char,moveFunction> moves = new Dictionary<char, moveFunction>{
- {'w',moveUp}, {'a',moveLeft}, {'s',moveDown}, {'d',moveRight}
- };
- delegate bool moveFunction (Tile[][] board);
- public static void Main (string[] args) {
- //# # initialize the game
- Game2048 g = new Game2048(); // creates an instance of our game
- g.init(); // tells the game to initialize
- g.run (); // tells the game to run
- }
- public void init() {
- //# board = makeBoard()
- board = makeBoard ();
- //# initializeBoardWith2RandomValues(board)
- initializeBoardWith2RandomValues (board);
- }
- void draw() {
- //# print("\033[1;1f") # tell console to move cursor to row1 col1
- //Console.SetCursorPosition(0,0);
- //# printBoard(board)
- printBoard(board);
- }
- char handleInput() {
- //# direction = keyhit.getch() #raw_input("wasd: ")
- char direction = Console.ReadKey().KeyChar;
- return direction;
- }
- public void update(char direction) {
- //# actualThingHappend = False
- bool actualThingHappened = false;
- //# if direction in moves:
- if(moves.ContainsKey(direction)){
- //# actualThingHappend = moves[direction](board)
- actualThingHappened = moves[direction](board);
- }
- //# if actualThingHappend:
- if(actualThingHappened){
- //# addToRandomSpot(board, random.choice([2,4]))
- int[] n = {2,4};
- addToRandomSpot(board, n[random.Next(n.Length)]);
- }
- //# if not actualThingHappend and len(findEmptySpots(board)) == 0 and not isMergePossible(board):
- if(!actualThingHappened && findEmptySpots(board).Count == 0 && !isMergePossible(board)){
- //# gameIsRunning = False
- gameIsRunning = false;
- //# print("GAME OVER")
- Console.WriteLine("GAME OVER");
- }
- //# if direction == 'q': gameIsRunning = False
- if(direction == 'q'){gameIsRunning = false;}
- }
- public void run() {
- while(gameIsRunning){
- draw ();
- update (handleInput ());
- }
- }
- public Coord WhereIs(Tile t) {
- for (int row = 0; row < board.Length; row++) {
- for (int col = 0; col < board [row].Length; col++) {
- if (board [row] [col] == t) {
- return new Coord (row, col);
- }
- }
- }
- return null;
- }
- }
Add Comment
Please, Sign In to add comment