下面是一个简单的俄罗斯方块的C语言代码示例,仅供参考:
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- #define BOARD_WIDTH 20
- #define BOARD_HEIGHT 10
- int board[BOARD_HEIGHT][BOARD_WIDTH] = {0};
- void drawBoard() {
- int i, j;
- for (i = 0; i < BOARD_HEIGHT; i++) {
- for (j = 0; j < BOARD_WIDTH; j++) {
- printf("%d ", board[i][j]);
- }
- printf("\n");
- }
- }
- void dropDown(int row) {
- int i;
- for (i = row; i >= 0; i--) {
- board[i][BOARD_WIDTH-1] = board[i+1][BOARD_WIDTH-1];
- }
- }
- void moveLeft(int row) {
- int i, temp;
- for (i = 0; i < BOARD_WIDTH-1; i++) {
- temp = board[row][i];
- board[row][i] = board[row][i+1];
- board[row][i+1] = temp;
- }
- }
- void moveRight(int row) {
- int i, temp;
- for (i = BOARD_WIDTH-1; i > 0; i--) {
- temp = board[row][i];
- board[row][i] = board[row][i-1];
- board[row][i-1] = temp;
- }
- }
- void rotate(int row) {
- int i, temp;
- for (i = 0; i < BOARD_WIDTH/2; i++) {
- temp = board[row][i];
- board[row][i] = board[row][BOARD_WIDTH-1-i];
- board[row][BOARD_WIDTH-1-i] = temp;
- }
- }
- int checkGameOver() {
- int i, j;
- for (i = BOARD_HEIGHT-1; i >= 0; i--) {
- for (j = BOARD_WIDTH-1; j >= 0; j--) {
- if (board[i][j] == 1) {
- return 0; // Game over if a block is touching the top of the board
- }
- }
- }
- return 1; // Game over if no blocks are touching the top of the board
- }
好的,以下是俄罗斯方块游戏的继续代码:
- int main() {
- int row = BOARD_HEIGHT-1; // Current row of the falling block
- int i, j;
- char ch;
- int score = 0;
- while (1) { // Main game loop
- dropDown(row);
- if (checkGameOver()) {
- printf("Game Over! Your score is %d.\n", score);
- break;
- }
- drawBoard();
- ch = getch(); // Wait for user input
- switch (ch) {
- case 'a': // Left arrow key pressed
- moveLeft(row);
- break;
- case 'd': // Right arrow key pressed
- moveRight(row);
- break;
- case 'x': // Up arrow key pressed
- rotate(row);
- break;
- case ' ': // Space key pressed: drop the block downwards
- dropDown(row);
- score += 10;
- break;
- }
- row++; // Move the block one row downwards if it's still within the board
- if (row >= BOARD_HEIGHT) {
- row = 0; // If the block has reached the bottom of the board, reset it to the top of the board
- }
- }
- return 0;
- }
这段代码是游戏的主循环,它会不断地让方块下落,然后等待用户输入来控制方块的移动和旋转。如果方块触碰到了顶部,游戏就结束,否则游戏会继续进行。在每次方块下落时,用户的得分会增加10分。当方块到达了底部时,它会被重置到顶部。