Separate example game to Example.GameLib.

This commit is contained in:
2020-04-20 03:11:23 +02:00
committed by Valeriano A.R
parent 08068a825b
commit 8349b60b34
51 changed files with 829 additions and 935 deletions

59
Example.GameLib/Makefile Normal file
View File

@@ -0,0 +1,59 @@
VERBOSE_BUILD := false
GAMELIB_DIR := ..
GameLibConfig := $(GAMELIB_DIR)/gamelib-config
LIBS := $(shell $(GameLibConfig) --libs)
STATICLIBS := $(shell $(GameLibConfig) --static-libs)
CFLAGS := $(shell $(GameLibConfig) --cflags)
PLATFORM := $(shell $(GameLibConfig) --platform)
EXEEXT := $(shell $(GameLibConfig) --exe-extension)
LDFLAGS :=
RES_GAME := game$(EXEEXT)
BUILDDIR := build-$(PLATFORM)
IsMinGW := $(findstring MINGW,$(shell uname -s)) $(findstring MSYS,$(shell uname -s))
IsDarwin := $(findstring Darwin,$(shell uname -s))
ifneq (,$(IsMinGW))
TARGET_ARCH := mingw
else
ifneq (,$(IsDarwin))
TARGET_ARCH := macosx
else
TARGET_ARCH := linux
endif
endif
ifeq ($(TARGET_ARCH),mingw)
CC := gcc
AR := ar
LAUNCHER :=
RM := rm -rf
MKDIR := mkdir
ECHO := echo
SLASH := /
endif
ifeq ($(TARGET_ARCH),linux)
CC := gcc
AR := ar
LAUNCHER :=
RM := rm -rf
MKDIR := mkdir
ECHO := echo
SLASH := /
endif
ifeq ($(TARGET_ARCH),macosx)
CC := gcc
AR := ar
LAUNCHER :=
RM := rm -rf
MKDIR := mkdir
ECHO := echo
VERBOSE_BUILD := false
SLASH := /
LIBS := $(LIBS) macosx/SDLMain.m
endif
include Makefile.common.mk

View File

@@ -0,0 +1,74 @@
########################
# Utility Declarations #
########################
ifeq ($(VERBOSE_BUILD),true)
DO_CC=$(CC) $(CFLAGS) -o $@ -c $<
DO_CXX=$(CXX) $(CFLAGS) -o $@ -c $<
else
DO_CC=@$(ECHO) "CC: $@" ;\
$(CC) $(CFLAGS) -o $@ -c $<
DO_CXX=@$(ECHO) "CXX: $@" ;\
$(CXX) $(CFLAGS) -o $@ -c $<
endif
#####################
# Game Declarations #
#####################
GAME_HEADS := $(GAMELIB_HEADS) Game$(SLASH)GameEnts.h Game$(SLASH)GameMap.h
GAME_OBJS := \
$(BUILDDIR)$(SLASH)Game.o$(SLASH)GameEnts.o \
$(BUILDDIR)$(SLASH)Game.o$(SLASH)GameMap.o \
$(BUILDDIR)$(SLASH)Game.o$(SLASH)main.o
RES_GAME_OUT := $(BUILDDIR)$(SLASH)$(RES_GAME)
#################
# General Rules #
#################
.FORCE:
(cd $(GAMELIB_DIR) && make lib $(GAMELIB_MAKEPARAMS))
all: .FORCE $(BUILDDIR) $(RES_GAME_OUT)
$(BUILDDIR):
$(MKDIR) $(BUILDDIR)
$(MKDIR) $(BUILDDIR)$(SLASH)Game.o
full-clean: clean
(cd $(GAMELIB_DIR) && make clean $(GAMELIB_MAKEPARAMS))
clean:
$(RM) $(GAME_OBJS) $(RES_GAME_OUT)
run: $(BUILDDIR) $(RES_GAME_OUT)
$(LAUNCHER) ./$(RES_GAME_OUT) debug
rebuild: clean all
##############
# Game Rules #
##############
$(BUILDDIR)$(SLASH)Game.o$(SLASH)GameEnts.o: src$(SLASH)GameEnts.c $(HEADS)
$(DO_CC)
$(BUILDDIR)$(SLASH)Game.o$(SLASH)GameMap.o: src$(SLASH)GameMap.c $(HEADS)
$(DO_CC)
$(BUILDDIR)$(SLASH)Game.o$(SLASH)main.o: src$(SLASH)main.c $(HEADS)
$(DO_CC)
################
# Result Rules #
################
$(RES_GAME_OUT): $(GAME_OBJS)
@$(ECHO) "LINK: $@"
@$(CC) $(GAME_OBJS) $(STATICLIBS) -o $(RES_GAME_OUT) $(LIBS) $(CFLAGS) $(LDFLAGS)

