C 语言代码示例,展示了如何实现一个简单的图形化用户界面(GUI)游戏

2023-10-16 08:58:07 浏览数 (2)

C 语言代码示例,展示如何实现一个简单的图形化用户界面(GUI)游戏,使用了图形库 SDL(Simple DirectMedia Layer)和 SDL_image:

代码语言:javascript复制
#include <stdio.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

// 屏幕宽度和高度
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;

// 初始化 SDL,创建窗口和渲染器
void initSDL(SDL_Window** window, SDL_Renderer** renderer) {
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init failed: %s", SDL_GetError());
        exit(EXIT_FAILURE);
    }
    
    *window = SDL_CreateWindow("Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                               SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
    if (*window == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_CreateWindow failed: %s", SDL_GetError());
        exit(EXIT_FAILURE);
    }
    
    *renderer = SDL_CreateRenderer(*window, -1, SDL_RENDERER_ACCELERATED);
    if (*renderer == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_CreateRenderer failed: %s", SDL_GetError());
        exit(EXIT_FAILURE);
    }
    
    SDL_SetRenderDrawColor(*renderer, 0xFF, 0xFF, 0xFF, 0xFF);
    SDL_RenderClear(*renderer);
    SDL_RenderPresent(*renderer);
}

// 释放资源,关闭 SDL
void closeSDL(SDL_Window* window, SDL_Renderer* renderer) {
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
}

int main() {
    SDL_Window* window = NULL;
    SDL_Renderer* renderer = NULL;
    
    initSDL(&window, &renderer);
    
    // 加载游戏背景
    SDL_Srface* backgroundSrface = IMG_Load("background.png");
    if (backgroundSrface == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "IMG_Load failed: %s", IMG_GetError());
        closeSDL(window, renderer);
        exit(EXIT_FAILURE);
    }
    
    SDL_Texture* backgroundTexture = SDL_CreateTextureFromSrface(renderer, backgroundSrface);
    if (backgroundTexture == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_CreateTextureFromSrface failed: %s", SDL_GetError());
        SDL_FreeSrface(backgroundSrface);
        closeSDL(window, renderer);
        exit(EXIT_FAILURE);
    }
    
    SDL_FreeSrface(backgroundSrface);
    
    // 游戏循环
    SDL_Event e;
    int quit = 0;
    while (!quit) {
        while (SDL_PollEvent(&e) != 0) {
            if (e.type == SDL_QUIT) {
                quit = 1;
            }
        }
        
        // 渲染背景
        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, backgroundTexture, NULL, NULL);
        SDL_RenderPresent(renderer);
    }
    
    // 释放资源,关闭 SDL
    SDL_DestroyTexture(backgroundTexture);
    closeSDL(window, renderer);
    
    return 0;
}

使用 SDL 和 SDL_image 库来创建一个简单的图形化界面游戏。定义了以下函数:

  • initSDL:用于初始化 SDL,创建窗口和渲染器。
  • closeSDL:用于释放资源,关闭 SDL。
  • main 函数中,我们先调用 initSDL 进行初始化。然后,我们加载游戏背景图片,并创建相应的纹理和表面。接下来,我们进入游戏循环,不断渲染背景,并监听 SDL_QUIT 事件以判断是否退出游戏。最后,我们释放资源,并调用 closeSDL 关闭 SDL。

0 人点赞