daily pastebin goal
25%
SHARE
TWEET

game2048 py->cs

mvaganov Dec 5th, 2018 16 Never
Upgrade to PRO!
ENDING IN00days00hours00mins00secs
 
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class Game2048
  5. {
  6.     public class Coord {
  7.         public int row, col;
  8.         public Coord(int r, int c){
  9.             row = r; col = c;
  10.         }
  11.     }
  12.  
  13.     //# import random
  14.     static Random random = new Random();
  15.  
  16.     /// <returns>a 2D array for the 2048 board, 4 rows and 4 columns per row.</returns>
  17.     //# def makeBoard():
  18.     public static int[][] makeBoard() {
  19.         //# """return a 2D array for the 2048 board, 4 rows and 4 columns per row."""
  20.         //# height, width = 4, 4
  21.         int height = 4, width = 4;
  22.         //# twoDlist = []
  23.         int[][] twoDlist = new int[height][];
  24.         //# for row in range(height):
  25.         for (int row = 0; row < height; row++) {
  26.             //# twoDlist.append([])
  27.             twoDlist[row] = new int[width];
  28.             //# for col in range(width):
  29.             for (int col = 0; col < width; col++){
  30.                 //# twoDlist[row].append(0)
  31.                 twoDlist [row] [col] = 0;
  32.             }
  33.         }
  34.         //# return twoDlist
  35.         return twoDlist;
  36.     }
  37.     //# def printBoard(board):
  38.     /// <summary>print the 2048 board. Each value prints 4 characters wide.</summary>
  39.     /// <param name="board">Board.</param>
  40.     public static void printBoard(int[][] board){
  41.         //# """print the 2048 board. Each value prints 4 characters wide."""
  42.         //# import sys
  43.         //# for row in range( len(board) ):
  44.         for(int row = 0; row < board.Length; row++){
  45.             //# for col in range( len(board[row]) ):
  46.             for(int col=0; col < board[row].Length; col++){
  47.                 //# if board[row][col] == 0:
  48.                 if(board[row][col] == 0){
  49.                     //# sys.stdout.write("    .")
  50.                     Console.Write("    .");
  51.                 }
  52.                 //# else:
  53.                 else {
  54.                     //# letters = "%5d" % board[row][col]
  55.                     string letters = string.Format("{0,5}", board[row][col]);
  56.                     //# sys.stdout.write(letters)
  57.                     Console.Write(letters);
  58.                 }
  59.             }
  60.             //# sys.stdout.write("\n\n")
  61.             Console.Write("\n\n");
  62.         }
  63.     }
  64.     //# def assignNumbers(board):
  65.     /// <summary>fill the 2048 board with non-zero values, for testing purposes</summary>
  66.     /// <param name="board">Board.</param>
  67.     public static void assignNumbers(int[][] board){
  68.         //# """fill the 2048 board with non-zero values, for testing purposes"""
  69.         //# value = 0
  70.         int value = 0;
  71.         //# for row in range( len(board) ):
  72.         for(int row = 0; row < board.Length; row++){
  73.             //# for col in range( len(board[row]) ):
  74.             for(int col = 0; col < board[row].Length; col++){
  75.                 //# board[row][col] = value
  76.                 board[row][col] = value;
  77.                 //# value += 1
  78.                 value ++;
  79.             }
  80.         }
  81.     }
  82.     //# def flipHorizontal(board):
  83.     /// <summary>reverses every row in the 2048 board, so the last elements are first</summary>
  84.     /// <param name="board">Board.</param>
  85.     public static void flipHorizontal(int[][] board){
  86.         //# """reverses every row in the 2048 board, so the last elements are first"""
  87.         //# for row in range(len(board)):
  88.         for(int row = 0; row < board.Length; row++){
  89.             //# board[row].reverse()
  90.             System.Array.Reverse(board[row]);
  91.         }
  92.     }
  93.     //# def flipXY(board):
  94.     /// <summary>swaps columns and rows, flipping the board about the x/y diagonal, so upper-right becomes lower-left.</summary>
  95.     /// <param name="board">Board.</param>
  96.     public static void flipXY(int[][] board){
  97.         //# """swaps columns and rows, flipping the board about the x/y diagonal, so upper-right becomes lower-left."""
  98.         //# height = len(board)
  99.         int height = board.Length;
  100.         //# width = len(board[0])
  101.         int width = board[0].Length;
  102.         //# for row in range(height):
  103.         for(int row = 0; row < height; row++){
  104.             //# for col in range(row+1):
  105.             for(int col = 0; col < row+1; col++){
  106.                 //# temp = board[row][col]
  107.                 int temp = board[row][col];
  108.                 //# board[row][col] = board[col][row]
  109.                 board[row][col] = board[col][row];
  110.                 //# board[col][row] = temp
  111.                 board[col][row] = temp;
  112.             }
  113.         }
  114.     }
  115.     //# def findEmptySpots(board, thingToLookFor = 0):
  116.     /// <returns>a list of row/col pairs where board[row][col] == 0</returns>
  117.     /// <param name="board">Board.</param>
  118.     /// <param name="thingToLookFor">Thing to look for.</param>
  119.     public static List<Coord> findEmptySpots(int[][] board, int thingToLookFor = 0){
  120.         //# """returns a list of row/col pairs where board[row][col] == 0"""
  121.         //# locations = []
  122.         List<Coord> locations = new List<Coord>();
  123.         //# for row in range(len(board)):
  124.         for(int row = 0; row < board.Length; row++){
  125.             //# for col in range(len(board[row])):
  126.             for(int col = 0; col < board[row].Length; col++){
  127.                 //# if board[row][col] == thingToLookFor:
  128.                 if(board[row][col] == thingToLookFor){
  129.                     //# locations.append([row, col]) # add a new list [row, col] to the list
  130.                     locations.Add(new Coord(row,col));
  131.                 }
  132.             }
  133.         }
  134.         //# return locations
  135.         return locations;
  136.     }
  137.     //# def findRandomEmptySpot(board):
  138.     /// <returns>a randomly chosen row/col pair where board[row][col] == 0 using random.choice(list)
  139.     /// if there is no empty spot in board, return None</returns>
  140.     /// <param name="board">Board.</param>
  141.     public static Coord findRandomEmptySpot(int[][] board){
  142.         //# """returns a randomly chosen row/col pair where board[row][col] == 0 using random.choice(list)
  143.         //# if there is no empty spot in board, return None"""
  144.         //# spots = findEmptySpots(board)
  145.         List<Coord> spots = findEmptySpots(board);
  146.         //# if len(spots) == 0:
  147.         if (spots.Count == 0){
  148.             //# return None
  149.             return null;
  150.         }
  151.         //# return random.choice(spots)
  152.         return spots[random.Next(spots.Count)];
  153.     }
  154.     //# def addToRandomSpot(board, value):
  155.     /// <summary>set a random empty spot (row/col) in board to value, and return True
  156.     /// if there are no empty spots in board, return False</summary>
  157.     /// <param name="board">Board.</param>
  158.     /// <param name="value">Value.</param>
  159.     public static bool addToRandomSpot(int[][] board, int value){
  160.         //# """set a random empty spot (row/col) in board to value, and return True
  161.         //# if there are no empty spots in board, return False"""
  162.         //# spot = findRandomEmptySpot(board)
  163.         Coord spot = findRandomEmptySpot(board);
  164.         //# if spot != None:
  165.         if (spot != null){
  166.             //# board[spot[0]][spot[1]] = value
  167.             board[spot.row][spot.col] = value;
  168.             //# return True
  169.             return true;
  170.         }
  171.         //# return False
  172.         return false;
  173.     }
  174.     //# def initializeBoardWith2RandomValues(board):
  175.     public static void initializeBoardWith2RandomValues(int[][] board){
  176.         //# import random
  177.         int[] n = new int[]{2,4};
  178.         //# addToRandomSpot(board, random.choice([2,4]))
  179.         addToRandomSpot(board, n[random.Next(n.Length)]);
  180.         //# addToRandomSpot(board, random.choice([2,4]))
  181.         addToRandomSpot(board, n[random.Next(n.Length)]);
  182.     }
  183.  
  184.     //# def pullRowLeft(row):
  185.     /// <summary>if an element is 0 and the next one isn't 0:
  186.     ///     swap them, then return True
  187.     /// if no element in the row could be pulled left, return False</summary>
  188.     /// <returns>returns True if an element could be pulled left, as per rules of 2048.</returns>
  189.     /// <param name="row">Row.</param>
  190.     public static bool pullRowLeft(int[] row){
  191.         //# """returns True if an element could be pulled left, as per rules of 2048.
  192.         //# if an element is 0 and the next one isn't 0:
  193.         //# swap them, then return True
  194.         //# if no element in the row could be pulled left, return False"""
  195.         //# for i in range(len(row)-1):
  196.         for(int i = 0; i < row.Length-1; i++){
  197.             //# if row[i] == 0 and row[i+1] != 0:
  198.             if(row[i] == 0 && row[i+1] != 0){
  199.                 //# temp = row[i]
  200.                 int temp = row[i];
  201.                 //# row[i] = row[i+1]
  202.                 row[i] = row[i+1];
  203.                 //# row[i+1] = temp
  204.                 row[i+1] = temp;
  205.                 //# return True
  206.                 return true;
  207.             }
  208.         }
  209.         //# return False
  210.         return false;
  211.     }
  212.     //# def mergeRowLeft(row, startIndex = 0):
  213.     /// <summary>if an element is not 0 and the next element has the same value:
  214.     ///     double the element, set next element to 0, return the element index
  215.     /// if no element in the row could be merged left, return -1</summary>
  216.     /// <returns>the index that was merged left, as per the rules of 2048</returns>
  217.     /// <param name="row">a list of elements</param>
  218.     /// <param name="startIndex">which element to start trying to merge (usually 0)</param>
  219.     public static int mergeRowLeft(int[] row, int startIndex = 0){
  220.         //# """returns the index that was merged left, as per the rules of 2048
  221.         //# row: a list of elements
  222.         //# startIndex: which element to start trying to merge (usually 0)
  223.         //# if an element is not 0 and the next element has the same value:
  224.         //# double the element, set next element to 0, return the element index
  225.         //# if no element in the row could be merged left, return -1"""
  226.         //# for i in range(startIndex, len(row)-1):
  227.         for(int i = startIndex; i < row.Length-1; i++){
  228.             //# if row[i] != 0 and row[i+1] == row[i]:
  229.             if(row[i] != 0 && row[i+1] == row[i]){
  230.                 //# row[i] = row[i] * 2
  231.                 row[i] = row[i] * 2;
  232.                 //# row[i+1] = 0
  233.                 row[i+1] = 0;
  234.                 //# return i #True
  235.                 return i;
  236.             }
  237.         }
  238.         //# return -1 #False
  239.         return -1;
  240.     }
  241.     //# def moveLeft(board):
  242.     /// <summary>pulls and merges elements in the given board to the left, as per 2048.
  243.     //# pull all elements as far left as possible
  244.     //# merges two elements if possible. if a merge happens, pull again.
  245.     //# the same element should never merge more than once during a move</summary>
  246.     /// <returns><c>true</c> if an element could be pulled or merged
  247.     /// <c>false</c> if no element could be pulled or merged</returns>
  248.     /// <param name="board">Board.</param>
  249.     public static bool moveLeft(int[][] board){
  250.         //# """pulls and merges elements in the given board to the left, as per 2048.
  251.         //# pull all elements as far left as possible
  252.         //# merges two elements if possible. if a merge happens, pull again.
  253.         //# the same element should never merge more than once during a move
  254.         //# return True if an element could be pulled or merged
  255.         //# return False if no element could be pulled or merged
  256.         //# """
  257.         //# elementCouldBeMergedOrPulled = False
  258.         bool elementCouldBeMergedOrPulled = false;
  259.         //# for r in range(0, len(board)):
  260.         for(int r = 0; r < board.Length; r++){
  261.             //# row = board[r]
  262.             int[] row = board[r];
  263.             //# mergeIndex = 0
  264.             int mergeIndex = 0;
  265.             //# aMergeCouldHappen = True
  266.             bool aMergeCouldHappen = true;
  267.             //# while aMergeCouldHappen:
  268.             while (aMergeCouldHappen){
  269.                 //# while pullRowLeft(row): elementCouldBeMergedOrPulled = True
  270.                 while(pullRowLeft(row)) { elementCouldBeMergedOrPulled = true; }
  271.                 //# mergeIndex = mergeRowLeft(row, mergeIndex)
  272.                 mergeIndex = mergeRowLeft(row, mergeIndex);
  273.                 //# if mergeIndex >= 0:
  274.                 if(mergeIndex >= 0) {
  275.                     //# elementCouldBeMergedOrPulled = True
  276.                     elementCouldBeMergedOrPulled = true;
  277.                 }
  278.                 //# if mergeIndex == -1:
  279.                 if(mergeIndex == -1){
  280.                     //# aMergeCouldHappen = False
  281.                     aMergeCouldHappen = false;
  282.                 }
  283.                 //# while pullRowLeft(row): pass
  284.                 while(pullRowLeft(row));
  285.                 //# mergeIndex += 1
  286.                 mergeIndex ++;
  287.             }
  288.         }
  289.         //# return elementCouldBeMergedOrPulled
  290.         return elementCouldBeMergedOrPulled;
  291.     }
  292.     //# def moveRight(board):
  293.     /// <summary>as moveLeft, except the board is flipped horizontally during the move</summary>
  294.     /// <returns><c>true</c>, if right was moved, <c>false</c> otherwise.</returns>
  295.     /// <param name="board">Board.</param>
  296.     public static bool moveRight(int[][] board){
  297.         //# """as moveLeft, except the board is flipped horizontally during the move"""
  298.         //# result = False
  299.         bool result = false;
  300.         //# flipHorizontal(board); result = moveLeft(board); flipHorizontal(board)
  301.         flipHorizontal(board); result = moveLeft(board); flipHorizontal(board);
  302.         //# return result
  303.         return result;
  304.     }
  305.     //# def moveUp(board):
  306.     /// <summary>as moveLeft, except board flipped about the x/y diagonal during the move</summary>
  307.     /// <returns><c>true</c>, if up was moved, <c>false</c> otherwise.</returns>
  308.     /// <param name="board">Board.</param>
  309.     public static bool moveUp(int[][] board){
  310.         //# """as moveLeft, except board flipped about the x/y diagonal during the move"""
  311.         //# result = False
  312.         bool result = false;
  313.         //# flipXY(board); result = moveLeft(board); flipXY(board)
  314.         flipXY(board); result = moveLeft(board); flipXY(board);
  315.         //# return result
  316.         return result;
  317.     }
  318.     //# def moveDown(board):
  319.     /// <summary>as moveLeft, except board flipped about the x/y diagonal AND horizontally</summary>
  320.     /// <returns><c>true</c>, if down was moved, <c>false</c> otherwise.</returns>
  321.     /// <param name="board">Board.</param>
  322.     public static bool moveDown(int[][] board){
  323.         //# """as moveLeft, except board flipped about the x/y diagonal AND horizontally"""
  324.         //# result = False
  325.         bool result = false;
  326.         //# flipXY(board); flipHorizontal(board); result = moveLeft(board);
  327.         flipXY(board); flipHorizontal(board); result = moveLeft(board);
  328.         //# flipHorizontal(board); flipXY(board)
  329.         flipHorizontal(board); flipXY(board);
  330.         //# return result
  331.         return result;
  332.     }
  333.     //# def isMergePossible(board):
  334.     public static bool isMergePossible(int[][] board){
  335.         //# height = len(board)
  336.         int height = board.Length;
  337.         //# width = len(board[0])
  338.         int width = board[0].Length;
  339.         //# for row in range(height-1):
  340.         for(int row=0; row < height-1; row++){
  341.             //# for col in range(width-1):
  342.             for(int col=0; col < width-1; col++){
  343.                 //# if board[row][col] != 0 and board[row][col] == board[row  ][col+1]:
  344.                 if(board[row][col] != 0 && board[row][col] == board[row  ][col+1]) {
  345.                     //# return True
  346.                     return true;
  347.                 }
  348.                 //# if board[row][col] != 0 and board[row][col] == board[row+1][col  ]:
  349.                 if(board[row][col] != 0 && board[row][col] == board[row+1][col  ]){
  350.                     //# return True
  351.                     return true;
  352.                 }
  353.             }
  354.         }
  355.         //# return False
  356.         return false;
  357.     }
  358.  
  359.     delegate bool moveFunction (int[][] board);
  360.     public static void Main (string[] args) {
  361.         //# # initialize the game
  362.         //# board = makeBoard()
  363.         int[][] board = makeBoard();
  364.         //# initializeBoardWith2RandomValues(board)
  365.         initializeBoardWith2RandomValues(board);
  366.         //# import keyhit
  367.         //# # game loop
  368.         //# gameIsRunning = True
  369.         bool gameIsRunning = true;
  370.         //# moves = {'w':moveUp, 'a':moveLeft, 's':moveDown, 'd':moveRight}
  371.         Dictionary<char,moveFunction> moves = new Dictionary<char, moveFunction>{
  372.             {'w',moveUp}, {'a',moveLeft}, {'s',moveDown}, {'d',moveRight}
  373.         };
  374.         //# while gameIsRunning:
  375.         while(gameIsRunning){
  376.             //# # draw the game
  377.             //# print("\033[1;1f") # tell console to move cursor to row1 col1
  378.             Console.SetCursorPosition(0,0);
  379.             //# printBoard(board)
  380.             printBoard(board);
  381.             //# # get input from the user
  382.             //# direction = keyhit.getch() #raw_input("wasd: ")
  383.             char direction = Console.ReadKey().KeyChar;
  384.             //# # update the game based on user input
  385.             //# actualThingHappend = False
  386.             bool actualThingHappened = false;
  387.             //# if direction in moves:
  388.             if(moves.ContainsKey(direction)){
  389.                 //# actualThingHappend = moves[direction](board)
  390.                 actualThingHappened = moves[direction](board);
  391.             }
  392.             //# if actualThingHappend:
  393.             if(actualThingHappened){
  394.                 //# addToRandomSpot(board, random.choice([2,4]))
  395.                 int[] n = {2,4};
  396.                 addToRandomSpot(board, n[random.Next(n.Length)]);
  397.             }
  398.             //# if not actualThingHappend and len(findEmptySpots(board)) == 0 and not isMergePossible(board):
  399.             if(!actualThingHappened && findEmptySpots(board).Count == 0 && !isMergePossible(board)){
  400.                 //# gameIsRunning = False
  401.                 gameIsRunning = false;
  402.                 //# print("GAME OVER")
  403.                 Console.WriteLine("GAME OVER");
  404.             }
  405.             //# if direction == 'q': gameIsRunning = False
  406.             if(direction == 'q'){gameIsRunning = false;}
  407.         }
  408.     }
  409. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top