View File

@@ -0,0 +1,31 @@
CC := emcc
AR := emar
LAUNCHER := emrun --port 8080
RM := del
MKDIR := mkdir
ECHO := echo
VERBOSE_BUILD := true
SLASH := \\
GAMELIB_DIR := ..
GAMELIB_MAKEPARAMS := -f Makefile.emscripten.mk target=release
LIBS :=
STATICLIBS := $(GAMELIB_DIR)$(SLASH)build-emscripten$(SLASH)libgame.a
CFLAGS := -s FULL_ES2=1 -s ASM_JS=1 -O1 -Wno-implicit-function-declaration -DEMSCRIPTEN -I$(GAMELIB_DIR)$(SLASH)src
PLATFORM := emscripten
EXEEXT := .html
LDFLAGS := --preload-file data -s TOTAL_MEMORY=134217728 -lidbfs.js
RES_GAME := game$(EXEEXT)
BUILDDIR := build-$(PLATFORM)
ifeq ($(target),release)
CFLAGS := $(CFLAGS) -O2
BUILDDIR := build-emscripten-release
GAMELIB_MAKEPARAMS := -f Makefile.emscripten.mk target=release
endif
include Makefile.common.mk

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@@ -0,0 +1,71 @@
######################
######################
######################
######################
######################
######################
######################
######################
######################
######################
################## ##
###############
#############
#############
##############
########## ###
######### ###
######## ##
######## ##
######## ## |||||
########
#########
##########
###########
############
#############
######## ## #
######### ###
######## ## #
#############
#############
########
##########
########
###########
########
########
############
########
#############
########
########
######## #
######## #
########
########
########
######## P
########
########
########
########
########
########
########
########
#########
########
########
#########
######################
######################
######################
######################
######################
######################
######################
######################
######################
######################

Binary file not shown.

After

Width:  |  Height:  |  Size: 652 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,11 @@
call c:\emsdk\emsdk_env.bat
make -f Makefile.emscripten.mk target=release full-clean
make -f Makefile.emscripten.mk target=release
mkdir DIST\web
copy web\* DIST\web\
copy build-emscripten-release\game.* DIST\web\
pause

View File

