UFUG2601-OJ 2048 Game
PS:如果读过题了可以跳过题目描述直接到题解部分
链接:UFUG2601-OJ 2048 Game
题目
题目描述
The 2048 game was a popular mini-game back in 2014. The game’s basic concept is merging and summing the numbers of power of 2( 2 N 2^N 2N)
If you are not familiar with the game, you can play a few rounds here:2048 (play2048.co)
In this problem, you will need to emulate the behavior of the game, inferring the final board state from the initialboardstate and the sliding operations.
2048 (video game) - Wikipedia
输入格式
In the first part of the input, there is a4x4 game board with numbers, which represents the initial state of the game.
In the second part of the input, there is an integer N followed by N characters, which represents the sliding operations.
There are four directions of operations, denoted by the characters U (up), D (down), L (left), and R (right).
输出格式
The output of the program should be the final state of the game (4x4) after the inputted operations are performed on the game board.
样例 #1
样例输入 #1
2 4 0 2
0 2 0 2
0 0 2 0
2 2 0 2
1 U
样例输出 #1
4 4 2 4
0 4 0 2
0 0 0 0
0 0 0 0
提示
Please carefully observe the game behaviors, especially the way numbers are merged.
题解
这道题就是大模拟,只要用代码模拟出游戏实际运行的逻辑和动作即可。我的代码思路实在算不上很好,就不仔细讲解了。
就是在此提醒大家,我们学校的评测机不会省略行末空格,一定不要像我一开始一样,把行末空格省掉!
代码实现
//2048 Game
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int a[10][10];
int n;
char o;
int main(){
for(int i=0;i<=3;++i){
for(int j=0;j<=3;++j){
scanf("%d",&a[i][j]);
}
}
scanf("%d",&n);
while(n--){
o=getchar();
o=getchar();
if(o=='U'){
bool b=0;
for(int j=0;j<=3;++j){
int i=0,k=4;
b=0;
while(i<=3){
if(a[i][j]==0){
++i;
}
else{
if(k==4){
k=0;
a[k][j]=a[i][j];
b=1;
}
else{
if(b&&(a[i][j]==a[k][j])){
a[k][j]<<=1;
b=0;
}
else{
a[++k][j]=a[i][j];
b=1;
}
}
if(k!=i){
a[i][j]=0;
}
++i;
}
}
}
}
else if(o=='D'){
bool b=0;
for(int j=0;j<=3;++j){
int i=3,k=4;
b=0;
while(i>=0){
if(a[i][j]==0){
--i;
}
else{
if(k==4){
k=3;
a[k][j]=a[i][j];
b=1;
}
else{
if(b&&(a[i][j]==a[k][j])){
a[k][j]<<=1;
b=0;
}
else{
a[--k][j]=a[i][j];
b=1;
}
}
if(k!=i){
a[i][j]=0;
}
--i;
}
}
}
}
else if(o=='L'){
bool b=0;
for(int i=0;i<=3;++i){
int j=0,k=4;
b=0;
while(j<=3){
if(a[i][j]==0){
++j;
}
else{
if(k==4){
k=0;
a[i][k]=a[i][j];
b=1;
}
else{
if(b&&(a[i][j]==a[i][k])){
a[i][k]<<=1;
b=0;
}
else{
a[i][++k]=a[i][j];
b=1;
}
}
if(k!=j){
a[i][j]=0;
}
++j;
}
}
}
}
else{
bool b=0;
for(int i=0;i<=3;++i){
int j=3,k=4;
b=0;
while(j>=0){
if(a[i][j]==0){
--j;
}
else{
if(k==4){
k=3;
a[i][k]=a[i][j];
b=1;
}
else{
if(b&&(a[i][j]==a[i][k])){
a[i][k]<<=1;
b=0;
}
else{
a[i][--k]=a[i][j];
b=1;
}
}
if(k!=j){
a[i][j]=0;
}
--j;
}
}
}
}
}
for(int i=0;i<=3;++i){
for(int j=0;j<=3;++j){
printf("%d ",a[i][j]);
}
printf("\n");
}
return 0;
}