@@ -0,0 +1,384 @@
/* SDLMain.m - main entry point for our Cocoa-ized SDL app
Initial Version: Darrell Walisser <dwaliss1@purdue.edu>
Non-NIB-Code & other changes: Max Horn <max@quendi.de>
Feel free to customize this file to suit your needs
*/
#include <SDL/SDL.h>
#import <Cocoa/Cocoa.h>
@interface SDLMain : NSObject
@end
#include <sys/param.h> /* for MAXPATHLEN */
#include <unistd.h>
/* For some reaon, Apple removed setAppleMenu from the headers in 10.4,
but the method still is there and works. To avoid warnings, we declare
it ourselves here. */
@interface NSApplication(SDL_Missing_Methods)
- (void)setAppleMenu:(NSMenu *)menu;
@end
/* Use this flag to determine whether we use SDLMain.nib or not */
#define SDL_USE_NIB_FILE 0
/* Use this flag to determine whether we use CPS (docking) or not */
#define SDL_USE_CPS 1
#ifdef SDL_USE_CPS
/* Portions of CPS.h */
typedef struct CPSProcessSerNum
{
UInt32 lo;
UInt32 hi;
} CPSProcessSerNum;
extern OSErr CPSGetCurrentProcess( CPSProcessSerNum *psn);
extern OSErr CPSEnableForegroundOperation( CPSProcessSerNum *psn, UInt32 _arg2, UInt32 _arg3, UInt32 _arg4, UInt32 _arg5);
extern OSErr CPSSetFrontProcess( CPSProcessSerNum *psn);
#endif /* SDL_USE_CPS */
static int gArgc;
static char **gArgv;
static BOOL gFinderLaunch;
static BOOL gCalledAppMainline = FALSE;
static NSString *getApplicationName(void)
{
const NSDictionary *dict;
NSString *appName = 0;
/* Determine the application name */
dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
if (dict)
appName = [dict objectForKey: @"CFBundleName"];
if (![appName length])
appName = [[NSProcessInfo processInfo] processName];
return appName;
}
#if SDL_USE_NIB_FILE
/* A helper category for NSString */
@interface NSString (ReplaceSubString)
- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString;
@end
#endif
@interface NSApplication (SDLApplication)
@end
@implementation NSApplication (SDLApplication)
/* Invoked from the Quit menu item */
- (void)terminate:(id)sender
{
/* Post a SDL_QUIT event */
SDL_Event event;
event.type = SDL_QUIT;
SDL_PushEvent(&event);
}
@end
/* The main class of the application, the application's delegate */
@implementation SDLMain
/* Set the working directory to the .app's parent directory */
- (void) setupWorkingDirectory:(BOOL)shouldChdir
{
if (shouldChdir)
{
char parentdir[MAXPATHLEN];
CFURLRef url = CFBundleCopyBundleURL(CFBundleGetMainBundle());
CFURLRef url2 = CFURLCreateCopyDeletingLastPathComponent(0, url);
if (CFURLGetFileSystemRepresentation(url2, 1, (UInt8 *)parentdir, MAXPATHLEN)) {
chdir(parentdir); /* chdir to the binary app's parent */
}
CFRelease(url);
CFRelease(url2);
}
}
#if SDL_USE_NIB_FILE
/* Fix menu to contain the real app name instead of "SDL App" */
- (void)fixMenu:(NSMenu *)aMenu withAppName:(NSString *)appName
{
NSRange aRange;
NSEnumerator *enumerator;
NSMenuItem *menuItem;
aRange = [[aMenu title] rangeOfString:@"SDL App"];
if (aRange.length != 0)
[aMenu setTitle: [[aMenu title] stringByReplacingRange:aRange with:appName]];
enumerator = [[aMenu itemArray] objectEnumerator];
while ((menuItem = [enumerator nextObject]))
{
aRange = [[menuItem title] rangeOfString:@"SDL App"];
if (aRange.length != 0)
[menuItem setTitle: [[menuItem title] stringByReplacingRange:aRange with:appName]];
if ([menuItem hasSubmenu])
[self fixMenu:[menuItem submenu] withAppName:appName];
}
}
#else
static void setApplicationMenu(void)
{
/* warning: this code is very odd */
NSMenu *appleMenu;
NSMenuItem *menuItem;
NSString *title;
NSString *appName;
appName = getApplicationName();
appleMenu = [[NSMenu alloc] initWithTitle:@""];
/* Add menu items */
title = [@"About " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
[appleMenu addItem:[NSMenuItem separatorItem]];
title = [@"Hide " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
menuItem = (NSMenuItem *)[appleMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
[appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
[appleMenu addItem:[NSMenuItem separatorItem]];
title = [@"Quit " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
/* Put menu into the menubar */
menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
[menuItem setSubmenu:appleMenu];
[[NSApp mainMenu] addItem:menuItem];
/* Tell the application object that this is now the application menu */
[NSApp setAppleMenu:appleMenu];
/* Finally give up our references to the objects */
[appleMenu release];
[menuItem release];
}
/* Create a window menu */
static void setupWindowMenu(void)
{
NSMenu *windowMenu;
NSMenuItem *windowMenuItem;
NSMenuItem *menuItem;
windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
/* "Minimize" item */
menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
[windowMenu addItem:menuItem];
[menuItem release];
/* Put menu into the menubar */
windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
[windowMenuItem setSubmenu:windowMenu];
[[NSApp mainMenu] addItem:windowMenuItem];
/* Tell the application object that this is now the window menu */
[NSApp setWindowsMenu:windowMenu];
/* Finally give up our references to the objects */
[windowMenu release];
[windowMenuItem release];
}
/* Replacement for NSApplicationMain */
static void CustomApplicationMain (int argc, char **argv)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
SDLMain *sdlMain;
/* Ensure the application object is initialised */
[NSApplication sharedApplication];
#ifdef SDL_USE_CPS
{
CPSProcessSerNum PSN;
/* Tell the dock about us */
if (!CPSGetCurrentProcess(&PSN))
if (!CPSEnableForegroundOperation(&PSN,0x03,0x3C,0x2C,0x1103))
if (!CPSSetFrontProcess(&PSN))
[NSApplication sharedApplication];
}
#endif /* SDL_USE_CPS */
/* Set up the menubar */
[NSApp setMainMenu:[[NSMenu alloc] init]];
setApplicationMenu();
setupWindowMenu();
/* Create SDLMain and make it the app delegate */
sdlMain = [[SDLMain alloc] init];
[NSApp setDelegate:sdlMain];
/* Start the main event loop */
[NSApp run];
[sdlMain release];
[pool release];
}
#endif
/*
* Catch document open requests...this lets us notice files when the app
* was launched by double-clicking a document, or when a document was
* dragged/dropped on the app's icon. You need to have a
* CFBundleDocumentsType section in your Info.plist to get this message,
* apparently.
*
* Files are added to gArgv, so to the app, they'll look like command line
* arguments. Previously, apps launched from the finder had nothing but
* an argv[0].
*
* This message may be received multiple times to open several docs on launch.
*
* This message is ignored once the app's mainline has been called.
*/
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{
const char *temparg;
size_t arglen;
char *arg;
char **newargv;
if (!gFinderLaunch) /* MacOS is passing command line args. */
return FALSE;
if (gCalledAppMainline) /* app has started, ignore this document. */
return FALSE;
temparg = [filename UTF8String];
arglen = SDL_strlen(temparg) + 1;
arg = (char *) SDL_malloc(arglen);
if (arg == NULL)
return FALSE;
newargv = (char **) realloc(gArgv, sizeof (char *) * (gArgc + 2));
if (newargv == NULL)
{
SDL_free(arg);
return FALSE;
}
gArgv = newargv;
SDL_strlcpy(arg, temparg, arglen);
gArgv[gArgc++] = arg;
gArgv[gArgc] = NULL;
return TRUE;
}
/* Called when the internal event loop has just started running */
- (void) applicationDidFinishLaunching: (NSNotification *) note
{
int status;
/* Set the working directory to the .app's parent directory */
[self setupWorkingDirectory:gFinderLaunch];
#if SDL_USE_NIB_FILE
/* Set the main menu to contain the real app name instead of "SDL App" */
[self fixMenu:[NSApp mainMenu] withAppName:getApplicationName()];
#endif
/* Hand off to main application code */
gCalledAppMainline = TRUE;
status = SDL_main (gArgc, gArgv);
/* We're done, thank you for playing */
exit(status);
}
@end
@implementation NSString (ReplaceSubString)
- (NSString *)stringByReplacingRange:(NSRange)aRange with:(NSString *)aString
{
unsigned int bufferSize;
unsigned int selfLen = [self length];
unsigned int aStringLen = [aString length];
unichar *buffer;
NSRange localRange;
NSString *result;
bufferSize = selfLen + aStringLen - aRange.length;
buffer = (unichar *)NSAllocateMemoryPages(bufferSize*sizeof(unichar));
/* Get first part into buffer */
localRange.location = 0;
localRange.length = aRange.location;
[self getCharacters:buffer range:localRange];
/* Get middle part into buffer */
localRange.location = 0;
localRange.length = aStringLen;
[aString getCharacters:(buffer+aRange.location) range:localRange];
/* Get last part into buffer */
localRange.location = aRange.location + aRange.length;
localRange.length = selfLen - localRange.location;
[self getCharacters:(buffer+aRange.location+aStringLen) range:localRange];
/* Build output string */
result = [NSString stringWithCharacters:buffer length:bufferSize];
NSDeallocateMemoryPages(buffer, bufferSize);
return result;
}
@end
#ifdef main
# undef main
#endif
/* Main entry point to executable - should *not* be SDL_main! */
int main (int argc, char **argv)
{
/* Copy the arguments into a global variable */
/* This is passed if we are launched by double-clicking */
if ( argc >= 2 && strncmp (argv[1], "-psn", 4) == 0 ) {
gArgv = (char **) SDL_malloc(sizeof (char *) * 2);
gArgv[0] = argv[0];
gArgv[1] = NULL;
gArgc = 1;
gFinderLaunch = YES;
} else {
int i;
gArgc = argc;
gArgv = (char **) SDL_malloc(sizeof (char *) * (argc+1));
for (i = 0; i <= argc; i++)
gArgv[i] = argv[i];
gFinderLaunch = NO;
}
#if SDL_USE_NIB_FILE
NSApplicationMain (argc, argv);
#else
CustomApplicationMain (argc, argv);
#endif
return 0;
}

View File

@@ -0,0 +1,184 @@
// Copyright (C) 2012 Valeriano Alfonso Rodriguez (Kableado)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "GameLib.h"
extern int gamelib_debug;
#include "GameEnts.h"
DrawImg img_player;
DrawImg img_platform;
DrawImg img_block;
Entity ent_Player;
Entity ent_Platform;
Entity ent_Block;
int EntityApplyGravity(Entity e) {
float grav = 10.0f;
float vTerminal = 50.0f;
vec2 vGrav;
// Only apply gravity to some entity types
if (!(e->type == Ent_Player || 0)) {
return (1);
}
// Apply gravity
vec2_set(vGrav, 0.0f, grav);
Entity_AddVelLimit(e, vGrav, vTerminal);
return (1);
}
void player_proc(Entity e, int ft) {
float acel = 8.0f;
float maxVel = 30.0f;
float jumpVel = 50.0f;
float airMovementFactor = 0.1f;
// Process elasticity
float entityScale[2];
Entity_GetScale(e, entityScale);
entityScale[0] += (1.0f - entityScale[0]) / 2.0f;
entityScale[1] += (1.0f - entityScale[1]) / 2.0f;
Entity_SetScale(e, entityScale);
if (e->A > 0) {
if (Input_GetKey(InputKey_Jump) == InputKey_Pressed ||
Input_GetKey(InputKey_Up) == InputKey_Pressed) {
// Apply jump
if (e->vel[1] > (-jumpVel)) {
e->vel[1] = -jumpVel;
}
Entity_CalcBBox(e);
Entity_SetScale(e, (float[2]){0.6f, 1.4f});
// FIXME: play sound
}
if (Input_GetKey(InputKey_Left)) {
vec2 left;
// Apply left movement
vec2_set(left, -acel, 0.0f);
Entity_AddVelLimit(e, left, maxVel);
}
if (Input_GetKey(InputKey_Right)) {
vec2 right;
// Apply right movement
vec2_set(right, acel, 0.0f);
Entity_AddVelLimit(e, right, maxVel);
}
} else {
if (Input_GetKey(InputKey_Left)) {
vec2 left;
// Apply left movement
vec2_set(left, -(acel * airMovementFactor), 0.0f);
Entity_AddVelLimit(e, left, maxVel * airMovementFactor);
}
if (Input_GetKey(InputKey_Right)) {
vec2 right;
// Apply right movement
vec2_set(right, acel * airMovementFactor, 0.0f);
Entity_AddVelLimit(e, right, maxVel * airMovementFactor);
}
}
if (Input_GetKey(InputKey_Action1) == InputKey_Pressed ||
Input_GetKey(InputKey_Action2) == InputKey_Pressed) {
Entity_SetScale(e, (float[2]){1.0f, 1.0f});
}
e->A = 0;
}
void player_postproc(Entity e, int ft){
// Scroll View
GameLib_MoveToPos(e->pos, 0.6f);
//GameLib_MoveToPos(e->pos, 1.0f);
}
int player_collision(Entity ent, Entity ent2, float t, vec2 n){
if(n[1] < 0 && fabs(n[1]) > fabs(n[0])){
ent->A = 1;
}
if (fabs(n[0]) > fabs(n[1])) {
float intensity = (fabs(ent->vel[0]) - 10.0f) / 40.0f;
if (intensity > 0) {
Entity_SetScale(ent, (float[2]){1.0f - (0.3f * intensity), 1.0f + (0.3f * intensity)});
}
} else {
float intensity = (fabs(ent->vel[1]) - 10.0f) / 40.0f;
if (intensity > 0) {
Entity_SetScale(ent, (float[2]){1.0f + (0.3f * intensity), 1.0f - (0.3f * intensity)});
}
}
return -1;
}
void GameEnts_Init() {
/////////////////////////////
// Load and initialize media.
//
img_player = Draw_LoadImage("data/player.png");
img_platform = Draw_LoadImage("data/platform.png");
img_block = Draw_LoadImage("data/block.png");
/////////////////////////
// Initialize entity types.
//
ent_Player = Entity_New();
ent_Player->type = Ent_Player;
// ent_Player->flags=EntityFlag_Light;
// Entity_SetLight(ent_Player,.2,.2,.2,200);
ent_Player->flags = EntityFlag_Collision | EntityFlag_Overlap;
ent_Player->zorder = 0;
AnimPlay_SetImg(&ent_Player->anim, img_player);
ent_Player->proc = player_proc;
ent_Player->postproc = player_postproc;
ent_Player->collision = player_collision;
ent_Player->mass = 1.0f;
ent_Player->radius = 12;
ent_Player->width = 24;
ent_Player->height = 24;
ent_Player->fric_static = 0.0f;
ent_Player->fric_dynamic = 0.2f;
ent_Platform = Entity_New();
ent_Platform->type = Ent_Platform;
ent_Platform->flags = EntityFlag_PlatformCollision;
ent_Platform->zorder = -1;
AnimPlay_SetImg(&ent_Platform->anim, img_platform);
ent_Platform->mass = 0.0f;
ent_Platform->radius = 12;
ent_Platform->width = 64;
ent_Platform->height = 16;
ent_Platform->fric_static = 0.0f;
ent_Platform->fric_dynamic = 0.2f;
ent_Block = Entity_New();
ent_Block->type = Ent_Block;
ent_Block->flags = EntityFlag_BlockCollision;
ent_Block->zorder = -1;
AnimPlay_SetImg(&ent_Block->anim, img_block);
ent_Block->mass = 0.0f;
ent_Block->radius = 32;
ent_Block->width = 64;
ent_Block->height = 64;
ent_Block->fric_static = 0.0f;
ent_Block->fric_dynamic = 0.2f;
}

View File

@@ -0,0 +1,19 @@
// Copyright (C) 2012 Valeriano Alfonso Rodriguez (Kableado)
#ifndef _GAMEENTS_H_
#define _GAMEENTS_H_
#define Ent_Player 1
#define Ent_Platform 2
#define Ent_Block 3
extern Entity ent_Player;
extern Entity ent_Platform;
extern Entity ent_Block;
int EntityApplyGravity(Entity e);
void GameEnts_Init();
#endif

View File

@@ -0,0 +1,115 @@
// Copyright (C) 2012 Valeriano Alfonso Rodriguez (Kableado)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "GameLib.h"
#include "GameEnts.h"
#include "GameMap.h"
int ReadLine(FILE *f, char *line, int max) {
int c;
int i = 0;
while (i < (max - 1)) {
c = fgetc(f);
if (c == EOF) {
line[i] = 0;
return (-1);
}
if (c == '\r') {
continue;
}
if (c == '\n') {
line[i] = 0;
return (i);
}
line[i] = c;
i++;
}
line[i] = 0;
return (i);
}
Entity GameMapAux_CreateEnt(Entity ent, int i, int j, int res) {
Entity e;
vec2 pos;
e = Entity_Copy(ent);
vec2_set(pos, (res / 2) + i * res, (res / 2) + j * res);
vec2_plus(e->pos, e->pos, pos);
Entity_CalcBBox(e);
GameLib_AddEntity(e);
return (e);
}
#define MaxLineLen 1024
int GameMap_LoadLevel(char *filename, int res) {
FILE *file;
char line[MaxLineLen];
int len, i, j;
int width, height;
char *map;
// Open the file
file = fopen(filename, "rb");
if (!file) {
return (0);
}
// Read the file to determine sizes
width = 0;
height = 0;
do {
len = ReadLine(file, line, MaxLineLen);
if (len > -1) {
if (len > height) {
height = len;
}
width++;
}
} while (len > -1);
fseek(file, 0, SEEK_SET);
// Build the map
map = malloc(sizeof(char) * width * height);
memset(map, 0, width * height);
#define MAP(x, y) map[(x) + ((y)*width)]
j = 0;
do {
len = ReadLine(file, line, MaxLineLen);
for (i = 0; i < len; i++) {
MAP(j, (height - 1) - i) = line[i];
}
j++;
} while (len > -1);
// Close the file
fclose(file);
// Parse the map
for (j = 0; j < height; j++) {
for (i = 0; i < width; i++) {
if (MAP(i, j) == 'P') {
// Player
GameMapAux_CreateEnt(ent_Player, i, j, res);
}
if (MAP(i, j) == '#') {
// Block
GameMapAux_CreateEnt(ent_Block, i, j, res);
}
if (MAP(i, j) == '|') {
// Platform
GameMapAux_CreateEnt(ent_Platform, i, j, res);
}
}
}
// Cleanup
free(map);
#undef MAP
return (1);
}

View File

@@ -0,0 +1,7 @@
// Copyright (C) 2012 Valeriano Alfonso Rodriguez (Kableado)
#ifndef _GAMEMAP_H_
#define _GAMEMAP_H_
int GameMap_LoadLevel(char *filename, int res);
#endif

View File

@@ -0,0 +1,68 @@
// Copyright (C) 2012 Valeriano Alfonso Rodriguez (Kableado)
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "GameLib.h"
extern int gamelib_debug;
#include "GameEnts.h"
#include "GameMap.h"
DrawFnt font;
DrawImg imgBackground;
void MainGame_Text(int x, int y, char *text) {
Draw_SetColor(0.0f, 0.0f, 0.0f, 0.5f);
Draw_DrawText(font, text, x + 1, y + 1);
Draw_SetColor(1.0f, 1.0f, 1.0f, 1.0f);
Draw_DrawText(font, text, x, y);
}
void ProcGame() {}
void PostProcGame() {
// Apply gravity to every entity
GameLib_ForEachEnt(EntityApplyGravity);
}
void PreDrawGame(float f) {}
void DrawGame(float f) { MainGame_Text(8, 8, "Hello world!"); }
int main(int argc, char *argv[]) {
if (argc > 1) {
if (!strcmp(argv[1], "debug")) {
gamelib_debug = 1;
printf("Debug Mode Activated!\n");
}
}
GameLib_Init(640, 480, "Game", 20, 60);
/////////////////////////////
// Load and initialize media.
//
font = Draw_DefaultFont(255, 255, 255, 255);
imgBackground = Draw_LoadImage("data/background.png");
Draw_SetOffset(imgBackground, 0, 0);
GameEnts_Init();
/////////////////////////
// Initialize world.
//
GameLib_DelEnts();
GameMap_LoadLevel("data/level_01.txt", 64);
/////////////////////////
// Run the world.
//
GameLib_CleanParallaxBackgrounds();
GameLib_AddParallaxBackground(imgBackground, (int[2]){512, 512},
(int[2]){0, 0}, (float[2]){0.5f, 0.0f});
GameLib_Loop(ProcGame, PostProcGame, PreDrawGame, DrawGame);
return (0);
}

View File

@@ -0,0 +1,146 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Game</title>
</head>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
font-family: Verdana,Arial,Helvetica,sans-serif;
background-color:#000000;
color: #777777;
font-size: 10pt;
}
h1{
text-align: left;
margin-top: 0;
margin-bottom: 1em;
font-size: 16pt;
font-weight: bold;
}
.header{
margin:0 auto;
width:600px;
padding-top:10px;
text-align:center;
}
.progress-container{
border: 1px solid #808080;
border-radius: 5px;
padding: 5px;
box-shadow: 0px 0px 5px #808080;
width: 600px;
display: block;
margin: 0 auto;
}
.progress-container progress{
width: 100%;
}
.game-screen-container{
display:block;
width: 100%;
padding-top: 10px;
}
.game-screen-container canvas{
border: 1px solid #808080;
border-radius: 5px;
padding: 5px;
box-shadow: 0px 0px 5px #808080;
margin: 0 auto;
}
</style>
<body>
<div class="game-screen-container">
<div id="progress-container" class="progress-container">
<h1>Loading...</h1>
<span>Code:</span></br>
<progress id="progress-code" max="1" value="0"></progress></br>
</br>
<span>Data:</span></br>
<progress id="progress-data" max="1" value="0"></progress></br>
</div>
<div style="width:0;height:0;position:absolute;display:block;overflow:hidden;">
<input type="button" id="btnFocus" value="focus" />
</div>
<canvas class="game-screen" id="canvas" style="display:none;"
oncontextmenu="event.preventDefault()" onclick="document.getElementById('btnFocus').focus();"></canvas>
</div>
<script type='text/javascript'>
var Module = {
preRun: [function (){
FS.mkdir('/saves');
FS.mount(IDBFS, {}, '/saves');
addRunDependency("SaveDir");
FS.syncfs(true, function (err) {
removeRunDependency("SaveDir");
});
}],
postRun: [],
progressContainer: document.getElementById('progress-container'),
progressCode: document.getElementById('progress-code'),
progressData: document.getElementById('progress-data'),
printErr: function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
if(console && console.log){
console.log(text);
}
},
canvas: (function() {
var canvas = document.getElementById('canvas');
// As a default initial behavior, pop up an alert when webgl context is lost. To make your
// application robust, you may want to override this behavior before shipping!
// See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2
canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false);
return canvas;
})(),
setStatus: function(text) {
var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
if(m){
this.progressData.value = parseInt(m[2]);
this.progressData.max = parseInt(m[4]);
}
},
totalDependencies: 0,
monitorRunDependencies: function(left) {
this.totalDependencies = Math.max(this.totalDependencies, left);
if(!left){
// All loaded
this.progressContainer.style.display="none";
this.canvas.style.display="block";
}
},
LaunchCode: function (){
var xhr = new XMLHttpRequest();
xhr.open('GET', "game.js", true);
xhr.responseType = 'text';
xhr.onprogress = function(event) {
this.progressCode.value = event.loaded;
this.progressCode.max = event.total;
}.bind(this);
xhr.onload = function(event) {
var packageData = xhr.response;
// Launch loaded code
try{
eval.call(null,packageData);
}catch(e){
alert("Error "+parent+" "+e);
parent.postMessage("Error","");
}
};
xhr.onerror = function(event) {
alert(event);
};
xhr.send(null);
}
};
Module.LaunchCode();
</script>
</body>
</html>