- Fixed MP3 play bug on the psp. MP3 files need to have NO Id3v2 tag, or they won't play. Also, volume control is broken
- added dt to moving W's easter egg movement.
- Added fullscreen for windows version
- other stuff ?
This commit is contained in:
wagic.the.homebrew
2008-11-19 12:21:23 +00:00
parent 2434571fa2
commit 349de34106
27 changed files with 1270 additions and 1012 deletions

View File

@@ -12,7 +12,7 @@ OBJS = src/JApp.o src/JGBKFont.o \
src/tinyxml/tinystr.o src/tinyxml/tinyxml.o \ src/tinyxml/tinystr.o src/tinyxml/tinyxml.o \
src/tinyxml/tinyxmlparser.o src/tinyxml/tinyxmlerror.o \ src/tinyxml/tinyxmlparser.o src/tinyxml/tinyxmlerror.o \
src/main.o src/vram.o \ src/main.o src/vram.o \
src/JAudio.o src/JCooleyesMP3.o \ src/JAudio.o src/JMP3.o \
src/decoder_prx.o \ src/decoder_prx.o \
src/Encoding.o src/JTTFont.o \ src/Encoding.o src/JTTFont.o \
src/JMD2Model.o src/JOBJModel.o \ src/JMD2Model.o src/JOBJModel.o \
@@ -23,7 +23,7 @@ LIBDIR = lib/psp
CFLAGS = -O2 -G0 -Wall -DDEVHOOK -DPSPFW3XX CFLAGS = -O2 -G0 -Wall -DDEVHOOK -DPSPFW3XX
LIBS = -lgif -lfreetype -ljpeg -lpng -lz -lmikmod -lpsppower -lpspmpeg -lpspaudiocodec -lpspaudiolib -lpspaudio -lpspgum -lpspgu -lpsprtc -lm -lstdc++ LIBS = -lgif -lfreetype -ljpeg -lpng -lz -lmikmod -lpsppower -lpspmpeg -lpspaudiocodec -lpspaudiolib -lpspaudio -lpspmp3 -lpspgum -lpspgu -lpsprtc -lm -lstdc++
include $(PSPSDK)/lib/build.mak include $(PSPSDK)/lib/build.mak

View File

@@ -73,15 +73,15 @@ void setChannelFlag(int channel, int flag);
#define SAMPLE_PER_FRAME 1152 #define SAMPLE_PER_FRAME 1152
#define MAX_MP3_FILE 2 #define MAX_MP3_FILE 2
class JCooleyesMP3; class JMP3;
void PlayMP3(JCooleyesMP3 *mp3, bool looping = false); void PlayMP3(JMP3 *mp3, bool looping = false);
void StopMP3(); void StopMP3();
void ResumeMP3(); void ResumeMP3(JMP3 *mp3);
bool InitMP3Decoder();
void ReleaseMP3Decoder(); void ReleaseMP3Decoder();
void MP3AudioOutCallback(void* buf, unsigned int length, void *userdata); void MP3AudioOutCallback(void* buf, unsigned int length, void *userdata);
int decodeThread2(SceSize args, void *argp);
extern bool g_MP3DecoderOK; extern bool g_MP3DecoderOK;
#endif #endif

59
JGE/include/JMP3.h Normal file
View File

@@ -0,0 +1,59 @@
//-------------------------------------------------------------------------------------
//
// JGE is a hardware accelerated 2D game SDK for PSP/Windows.
//
// Licensed under the BSD license, see LICENSE in JGE root for details.
//
// Copyright (c) 2007 James Hui (a.k.a. Dr.Watson) <jhkhui@gmail.com>
// Copyright (c) 2008 Alexander Berl <raphael@fx-world.org>
// Copyright (c) 2008 WilLoW :--) <wagic.the.homebrew@gmail.com>
//
//-------------------------------------------------------------------------------------
#ifndef _JMP3_
#define _JMP3_
#include <string>
class JMP3
{
protected:
static bool loadModules();
int m_volume;
int m_samplesPlayed;
int m_inBufferSize, m_outBufferSize;
char m_inBuffer[16*1024]; // ?
short m_outBuffer[16*(1152/2)]; //?
int m_numChannels;
int m_samplingRate;
bool m_loop;
int m_lastDecoded;
int m_playTime;
public:
int m_paused;
int m_channel;
int m_mp3Handle;
int m_fileHandle;
static JMP3* mInstance;
JMP3(const std::string& filename, int inBufferSize= 16*1024, int outBufferSize =16*(1152/2));
~JMP3();
static void init();
bool fillBuffers();
bool load(const std::string& filename, int inBufferSize, int outBufferSize);
bool unload();
bool update();
bool play();
bool pause();
bool setLoop(bool loop);
int setVolume(int volume);
int playTime() const;
int playTimeMinutes();
int playTimeSeconds();
};
#endif

View File

@@ -36,7 +36,7 @@
#include <psprtc.h> #include <psprtc.h>
#include "JAudio.h" #include "JAudio.h"
#include "JCooleyesMP3.h" #include "JMP3.h"
#endif #endif
@@ -47,11 +47,12 @@ class JMusic
public: public:
JMusic(); JMusic();
~JMusic(); ~JMusic();
void Update();
#if defined (WIN32) || defined (LINUX) #if defined (WIN32) || defined (LINUX)
FSOUND_SAMPLE *mTrack; // MP3 needed to be of "sample" type for FMOD, FMUSIC_MODULE is for MODs FSOUND_SAMPLE *mTrack; // MP3 needed to be of "sample" type for FMOD, FMUSIC_MODULE is for MODs
#else #else
JCooleyesMP3* mTrack; JMP3* mTrack;
#endif #endif
}; };

View File

@@ -60,6 +60,7 @@
#define SCREEN_WIDTH_F 480.0f #define SCREEN_WIDTH_F 480.0f
#define SCREEN_HEIGHT_F 272.0f #define SCREEN_HEIGHT_F 272.0f
#ifdef WIN32 #ifdef WIN32
// #define DEFAULT_BLEND BLEND_DEFAULT // #define DEFAULT_BLEND BLEND_DEFAULT
// #define BLEND_OPTION_ADD BLEND_COLORADD // #define BLEND_OPTION_ADD BLEND_COLORADD

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -16,7 +16,7 @@
#include "../include/JGE.h" #include "../include/JGE.h"
#include "../include/JAudio.h" #include "../include/JAudio.h"
#include "../include/JCooleyesMP3.h" #include "../include/JMP3.h"
#include "../include/JFileSystem.h" #include "../include/JFileSystem.h"
#include "../include/decoder_prx.h" #include "../include/decoder_prx.h"
@@ -29,7 +29,7 @@ short g_DecodedDataOutputBuffer[SAMPLE_PER_FRAME<<2] __attribute__((aligned(64))
bool g_MP3DecoderOK = false; bool g_MP3DecoderOK = false;
bool g_GotEDRAM; bool g_GotEDRAM;
JCooleyesMP3* g_CurrentMP3; JMP3* g_CurrentMP3;
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////
@@ -38,7 +38,7 @@ WAVDATA currentWav[NUMBER_WAV_CHANNELS]; //
/////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////
char loadWaveData(WAVDATA* p_wav, char* fileName, char memLoad) // WAVE加载, memLoad-是否加载至内 char loadWaveData(WAVDATA* p_wav, char* fileName, char memLoad) // WAVE加载, memLoad-是否加载至内磥E
{ {
JFileSystem* fileSystem = JFileSystem::GetInstance(); JFileSystem* fileSystem = JFileSystem::GetInstance();
@@ -172,7 +172,7 @@ void releaseWaveData(WAVDATA* p_wav) // WAVE
} }
/////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////
void audioOutCallback(int channel, void* buf, unsigned int length) // 各通道回 void audioOutCallback(int channel, void* buf, unsigned int length) // 各通道回祦E
{ {
WAVDATA* p_wav = NULL; WAVDATA* p_wav = NULL;
memset(buf, 0, 4096); memset(buf, 0, 4096);
@@ -387,122 +387,67 @@ void audioInit() //
memset(&currentWav[i], 0, sizeof(WAVDATA)); memset(&currentWav[i], 0, sizeof(WAVDATA));
p_currentWav[i] = NULL; p_currentWav[i] = NULL;
} }
pspAudioInit(); JMP3::init();
pspAudioSetChannelCallback(0, audioOutCallback_0, NULL);
pspAudioSetChannelCallback(1, audioOutCallback_1, NULL);
pspAudioSetChannelCallback(2, audioOutCallback_2, NULL);
//pspAudioSetChannelCallback(3, audioOutCallback_3, NULL);
pspAudioSetChannelCallback(3, MP3AudioOutCallback, NULL);
InitMP3Decoder();
} }
void audioDestroy() void audioDestroy()
{ {
ReleaseMP3Decoder();
pspAudioEnd();
}
//////////////////////////////////////////////////////////////////////////
void MP3AudioOutCallback(void* buf, unsigned int length, void *userdata)
{
// PSP_NUM_AUDIO_SAMPLES is 1024, 16bit samples (short), 2 channels for stereo sound
memset(buf, 0, PSP_NUM_AUDIO_SAMPLES<<2);
if (g_CurrentMP3 != NULL)
g_CurrentMP3->FeedAudioData(buf, length);
} }
int mp3thread = 0;
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
void PlayMP3(JCooleyesMP3 *mp3, bool looping) void PlayMP3(JMP3 *mp3, bool looping)
{ {
if (g_MP3DecoderOK) if (mp3thread) StopMP3();
{ JMP3::mInstance = mp3;
g_CurrentMP3 = mp3; mp3->setLoop(looping);
mp3->InitBuffers(g_MP3CodecBuffer, g_DecoderBuffer, g_DecodedDataOutputBuffer); mp3->play();
mp3->Play(looping); mp3thread = sceKernelCreateThread("decodeThread2", decodeThread2, 0x12, 0xFA0, 0, 0);
} printf("thread id : %i\n", mp3thread);
sceKernelStartThread(mp3thread, 0, NULL);
} }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
void StopMP3() void StopMP3()
{ {
if (g_CurrentMP3 != NULL) printf("stop 1\n");
{ JMP3 * mp3 = JMP3::mInstance;
g_CurrentMP3->Stop(); printf("stop 2\n");
} if (mp3){
printf("stop 3\n");
mp3->pause();
printf("stop 4\n");
sceKernelWaitThreadEnd(mp3thread, NULL);
printf("stop 5\n");
sceKernelDeleteThread(mp3thread);
printf("stop 6\n");
mp3->unload();
printf("stop 7\n");
JMP3::mInstance = NULL;
mp3thread = 0;
}
printf("stop 8\n");
} }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
void ResumeMP3() void ResumeMP3(JMP3 * mp3)
{ {
if (g_CurrentMP3 != NULL) mp3->play();
{
g_CurrentMP3->Resume();
}
} }
////////////////////////////////////////////////////////////////////////// int decodeThread2(SceSize args, void *argp){
bool InitMP3Decoder() JMP3 * mp3 = NULL;
{ while((mp3 = JMP3::mInstance) && !mp3->m_paused){
int result; mp3->update();
// if (sceKernelDevkitVersion() == 0x01050001)
// {
// LoadStartModule("flash0:/kd/me_for_vsh.prx", PSP_MEMORY_PARTITION_KERNEL);
// LoadStartModule("flash0:/kd/audiocodec.prx", PSP_MEMORY_PARTITION_KERNEL);
// }
// else
// {
// sceUtilityLoadAvModule(PSP_AV_MODULE_AVCODEC);
// }
// result = pspSdkLoadStartModule("flash0:/kd/me_for_vsh.prx", PSP_MEMORY_PARTITION_KERNEL);
// result = pspSdkLoadStartModule("flash0:/kd/videocodec.prx", PSP_MEMORY_PARTITION_KERNEL);
// result = pspSdkLoadStartModule("flash0:/kd/audiocodec.prx", PSP_MEMORY_PARTITION_KERNEL);
// result = pspSdkLoadStartModule("flash0:/kd/mpegbase.prx", PSP_MEMORY_PARTITION_KERNEL);
// result = pspSdkLoadStartModule("flash0:/kd/mpeg_vsh.prx", PSP_MEMORY_PARTITION_USER);
//
// pspSdkFixupImports(result);
prx_static_init();
sceMpegInit();
memset(g_MP3CodecBuffer, 0, sizeof(g_MP3CodecBuffer));
if ( sceAudiocodecCheckNeedMem(g_MP3CodecBuffer, 0x1002) < 0 )
return false;
if ( sceAudiocodecGetEDRAM(g_MP3CodecBuffer, 0x1002) < 0 )
return false;
g_GotEDRAM = true;
if ( sceAudiocodecInit(g_MP3CodecBuffer, 0x1002) < 0 )
return false;
g_MP3DecoderOK = true;
return true;
}
//////////////////////////////////////////////////////////////////////////
void ReleaseMP3Decoder()
{
if ( g_GotEDRAM )
sceAudiocodecReleaseEDRAM(g_MP3CodecBuffer);
}
//sceKernelDelayThread(10000);
}
return 0;
}

233
JGE/src/JMP3.cpp Normal file
View File

@@ -0,0 +1,233 @@
#include <pspkernel.h>
#include <pspdebug.h>
#include <stdio.h>
#include <pspaudio.h>
#include <pspmp3.h>
#include <psputility.h>
#include "../include/JAudio.h"
#include "../include/JFileSystem.h"
#include "../include/JMP3.h"
JMP3* JMP3::mInstance = NULL;
void JMP3::init() {
loadModules();
}
JMP3::JMP3(const std::string& filename, int inBufferSize, int outBufferSize) :
m_volume(PSP_AUDIO_VOLUME_MAX), m_paused(true), m_samplesPlayed(0) {
load(filename, inBufferSize,outBufferSize);
}
JMP3::~JMP3() {
unload();
}
bool JMP3::loadModules() {
int loadAvCodec = sceUtilityLoadModule(PSP_MODULE_AV_AVCODEC);
if (loadAvCodec < 0) {
return false;
}
int loadMp3 = sceUtilityLoadModule(PSP_MODULE_AV_MP3);
if (loadMp3 < 0) {
return false;
}
return true;
}
bool JMP3::fillBuffers() {
SceUChar8* dest;
SceInt32 length;
SceInt32 pos;
int ret = sceMp3GetInfoToAddStreamData(m_mp3Handle, &dest, &length, &pos);
if (ret < 0)
return false;
if (sceIoLseek32(m_fileHandle, pos, SEEK_SET) < 0) {
return false;
}
int readLength = sceIoRead(m_fileHandle, dest, length);
if (readLength < 0)
return false;
ret = sceMp3NotifyAddStreamData(m_mp3Handle, readLength);
if (ret < 0)
return false;
return true;
}
bool JMP3::load(const std::string& filename, int inBufferSize, int outBufferSize) {
printf("load\n");
m_inBufferSize = inBufferSize;
printf("1\n");
//m_inBuffer = new char[m_inBufferSize];
//if (!m_inBuffer)
// return false;
m_outBufferSize = outBufferSize;
printf("2\n");
//m_outBuffer = new short[outBufferSize];
//if (!m_outBuffer)
// return false;
printf("3:%s\n",filename.c_str());
m_fileHandle = sceIoOpen(filename.c_str(), PSP_O_RDONLY, 0777);
if (m_fileHandle < 0)
return false;
printf("4\n");
int ret = sceMp3InitResource();
if (ret < 0)
return false;
SceMp3InitArg initArgs;
int fileSize = sceIoLseek32(m_fileHandle, 0, SEEK_END);
sceIoLseek32(m_fileHandle, 0, SEEK_SET);
unsigned char* testbuffer = new unsigned char[7456];
sceIoRead(m_fileHandle, testbuffer, 7456);
delete testbuffer;
initArgs.unk1 = 0;
initArgs.unk2 = 0;
initArgs.mp3StreamStart = 0;
initArgs.mp3StreamEnd = fileSize;
initArgs.mp3BufSize = m_inBufferSize;
initArgs.mp3Buf = (SceVoid*) m_inBuffer;
initArgs.pcmBufSize = m_outBufferSize;
initArgs.pcmBuf = (SceVoid*) m_outBuffer;
printf("5\n");
m_mp3Handle = sceMp3ReserveMp3Handle(&initArgs);
if (m_mp3Handle < 0)
return false;
// Alright we are all set up, let's fill the first buffer.
printf("5.5\n");
bool _filled= fillBuffers();
if (! _filled) return false;
printf("end = %i, bufsize = %i, outSize = %i\n", fileSize, m_inBufferSize, m_outBufferSize);
// Start this bitch up!
printf("6\n");
int start = sceMp3Init(m_mp3Handle);
if (start < 0)
return false;
printf("7\n");
m_numChannels = sceMp3GetMp3ChannelNum(m_mp3Handle);
printf("8\n");
m_samplingRate = sceMp3GetSamplingRate(m_mp3Handle);
return true;
}
bool JMP3::unload() {
printf("unload 1\n");
if (m_channel >= 0)
sceAudioSRCChRelease();
printf("unload 2\n");
sceMp3ReleaseMp3Handle(m_mp3Handle);
printf("unload 3\n");
sceMp3TermResource();
printf("unload 4\n");
sceIoClose(m_fileHandle);
printf("unload 5\n");
//delete[] m_inBuffer;
printf("unload 6\n");
//delete[] m_outBuffer;
printf("unload 7\n");
return true;
}
bool JMP3::update() {
if (!m_paused) {
if (sceMp3CheckStreamDataNeeded(m_mp3Handle) > 0) {
fillBuffers();
}
short* tempBuffer;
int numDecoded = 0;
while (true) {
numDecoded = sceMp3Decode(m_mp3Handle, &tempBuffer);
if (numDecoded > 0)
break;
int ret = sceMp3CheckStreamDataNeeded(m_mp3Handle);
if (ret <= 0)
break;
fillBuffers();
}
// Okay, let's see if we can't get something outputted :/
if (numDecoded == 0 || numDecoded == 0x80671402) {
sceMp3ResetPlayPosition(m_mp3Handle);
if (!m_loop)
m_paused = true;
m_samplesPlayed = 0;
} else {
if (m_channel < 0 || m_lastDecoded != numDecoded) {
if (m_channel >= 0)
sceAudioSRCChRelease();
m_channel = sceAudioSRCChReserve(numDecoded / (2 * m_numChannels), m_samplingRate, m_numChannels);
}
// Output
m_samplesPlayed += sceAudioSRCOutputBlocking(m_volume, tempBuffer);
m_playTime = (m_samplingRate > 0) ? (m_samplesPlayed / m_samplingRate) : 0;
}
}
return true;
}
bool JMP3::play() {
return (m_paused = false);
}
bool JMP3::pause() {
return (m_paused = true);
}
bool JMP3::setLoop(bool loop) {
sceMp3SetLoopNum(m_mp3Handle, (loop == true) ? -1 : 0);
return (m_loop = loop);
}
int JMP3::setVolume(int volume) {
return (m_volume = volume);
}
int JMP3::playTime() const {
return m_playTime;
}
int JMP3::playTimeMinutes() {
return m_playTime / 60;
}
int JMP3::playTimeSeconds() {
return m_playTime % 60;
}

View File

@@ -10,8 +10,9 @@
#include "../include/JSoundSystem.h" #include "../include/JSoundSystem.h"
#include "../include/JAudio.h" #include "../include/JAudio.h"
#include "../include/JCooleyesMP3.h" #include "../include/JMP3.h"
#include <string>
using std::string;
JMusic::JMusic() JMusic::JMusic()
{ {
@@ -26,6 +27,10 @@ JMusic::~JMusic()
delete mTrack; delete mTrack;
} }
void JMusic::Update(){
//if (mTrack) mTrack->update();
}
JSample::JSample() JSample::JSample()
{ {
mSample = NULL; mSample = NULL;
@@ -93,29 +98,17 @@ void JSoundSystem::DestroySoundSystem()
JMusic *JSoundSystem::LoadMusic(const char *fileName) JMusic *JSoundSystem::LoadMusic(const char *fileName)
{ {
//char s[strlen(fileName)+1]; string s = "Res/";
//strcpy(s, fileName); s.append(fileName);
JMusic *music = new JMusic(); JMusic *music = new JMusic();
if (music) if (music)
{ {
music->mTrack = new JCooleyesMP3(); music->mTrack = new JMP3(s);
if (music->mTrack)
music->mTrack->Load(fileName);
} }
JMP3::mInstance = music->mTrack;
return music; return music;
} }
// void JSoundSystem::FreeMusic(JMusic *music)
// {
// if (music)
// {
// if (music->mTrack)
// delete music->mTrack;
//
// }
// }
JSample *JSoundSystem::LoadSample(const char *fileName) JSample *JSoundSystem::LoadSample(const char *fileName)
{ {
@@ -132,30 +125,8 @@ JSample *JSoundSystem::LoadSample(const char *fileName)
return sample; return sample;
} }
//
// void JSoundSystem::FreeMusic(JMusic *music)
// {
// if (music)
// {
// if (music->mTrack)
// {
// music->mTrack->Release();
// delete music->mTrack;
// }
// delete music;
// }
// }
// void JSoundSystem::FreeSample(JSample *sample)
// {
// if (sample)
// {
// releaseWaveData(sample->mSample);
// delete sample;
// }
// }
void JSoundSystem::PlayMusic(JMusic *music, bool looping) void JSoundSystem::PlayMusic(JMusic *music, bool looping)
{ {
@@ -174,8 +145,8 @@ void JSoundSystem::PlaySample(JSample *sample)
void JSoundSystem::SetVolume(int volume) void JSoundSystem::SetVolume(int volume)
{ {
JMP3 * mp3 = JMP3::mInstance;
mVolume = volume; if (mp3) mp3->setVolume(volume);
} }
@@ -188,7 +159,7 @@ void JSoundSystem::StopMusic(JMusic *music)
void JSoundSystem::ResumeMusic(JMusic *music) void JSoundSystem::ResumeMusic(JMusic *music)
{ {
ResumeMP3(); ResumeMP3(music->mTrack);
} }

View File

@@ -10,6 +10,8 @@
#ifdef WIN32 #ifdef WIN32
#pragma warning(disable : 4786) #pragma warning(disable : 4786)
extern int actualWidth;
extern int actualHeight;
#endif #endif
#include "../../Dependencies/include/png.h" #include "../../Dependencies/include/png.h"
@@ -192,13 +194,16 @@ void JRenderer::DestroyRenderer()
void JRenderer::BeginScene() void JRenderer::BeginScene()
{ {
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glLoadIdentity (); // Reset The Modelview Matrix glLoadIdentity ();// Reset The Modelview Matrix
float scaleH = (float)actualHeight/SCREEN_HEIGHT_F;
float scaleW = (float)actualWidth/SCREEN_WIDTH_F;
glScalef(scaleW,scaleW,1.f);
} }
void JRenderer::EndScene() void JRenderer::EndScene()
{ {
glFlush (); glFlush ();
} }

View File

@@ -21,6 +21,9 @@ JMusic::JMusic()
} }
void JMusic::Update(){
}
JMusic::~JMusic() JMusic::~JMusic()
{ {
JSoundSystem::GetInstance()->StopMusic(this); JSoundSystem::GetInstance()->StopMusic(this);

View File

@@ -10,7 +10,8 @@
* Visit My Site At nehe.gamedev.net * Visit My Site At nehe.gamedev.net
*/ */
int actualWidth;
int actualHeight;
#include <windows.h> // Header File For Windows #include <windows.h> // Header File For Windows
#include <gl\gl.h> // Header File For The OpenGL32 Library #include <gl\gl.h> // Header File For The OpenGL32 Library
@@ -42,6 +43,7 @@ HINSTANCE hInstance; // Holds The Instance Of The Application
bool active=TRUE; // Window Active Flag Set To TRUE By Default bool active=TRUE; // Window Active Flag Set To TRUE By Default
bool fullscreen=FALSE; // Windowed Mode By Default bool fullscreen=FALSE; // Windowed Mode By Default
DWORD lastTickCount; DWORD lastTickCount;
BOOL g_keys[256]; BOOL g_keys[256];
@@ -142,17 +144,20 @@ GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize Th
height=1; // Making Height Equal One height=1; // Making Height Equal One
} }
glViewport(0,0,width,height); // Reset The Current Viewport actualWidth = width;
actualHeight = height;
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glScissor(0, 0, width, height);
glLoadIdentity(); // Reset The Projection Matrix glViewport (0, 0, width, height); // Reset The Current Viewport
glMatrixMode (GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity (); // Reset The Projection Matrix
gluOrtho2D(0.0f, (float) width-1.0f, 0.0f, (float) height -1.0f);
// Calculate The Aspect Ratio Of The Window glMatrixMode (GL_MODELVIEW); // Select The Modelview Matrix
gluPerspective(75.0f,(GLfloat)width/(GLfloat)height,0.5f,1000.0f); glLoadIdentity (); // Reset The Modelview Matrix
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
glDisable (GL_DEPTH_TEST);
} }
int InitGL(GLvoid) // All Setup For OpenGL Goes Here int InitGL(GLvoid) // All Setup For OpenGL Goes Here
@@ -303,6 +308,11 @@ GLvoid KillGLWindow(GLvoid) // Properly Kill The Window
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag) BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{ {
actualWidth = width;
actualHeight = height;
GLuint PixelFormat; // Holds The Results After Searching For A Match GLuint PixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure WNDCLASS wc; // Windows Class Structure
DWORD dwExStyle; // Window Extended Style DWORD dwExStyle; // Window Extended Style
@@ -373,6 +383,8 @@ BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscree
dwStyle= WS_OVERLAPPED | \ dwStyle= WS_OVERLAPPED | \
WS_CAPTION | \ WS_CAPTION | \
WS_MINIMIZEBOX | WS_MINIMIZEBOX |
WS_SIZEBOX |
WS_MAXIMIZEBOX |
//WS_MINIMIZE | //WS_MINIMIZE |
WS_SYSMENU;// | \ WS_SYSMENU;// | \
//WS_THICKFRAME ; //WS_THICKFRAME ;
@@ -565,6 +577,7 @@ LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window
case WM_SIZE: // Resize The OpenGL Window case WM_SIZE: // Resize The OpenGL Window
{ {
ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height
return 0; // Jump Back return 0; // Jump Back
} }

View File

@@ -13,7 +13,7 @@ ASFLAGS = $(CXXFLAGS)
INCDIR = ../../JGE/include ../../JGE/include/psp ../../JGE/include/psp/freetype2 ../../JGE/src INCDIR = ../../JGE/include ../../JGE/include/psp ../../JGE/include/psp/freetype2 ../../JGE/src
LIBDIR = ../../JGE/lib/psp LIBDIR = ../../JGE/lib/psp
LDFLAGS = LDFLAGS =
LIBS = -ljge300 -lhgetools -lfreetype -ljpeg -lgif -lpng -lz -lm -lmikmod -lpsppower -lpspmpeg -lpspaudiocodec -lpspaudiolib -lpspaudio -lpspgum -lpspgu -lpsprtc -lstdc++ -lpspfpu LIBS = -ljge300 -lhgetools -lfreetype -ljpeg -lgif -lpng -lz -lm -lmikmod -lpsppower -lpspmpeg -lpspaudiocodec -lpspaudiolib -lpspaudio -lpspmp3 -lpspgum -lpspgu -lpsprtc -lstdc++ -lpspfpu
EXTRA_TARGETS = EBOOT.PBP EXTRA_TARGETS = EBOOT.PBP
PSP_EBOOT_TITLE = WTH?! PSP_EBOOT_TITLE = WTH?!

View File

@@ -1,50 +1,50 @@
100 100
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0

View File

@@ -1,92 +1,92 @@
1167 1167
460 460
1202 1202
525 525
1340 1340
92 92
1284 1284
101 101
1149 1149
20 20
1264 1264
20 20
1321 1321
20 20
1272 1272
437 437
1126 1126
485 485
1334 1334
107 107
1352 1352
91 91
1279 1279
20 20
1154 1154
481 481
1328 1328
551 551
1335 1335
20 20
1227 1227
500 500
1236 1236
489 489
1186 1186
20 20
1219 1219
20 20
1175 1175
459 459
1136 1136
111 111
1332 1332
545 545
1250 1250
21 21
1204 1204
19 19
1381 1381
499 499
1170 1170
484 484
1097 1097
102 102
1102 1102
46 46
1282 1282
485 485
1378 1378
490 490
1300 1300
20 20
1363 1363
495 495
129665 129665
90 90
1387 1387
4 4
129652 129652
5 5
174957 174957
108 108
175030 175030
5 5
130378 130378
107 107
175031 175031
5 5
1312 1312
19 19
130386 130386
97 97
1275 1275
21 21
1148 1148
103 103
135185 135185
20 20
1100 1100
109 109
153441 153441
19 19

View File

@@ -80,6 +80,7 @@ class GameApp: public JApp
static JResourceManager * CommonRes; static JResourceManager * CommonRes;
static hgeParticleSystem * Particles[6]; static hgeParticleSystem * Particles[6];
static int HasMusic; static int HasMusic;
static JMusic* music;
}; };

View File

@@ -194,9 +194,13 @@ class GameStateDeckViewer: public GameState, public JGuiListener
welcome_menu->Add(10, "Cancel"); welcome_menu->Add(10, "Cancel");
if (GameApp::HasMusic && GameOptions::GetInstance()->values[OPTIONS_MUSICVOLUME] > 0){ if (GameApp::HasMusic && GameOptions::GetInstance()->values[OPTIONS_MUSICVOLUME] > 0){
if (!bgMusic) bgMusic = JSoundSystem::GetInstance()->LoadMusic("sound/Track1.mp3"); if (GameApp::music){
if (bgMusic){ JSoundSystem::GetInstance()->StopMusic(GameApp::music);
JSoundSystem::GetInstance()->PlayMusic(bgMusic, true); SAFE_DELETE(GameApp::music);
}
GameApp::music = JSoundSystem::GetInstance()->LoadMusic("sound/track1.mp3");
if (GameApp::music){
JSoundSystem::GetInstance()->PlayMusic(GameApp::music, true);
} }
} }
colorFilter = ALL_COLORS; colorFilter = ALL_COLORS;
@@ -219,7 +223,10 @@ class GameStateDeckViewer: public GameState, public JGuiListener
virtual void End() virtual void End()
{ {
//mEngine->EnableVSync(false); //mEngine->EnableVSync(false);
if (bgMusic) JSoundSystem::GetInstance()->StopMusic(bgMusic); if (GameApp::music){
JSoundSystem::GetInstance()->StopMusic(GameApp::music);
SAFE_DELETE(GameApp::music);
}
SAFE_DELETE(backTex); SAFE_DELETE(backTex);
SAFE_DELETE(backQuad); SAFE_DELETE(backQuad);
SAFE_DELETE(welcome_menu); SAFE_DELETE(welcome_menu);

View File

@@ -43,7 +43,7 @@ class GameStateMenu: public GameState, public JGuiListener
JQuad * mMovingW; JQuad * mMovingW;
float mCreditsYPos; float mCreditsYPos;
int currentState; int currentState;
JMusic * bgMusic; //JMusic * bgMusic;
int mVolume; int mVolume;
char nbcardsStr[400]; char nbcardsStr[400];
@@ -64,10 +64,11 @@ class GameStateMenu: public GameState, public JGuiListener
mGuiController = NULL; mGuiController = NULL;
subMenuController = NULL; subMenuController = NULL;
mIconsTexture = NULL; mIconsTexture = NULL;
bgMusic = NULL; //bgMusic = NULL;
timeIndex = 0; timeIndex = 0;
angleMultiplier = MIN_ANGLE_MULTIPLIER; angleMultiplier = MIN_ANGLE_MULTIPLIER;
yW = 55; yW = 55;
mVolume = 0;
} }
virtual ~GameStateMenu() virtual ~GameStateMenu()
@@ -90,7 +91,7 @@ class GameStateMenu: public GameState, public JGuiListener
mIconsTexture = JRenderer::GetInstance()->LoadTexture("graphics/menuicons.png", TEX_TYPE_USE_VRAM); mIconsTexture = JRenderer::GetInstance()->LoadTexture("graphics/menuicons.png", TEX_TYPE_USE_VRAM);
bgTexture = JRenderer::GetInstance()->LoadTexture("graphics/menutitle.png", TEX_TYPE_USE_VRAM); bgTexture = JRenderer::GetInstance()->LoadTexture("graphics/menutitle.png", TEX_TYPE_USE_VRAM);
movingWTexture = JRenderer::GetInstance()->LoadTexture("graphics/movingW.png", TEX_TYPE_USE_VRAM); movingWTexture = JRenderer::GetInstance()->LoadTexture("graphics/movingW.png", TEX_TYPE_USE_VRAM);
mBg = NEW JQuad(bgTexture, 0, 0, 256, 167); // Create background quad for rendering. mBg = NEW JQuad(bgTexture, 0, 0, 256, 166); // Create background quad for rendering.
mMovingW = NEW JQuad(movingWTexture, 2, 2, 84, 62); mMovingW = NEW JQuad(movingWTexture, 2, 2, 84, 62);
mBg->SetHotSpot(105,50); mBg->SetHotSpot(105,50);
mMovingW->SetHotSpot(72,16); mMovingW->SetHotSpot(72,16);
@@ -149,7 +150,7 @@ class GameStateMenu: public GameState, public JGuiListener
if (mBg) delete mBg; if (mBg) delete mBg;
if (mMovingW) delete mMovingW; if (mMovingW) delete mMovingW;
SAFE_DELETE (bgMusic); //SAFE_DELETE (bgMusic);
} }
@@ -157,15 +158,17 @@ class GameStateMenu: public GameState, public JGuiListener
JRenderer::GetInstance()->ResetPrivateVRAM(); JRenderer::GetInstance()->ResetPrivateVRAM();
JRenderer::GetInstance()->EnableVSync(true); JRenderer::GetInstance()->EnableVSync(true);
if (GameApp::HasMusic && !bgMusic && GameOptions::GetInstance()->values[OPTIONS_MUSICVOLUME] > 0){
bgMusic = JSoundSystem::GetInstance()->LoadMusic("sound/Track0.mp3"); if (GameApp::HasMusic && !GameApp::music && GameOptions::GetInstance()->values[OPTIONS_MUSICVOLUME] > 0){
GameApp::music = JSoundSystem::GetInstance()->LoadMusic("sound/Track0.mp3");
JSoundSystem::GetInstance()->PlayMusic(GameApp::music, true);
} }
if (bgMusic){ if (GameApp::HasMusic && GameApp::music && GameOptions::GetInstance()->values[OPTIONS_MUSICVOLUME] == 0){
mVolume = 0; JSoundSystem::GetInstance()->StopMusic(GameApp::music);
JSoundSystem::GetInstance()->SetVolume(mVolume); SAFE_DELETE(GameApp::music);
JSoundSystem::GetInstance()->PlayMusic(bgMusic, true); }
}
} }
@@ -198,19 +201,23 @@ class GameStateMenu: public GameState, public JGuiListener
{ {
//mEngine->EnableVSync(false); //mEngine->EnableVSync(false);
if (bgMusic) // if (bgMusic)
{ // {
JSoundSystem::GetInstance()->StopMusic(bgMusic); //JSoundSystem::GetInstance()->StopMusic(bgMusic);
} //SAFE_DELETE(bgMusic);
// }
JRenderer::GetInstance()->EnableVSync(false); JRenderer::GetInstance()->EnableVSync(false);
} }
virtual void Update(float dt) virtual void Update(float dt)
{ {
if (bgMusic && mVolume < 2*GameOptions::GetInstance()->values[OPTIONS_MUSICVOLUME]){
mVolume++; if (GameApp::music){
JSoundSystem::GetInstance()->SetVolume(mVolume/2); /*if (mVolume < 2*GameOptions::GetInstance()->values[OPTIONS_MUSICVOLUME]){
mVolume++;
JSoundSystem::GetInstance()->SetVolume(mVolume/2);
}*/
} }
timeIndex += dt * 2; timeIndex += dt * 2;
@@ -282,7 +289,7 @@ class GameStateMenu: public GameState, public JGuiListener
if (mEngine->GetButtonState(PSP_CTRL_TRIANGLE) && (dt != 0)) if (mEngine->GetButtonState(PSP_CTRL_TRIANGLE) && (dt != 0))
{ {
angleMultiplier = (cos(timeIndex)*angleMultiplier - M_PI/3 - 0.1 - angleW) / dt; angleMultiplier = (cos(timeIndex)*angleMultiplier - M_PI/3 - 0.1 - angleW) / dt;
yW = yW + 0.001 + (yW - 55) / 1000; yW = yW + 5*dt + (yW - 55) *5* dt;
} }
else else
angleW = cos(timeIndex)*angleMultiplier - M_PI/3 - 0.1; angleW = cos(timeIndex)*angleMultiplier - M_PI/3 - 0.1;
@@ -290,7 +297,7 @@ class GameStateMenu: public GameState, public JGuiListener
else else
{ {
angleW += angleMultiplier * dt; angleW += angleMultiplier * dt;
yW = yW + 0.001 + (yW - 55) / 1000; yW = yW + 5*dt + (yW - 55) *5*dt;
} }
} }

View File

@@ -6,6 +6,8 @@
#endif #endif
#ifdef _DEBUG #ifdef _DEBUG
//if you get the following error :'_NORMAL_BLOCK' : undeclared identifier,
// try to add #include "crtdbg.h" somewhere in your code before including this file
#define NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) #define NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#else #else
#define NEW new #define NEW new

View File

@@ -21,6 +21,7 @@ const char * const GameState::menuTexts[]= {"--NEW--","Deck 1", "Deck 2", "Deck
JResourceManager* GameApp::CommonRes = NEW JResourceManager(); JResourceManager* GameApp::CommonRes = NEW JResourceManager();
hgeParticleSystem* GameApp::Particles[] = {NULL,NULL,NULL,NULL,NULL,NULL}; hgeParticleSystem* GameApp::Particles[] = {NULL,NULL,NULL,NULL,NULL,NULL};
int GameApp::HasMusic = 1; int GameApp::HasMusic = 1;
JMusic * GameApp::music = NULL;
GameState::GameState(GameApp* parent): mParent(parent) GameState::GameState(GameApp* parent): mParent(parent)
{ {
@@ -75,6 +76,7 @@ void GameApp::Create()
} }
CommonRes->CreateTexture("graphics/menuicons.png"); CommonRes->CreateTexture("graphics/menuicons.png");
//Creating thes quad in this specific order allows us to have them in the correct order to call them by integer id //Creating thes quad in this specific order allows us to have them in the correct order to call them by integer id
CommonRes->CreateQuad("c_artifact", "graphics/menuicons.png", 2 + 6*36, 38, 32, 32); CommonRes->CreateQuad("c_artifact", "graphics/menuicons.png", 2 + 6*36, 38, 32, 32);

View File

@@ -181,6 +181,11 @@ void GameStateDuel::Update(float dt)
} }
}else if (mGamePhase == DUEL_PLAY){ }else if (mGamePhase == DUEL_PLAY){
//Stop the music before starting the game
if (GameApp::music){
JSoundSystem::GetInstance()->StopMusic(GameApp::music);
SAFE_DELETE(GameApp::music);
}
if (!game){ if (!game){
GameObserver::Init(mPlayers, 2); GameObserver::Init(mPlayers, 2);
game = GameObserver::GetInstance(); game = GameObserver::GetInstance();
@@ -209,11 +214,13 @@ void GameStateDuel::Update(float dt)
}else{ }else{
mGamePhase = DUEL_END; mGamePhase = DUEL_END;
} }
}else if (mParent->players[0] == PLAYER_TYPE_CPU && mParent->players[1] == PLAYER_TYPE_CPU){ }else
#endif
if (mParent->players[0] == PLAYER_TYPE_CPU && mParent->players[1] == PLAYER_TYPE_CPU){
End(); End();
Start(); Start();
} }
#endif
mFont->SetColor(ARGB(255,255,255,255)); mFont->SetColor(ARGB(255,255,255,255));
} }
if (mEngine->GetButtonClick(PSP_CTRL_START)){ if (mEngine->GetButtonClick(PSP_CTRL_START)){

View File

@@ -1,188 +1,188 @@
#!/usr/bin/python #!/usr/bin/python
# #
# Requires BeautifulSoup verion 3, available from # Requires BeautifulSoup verion 3, available from
# http://www.crummy.com/software/BeautifulSoup/ # http://www.crummy.com/software/BeautifulSoup/
# #
# Usage: python gatherer-builder.py <output file> # Usage: python gatherer-builder.py <output file>
# #
# Copyright 2006: Nathan Callahan # Copyright 2006: Nathan Callahan
# Feel free to do what you want with this file, but give credit # Feel free to do what you want with this file, but give credit
# where it's due. # where it's due.
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup, Tag from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup, Tag
import re import re
import codecs import codecs
import sys import sys
import urllib import urllib
import os import os
import os.path import os.path
from mtgCommon import * from mtgCommon import *
setinfo=sets['SHM'] setinfo=sets['CK']
stripReminderText = False stripReminderText = False
conffile = open(setinfo['dir'] + ".conf", 'w') conffile = open(setinfo['dir'] + ".conf", 'w')
# FETCH_IMAGES = False # FETCH_IMAGES = False
FETCH_IMAGES = True FETCH_IMAGES = True
url = "http://ww2.wizards.com/gatherer/Index.aspx?setfilter=%s\\&output=Spoiler" % setinfo['gathname'] url = "http://ww2.wizards.com/gatherer/Index.aspx?setfilter=%s\\&output=Spoiler" % setinfo['gathname']
gatherer = urllib.urlopen(url) gatherer = urllib.urlopen(url)
soup = BeautifulSoup(gatherer.read(), smartQuotesTo=None) soup = BeautifulSoup(gatherer.read(), smartQuotesTo=None)
xml = BeautifulStoneSoup('<?xml version=\'1.0\' encoding=\'latin1\'?><!DOCTYPE ccg-setinfo SYSTEM "../gccg-set.dtd"><ccg-setinfo name="%s" dir="%s" abbrev="%s" game="Magic The Gathering"><cards></cards></ccg-setinfo>' % (setinfo['name'], setinfo['dir'], setinfo['abbrev']),selfClosingTags=['attr']) xml = BeautifulStoneSoup('<?xml version=\'1.0\' encoding=\'latin1\'?><!DOCTYPE ccg-setinfo SYSTEM "../gccg-set.dtd"><ccg-setinfo name="%s" dir="%s" abbrev="%s" game="Magic The Gathering"><cards></cards></ccg-setinfo>' % (setinfo['name'], setinfo['dir'], setinfo['abbrev']),selfClosingTags=['attr'])
rarity_re=re.compile(".*%s_(?P<rarity>.)\.gif.*" % setinfo['gathabbrev']) rarity_re=re.compile(".*%s_(?P<rarity>.)\.gif.*" % setinfo['gathabbrev'])
def fetchImage(id, filename): def fetchImage(id, filename):
if (not os.path.exists(setinfo['abbrev'] + "/" + filename)): if (not os.path.exists(setinfo['abbrev'] + "/" + filename)):
for i in setinfo['gathdirs']: for i in setinfo['gathdirs']:
url="http://resources.wizards.com/Magic/Cards/%s/Card%s.jpg" % (i, id) url="http://resources.wizards.com/Magic/Cards/%s/Card%s.jpg" % (i, id)
print url print url
try: try:
pic = urllib.urlopen(url) pic = urllib.urlopen(url)
except: except:
pass pass
if (not pic): # this is completely wrong, supposed to check if it's not found if (not pic): # this is completely wrong, supposed to check if it's not found
raise IOError raise IOError
if (not os.path.exists(setinfo['abbrev'])): if (not os.path.exists(setinfo['abbrev'])):
os.mkdir(setinfo['abbrev']) os.mkdir(setinfo['abbrev'])
else: else:
assert os.path.isdir(setinfo['abbrev']) assert os.path.isdir(setinfo['abbrev'])
f = open(setinfo['abbrev'] + "/" + filename, 'wb') f = open(setinfo['abbrev'] + "/" + filename, 'wb')
f.write(pic.read()) f.write(pic.read())
f.close() f.close()
for cardRow in soup.find(id="_gridResults").findAll('tr',onmouseover="this.style.backgroundColor='#F5DEB3';"): for cardRow in soup.find(id="_gridResults").findAll('tr',onmouseover="this.style.backgroundColor='#F5DEB3';"):
name = cardRow('b')[0].string name = cardRow('b')[0].string
name = name.replace('"','') name = name.replace('"','')
name = name.replace(u'\xe2', 'a') name = name.replace(u'\xe2', 'a')
name = name.replace(u'\xc6', 'AE') name = name.replace(u'\xc6', 'AE')
manaCost = replaceSymbols(cardRow('td')[1]('font')[0]) manaCost = replaceSymbols(cardRow('td')[1]('font')[0])
manaCost = ''.join(manaCost.contents) manaCost = ''.join(manaCost.contents)
print manaCost print manaCost
if manaCost == "&nbsp;": if manaCost == "&nbsp;":
manaCost=""; manaCost="";
htmlText = cardRow('td')[3] htmlText = cardRow('td')[3]
htmlText = replaceSymbols(htmlText) htmlText = replaceSymbols(htmlText)
text = cleanupHTMLText(htmlText, stripReminderText) text = cleanupHTMLText(htmlText, stripReminderText)
supertype, subtype = getCardTypes(cardRow) supertype, subtype = getCardTypes(cardRow)
splitCard = split_re.match(text) splitCard = split_re.match(text)
if splitCard: if splitCard:
text = splitCard.group('t1') + " // " + splitCard.group('t2') text = splitCard.group('t1') + " // " + splitCard.group('t2')
manaCost = manaCost + " // " + splitCard.group('mana2') manaCost = manaCost + " // " + splitCard.group('mana2')
supertype = supertype + " // " + splitCard.group('type2') supertype = supertype + " // " + splitCard.group('type2')
power = cardRow('td')[4]('font')[0].string power = cardRow('td')[4]('font')[0].string
if power == "&nbsp;": if power == "&nbsp;":
power = None power = None
toughness = cardRow('td')[5]('font')[0].string toughness = cardRow('td')[5]('font')[0].string
if toughness == "&nbsp;": if toughness == "&nbsp;":
toughness = None toughness = None
colors = set() colors = set()
for c in manaCost: for c in manaCost:
if c in symbolColors: if c in symbolColors:
colors.add(symbolColors[c].capitalize()) colors.add(symbolColors[c].capitalize())
color = ''.join(sorted([c+" " for c in colors])).rstrip() color = ''.join(sorted([c+" " for c in colors])).rstrip()
if not color: if not color:
if (supertype.find("Artifact") != -1): if (supertype.find("Artifact") != -1):
color = "Artifact" color = "Artifact"
elif (supertype.find("Land") != -1): elif (supertype.find("Land") != -1):
color = "Land" color = "Land"
else: else:
ss = "%s is " % name ss = "%s is " % name
start = text.find(ss) + len(ss) start = text.find(ss) + len(ss)
end = text.find('.',start) end = text.find('.',start)
color = text[start:end].capitalize() color = text[start:end].capitalize()
printings = 1 printings = 1
for printing in cardRow('td')[6].findAll(src=rarity_re): for printing in cardRow('td')[6].findAll(src=rarity_re):
print name print name
if name in basic_lands: if name in basic_lands:
rarity = 'L' rarity = 'L'
else: else:
rarity = rarity_re.match(str(printing)).group('rarity') rarity = rarity_re.match(str(printing)).group('rarity')
card = Tag(xml, 'card') card = Tag(xml, 'card')
cards=xml('ccg-setinfo')[0]('cards')[0] cards=xml('ccg-setinfo')[0]('cards')[0]
cards.insert(len(cards),card) cards.insert(len(cards),card)
card=cards('card')[-1] card=cards('card')[-1]
card['name']=name card['name']=name
if printings > 1: if printings > 1:
card['graphics']=name.translate(imagetrans)+str(printings)+".jpg" card['graphics']=name.translate(imagetrans)+str(printings)+".jpg"
else: else:
card['graphics']=name.translate(imagetrans)+".jpg" card['graphics']=name.translate(imagetrans)+".jpg"
id = id_re.match(printing.parent['onclick']).group('id') id = id_re.match(printing.parent['onclick']).group('id')
if FETCH_IMAGES: if FETCH_IMAGES:
fetchImage(id, id + ".jpg") fetchImage(id, id + ".jpg")
text = text.replace(u'\xe2', 'a') text = text.replace(u'\xe2', 'a')
card['text']=text card['text']=text
card.insert(0,Tag(xml,'attr')) card.insert(0,Tag(xml,'attr'))
card('attr')[0]['key']='rarity' card('attr')[0]['key']='rarity'
card('attr')[0]['value']=rarity card('attr')[0]['value']=rarity
card.insert(1,Tag(xml,'attr')) card.insert(1,Tag(xml,'attr'))
card('attr')[1]['key']='color' card('attr')[1]['key']='color'
card('attr')[1]['value']=color card('attr')[1]['value']=color
conffile.write("[card]") conffile.write("[card]")
# conffile.write("\nimage=" + card['graphics']) # conffile.write("\nimage=" + card['graphics'])
conffile.write("\ntext=" + text) conffile.write("\ntext=" + text)
conffile.write("\nid=" + id) conffile.write("\nid=" + id)
conffile.write("\nname=" + name) conffile.write("\nname=" + name)
conffile.write("\nrarity=" + rarity) conffile.write("\nrarity=" + rarity)
# conffile.write("\ncolor=" + color) # conffile.write("\ncolor=" + color)
conffile.write("\ntype=" + supertype) conffile.write("\ntype=" + supertype)
if manaCost: if manaCost:
card.insert(2,Tag(xml,'attr')) card.insert(2,Tag(xml,'attr'))
card('attr')[2]['key']='cost' card('attr')[2]['key']='cost'
card('attr')[2]['value']=manaCost card('attr')[2]['value']=manaCost
conffile.write("\nmana=" + manaCost) conffile.write("\nmana=" + manaCost)
if power: if power:
card.insert(len(card),Tag(xml,'attr')) card.insert(len(card),Tag(xml,'attr'))
card('attr')[-1]['key']='power' card('attr')[-1]['key']='power'
card('attr')[-1]['value']=power card('attr')[-1]['value']=power
conffile.write("\npower=" + power) conffile.write("\npower=" + power)
if subtype: if subtype:
subtype = subtype.replace(u'\xe2', 'a') subtype = subtype.replace(u'\xe2', 'a')
card.insert(len(card),Tag(xml,'attr')) card.insert(len(card),Tag(xml,'attr'))
card('attr')[-1]['key']='subtype' card('attr')[-1]['key']='subtype'
card('attr')[-1]['value']=subtype card('attr')[-1]['value']=subtype
conffile.write("\nsubtype=" + subtype) conffile.write("\nsubtype=" + subtype)
if toughness: if toughness:
card.insert(len(card),Tag(xml,'attr')) card.insert(len(card),Tag(xml,'attr'))
card('attr')[-1]['key']='toughness' card('attr')[-1]['key']='toughness'
card('attr')[-1]['value']=toughness card('attr')[-1]['value']=toughness
conffile.write("\ntoughness=" + toughness) conffile.write("\ntoughness=" + toughness)
card.insert(len(card),Tag(xml,'attr')) card.insert(len(card),Tag(xml,'attr'))
card('attr')[-1]['key']='type' card('attr')[-1]['key']='type'
card('attr')[-1]['value']=supertype card('attr')[-1]['value']=supertype
printings += 1 printings += 1
conffile.write("\n[/card]\n") conffile.write("\n[/card]\n")
f = file(sys.argv[1],'w') f = file(sys.argv[1],'w')
f.write(xml.prettify('latin1')) f.write(xml.prettify('latin1'))
f.close() f.close()
conffile.close() conffile.close()

View File

@@ -1,494 +1,495 @@
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup, Tag from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup, Tag
import re import re
import codecs import codecs
import sys import sys
sets ={'BE':{'name':'Beta', sets ={'BE':{'name':'Beta',
'dir':'BE', 'dir':'BE',
'abbrev':'BE', 'abbrev':'BE',
'gathabbrev': '2E', 'gathabbrev': '2E',
'gathname':'LimitedEditionBeta', 'gathname':'LimitedEditionBeta',
}, },
'RV':{'name':'Revised', 'RV':{'name':'Revised',
'dir':'RV', 'dir':'RV',
'abbrev':'RV', 'abbrev':'RV',
'gathdirs':['3E/en-us'], 'gathdirs':['3E/en-us'],
'gathabbrev': '3E', 'gathabbrev': '3E',
'gathname':'RevisedEdition' 'gathname':'RevisedEdition'
}, },
'4E':{'name':'4th Edition', '4E':{'name':'4th Edition',
'dir':'4E', 'dir':'4E',
'abbrev':'4E', 'abbrev':'4E',
'gathdirs':['4E/en-us'], 'gathdirs':['4E/en-us'],
'gathabbrev': '4E', 'gathabbrev': '4E',
'gathname':'FourthEdition', 'gathname':'FourthEdition',
}, },
'5E':{'name':'5th Edition', '5E':{'name':'5th Edition',
'dir':'5E', 'dir':'5E',
'abbrev':'5E', 'abbrev':'5E',
'gathdirs':['5E/en-us'], 'gathdirs':['5E/en-us'],
'gathabbrev': '5E', 'gathabbrev': '5E',
'gathname':'FifthEdition' 'gathname':'FifthEdition'
}, },
'6E':{'name':'6th Edition', '6E':{'name':'6th Edition',
'dir':'6E', 'dir':'6E',
'abbrev':'6E', 'abbrev':'6E',
'gathdirs':['6E/en-us'], 'gathdirs':['6E/en-us'],
'gathabbrev': '6E', 'gathabbrev': '6E',
'gathname':'ClassicSixthEdition', 'gathname':'ClassicSixthEdition',
}, },
'7E':{'name':'7th Edition', '7E':{'name':'7th Edition',
'dir':'7E', 'dir':'7E',
'abbrev':'7E', 'abbrev':'7E',
'gathdirs':['7E/en-us'], 'gathdirs':['7E/en-us'],
'gathabbrev': '7E', 'gathabbrev': '7E',
'gathname':'SeventhEdition', 'gathname':'SeventhEdition',
}, },
'8E':{'name':'8th Edition', '8E':{'name':'8th Edition',
'dir':'8E', 'dir':'8E',
'abbrev':'8E', 'abbrev':'8E',
'gathdirs':['8ED/en-us'], 'gathdirs':['8ED/en-us'],
'gathabbrev': '8ED', 'gathabbrev': '8ED',
'gathname':'EighthEdition', 'gathname':'EighthEdition',
}, },
'9E':{'name':'9th Edition', '9E':{'name':'9th Edition',
'dir':'9E', 'dir':'9E',
'abbrev':'9E', 'abbrev':'9E',
'gathdirs':['9ED/en-us'], 'gathdirs':['9ED/en-us'],
'gathabbrev': '9ED', 'gathabbrev': '9ED',
'gathname':'NinthEdition', 'gathname':'NinthEdition',
}, },
'10E':{'name':'10th Edition', '10E':{'name':'10th Edition',
'dir':'10E', 'dir':'10E',
'abbrev':'10E', 'abbrev':'10E',
'gathdirs':['10E/EN'], 'gathdirs':['10E/EN'],
'gathabbrev': '10E', 'gathabbrev': '10E',
'gathname':'TenthEdition', 'gathname':'TenthEdition',
}, },
'EVE':{'name':'Eventide', 'EVE':{'name':'Eventide',
'dir':'EVE', 'dir':'EVE',
'abbrev':'EVE', 'abbrev':'EVE',
'gathdirs':['EVE/EN'], 'gathdirs':['EVE/EN'],
'gathabbrev': 'EVE', 'gathabbrev': 'EVE',
'gathname':'Eventide', 'gathname':'Eventide',
}, },
'SHM':{'name':'Shadowmoor', 'SHM':{'name':'Shadowmoor',
'dir':'SHM', 'dir':'SHM',
'abbrev':'SHM', 'abbrev':'SHM',
'gathdirs':['SHM/EN'], 'gathdirs':['SHM/EN'],
'gathabbrev': 'SHM', 'gathabbrev': 'SHM',
'gathname':'Shadowmoor', 'gathname':'Shadowmoor',
}, },
'ALA':{'name':'Shards of Alara', 'ALA':{'name':'Shards of Alara',
'dir':'ALA', 'dir':'ALA',
'abbrev':'ALA', 'abbrev':'ALA',
'gathdirs':['ALA/EN'], 'gathdirs':['ALA/EN'],
'gathabbrev': 'ALA', 'gathabbrev': 'ALA',
'gathname':'ShardsOfAlara', 'gathname':'ShardsOfAlara',
}, },
'UH':{'name':'Unhinged', 'UH':{'name':'Unhinged',
'dir':'UH', 'dir':'UH',
'abbrev':'UH', 'abbrev':'UH',
'gathdirs':['UNH/en-us'], 'gathdirs':['UNH/en-us'],
'gathabbrev': 'UNH', 'gathabbrev': 'UNH',
'gathname':'Unhinged', 'gathname':'Unhinged',
}, },
'UG':{'name':'Unglued', 'UG':{'name':'Unglued',
'dir':'UG', 'dir':'UG',
'abbrev':'UG', 'abbrev':'UG',
'gathdirs':['UG/en-us'], 'gathdirs':['UG/en-us'],
'gathabbrev':'UG', 'gathabbrev':'UG',
'gathname':'Unglued', 'gathname':'Unglued',
}, },
'P1':{'name':'Portal', 'P1':{'name':'Portal',
'dir':'P1', 'dir':'P1',
'abbrev':'P1', 'abbrev':'P1',
'gathdirs':['P1/en-us'], 'gathdirs':['P1/en-us'],
'gathabbrev':'P1', 'gathabbrev':'P1',
'gathname':'Portal', 'gathname':'Portal',
}, },
'P2':{'name':'Portal Second Age', 'P2':{'name':'Portal Second Age',
'dir':'P2', 'dir':'P2',
'abbrev':'P2', 'abbrev':'P2',
'gathdirs':['P2/en-us'], 'gathdirs':['P2/en-us'],
'gathabbrev':'P2', 'gathabbrev':'P2',
'gathname':'PortalSecondAge', 'gathname':'PortalSecondAge',
}, },
'P3':{'name':'Portal Three Kingdoms', 'P3':{'name':'Portal Three Kingdoms',
'dir':'P3', 'dir':'P3',
'abbrev':'P3', 'abbrev':'P3',
'gathdirs':['PK/en-us'], 'gathdirs':['PK/en-us'],
'gathabbrev': 'PK', 'gathabbrev': 'PK',
'gathname':'PortalThreeKingdoms', 'gathname':'PortalThreeKingdoms',
}, },
'AN':{'name':'Arabian Nights', 'AN':{'name':'Arabian Nights',
'dir':'AN', 'dir':'AN',
'abbrev':'AN', 'abbrev':'AN',
'gathdirs':['AN/en-us'], 'gathdirs':['AN/en-us'],
'gathabbrev': 'AN', 'gathabbrev': 'AN',
'gathname':'ArabianNights' 'gathname':'ArabianNights'
}, },
'AQ':{'name':'Antiquities', 'AQ':{'name':'Antiquities',
'dir':'AQ', 'dir':'AQ',
'abbrev':'AQ', 'abbrev':'AQ',
'gathdirs':['AQ/en-us'], 'gathdirs':['AQ/en-us'],
'gathabbrev': 'AQ', 'gathabbrev': 'AQ',
'gathname':'Antiquities', 'gathname':'Antiquities',
}, },
'LG':{'name':'Legends', 'LG':{'name':'Legends',
'dir':'LG', 'dir':'LG',
'abbrev':'LG', 'abbrev':'LG',
'gathdirs':['LG/en-us'], 'gathdirs':['LG/en-us'],
'gathabbrev': 'LE', 'gathabbrev': 'LE',
'gathname':'Legends', 'gathname':'Legends',
}, },
'DK':{'name':'The Dark', 'DK':{'name':'The Dark',
'dir':'DK', 'dir':'DK',
'abbrev':'DK', 'abbrev':'DK',
'gathdirs':['DK/en-us'], 'gathdirs':['DK/en-us'],
'gathabbrev': 'DK', 'gathabbrev': 'DK',
'gathname':'TheDark', 'gathname':'TheDark',
}, },
'FE':{'name':'Fallen Empires', 'FE':{'name':'Fallen Empires',
'dir':'FE', 'dir':'FE',
'abbrev':'FE', 'abbrev':'FE',
'gathdirs':['FE/en-us'], 'gathdirs':['FE/en-us'],
'gathabbrev': 'FE', 'gathabbrev': 'FE',
'gathname':'FallenEmpires', 'gathname':'FallenEmpires',
}, },
'IA':{'name':'Ice Age', 'IA':{'name':'Ice Age',
'dir':'IA', 'dir':'IA',
'abbrev':'IA', 'abbrev':'IA',
'gathdirs':['IA/en-us'], 'gathdirs':['IA/en-us'],
'gathabbrev': 'IA', 'gathabbrev': 'IA',
'gathname':'IceAge', 'gathname':'IceAge',
}, },
'HL':{'name':'Homelands', 'HL':{'name':'Homelands',
'dir':'HL', 'dir':'HL',
'abbrev':'HL', 'abbrev':'HL',
'gathdirs':['HM/en-us'], 'gathdirs':['HM/en-us'],
'gathabbrev': 'HM', 'gathabbrev': 'HM',
'gathname':'Homelands' 'gathname':'Homelands'
}, },
'AL':{'name':'Alliances', 'AL':{'name':'Alliances',
'dir':'AL', 'dir':'AL',
'abbrev':'AL', 'abbrev':'AL',
'gathdirs':['AL/en-us'], 'gathdirs':['AL/en-us'],
'gathabbrev': 'AL', 'gathabbrev': 'AL',
'gathname':'Alliances', 'gathname':'Alliances',
}, },
'MI':{'name':'Mirage', 'MI':{'name':'Mirage',
'dir':'MI', 'dir':'MI',
'abbrev':'MI', 'abbrev':'MI',
'gathdirs':['MI/en-us'], 'gathdirs':['MI/en-us'],
'gathabbrev': 'MI', 'gathabbrev': 'MI',
'gathname':'Mirage', 'gathname':'Mirage',
}, },
'VI':{'name':'Visions', 'VI':{'name':'Visions',
'dir':'VI', 'dir':'VI',
'abbrev':'VI', 'abbrev':'VI',
'gathabbrev': 'VI', 'gathabbrev': 'VI',
'gathname':'Visions', 'gathname':'Visions',
}, },
'WL':{'name':'Weatherlight', 'WL':{'name':'Weatherlight',
'dir':'WL', 'dir':'WL',
'abbrev':'WL', 'abbrev':'WL',
'gathabbrev': 'WL', 'gathabbrev': 'WL',
'gathname':'Weatherlight', 'gathname':'Weatherlight',
}, },
'TE':{'name':'Tempest', 'TE':{'name':'Tempest',
'dir':'TE', 'dir':'TE',
'abbrev':'TE', 'abbrev':'TE',
'gathabbrev': 'TE', 'gathabbrev': 'TE',
'gathname':'Tempest', 'gathname':'Tempest',
}, },
'SH':{'name':'Stronghold', 'SH':{'name':'Stronghold',
'dir':'SH', 'dir':'SH',
'abbrev':'SH', 'abbrev':'SH',
'gathabbrev': 'ST', 'gathabbrev': 'ST',
'gathname':'Stronghold', 'gathname':'Stronghold',
}, },
'EX':{'name':'Exodus', 'EX':{'name':'Exodus',
'dir':'EX', 'dir':'EX',
'abbrev':'EX', 'abbrev':'EX',
'gathabbrev': 'EX', 'gathabbrev': 'EX',
'gathname':'Exodus', 'gathname':'Exodus',
}, },
'US':{'name':'Urza\'s Saga', 'US':{'name':'Urza\'s Saga',
'dir':'US', 'dir':'US',
'abbrev':'US', 'abbrev':'US',
'gathabbrev': 'UZ', 'gathabbrev': 'UZ',
'gathname':'UrzasSaga', 'gathname':'UrzasSaga',
}, },
'UL':{'name':'Urza\'s Legacy', 'UL':{'name':'Urza\'s Legacy',
'dir':'UL', 'dir':'UL',
'abbrev':'UL', 'abbrev':'UL',
'gathabbrev': 'GU', 'gathabbrev': 'GU',
'gathname':'UrzasDestiny', 'gathname':'UrzasDestiny',
}, },
'UD':{'name':'Urza\'s Destiny', 'UD':{'name':'Urza\'s Destiny',
'dir':'UD', 'dir':'UD',
'abbrev':'UD', 'abbrev':'UD',
'gathabbrev': 'CG', 'gathabbrev': 'CG',
'gathname':'UrzasLegacy', 'gathname':'UrzasLegacy',
}, },
'MM':{'name':'Mercadian Masques', 'MM':{'name':'Mercadian Masques',
'dir':'MM', 'dir':'MM',
'abbrev':'MM', 'abbrev':'MM',
'gathabbrev': 'MM', 'gathabbrev': 'MM',
'gathname':'MercadianMasques', 'gathname':'MercadianMasques',
}, },
'NE':{'name':'Nemesis', 'NE':{'name':'Nemesis',
'dir':'NE', 'dir':'NE',
'abbrev':'NE', 'abbrev':'NE',
'gathabbrev': 'NE', 'gathabbrev': 'NE',
'gathname':'Nemesis', 'gathname':'Nemesis',
}, },
'PY':{'name':'Prophecy', 'PY':{'name':'Prophecy',
'dir':'PY', 'dir':'PY',
'abbrev':'PY', 'abbrev':'PY',
'gathabbrev': 'PR', 'gathabbrev': 'PR',
'gathname':'Prophecy', 'gathname':'Prophecy',
}, },
'IN':{'name':'Invasion', 'IN':{'name':'Invasion',
'dir':'IN', 'dir':'IN',
'abbrev':'IN', 'abbrev':'IN',
'gathabbrev': 'IN', 'gathabbrev': 'IN',
'gathname':'Invasion', 'gathname':'Invasion',
}, },
'PS':{'name':'Planeshift', 'PS':{'name':'Planeshift',
'dir':'PS', 'dir':'PS',
'abbrev':'PS', 'abbrev':'PS',
'gathabbrev': 'PS', 'gathabbrev': 'PS',
'gathname':'Planeshift', 'gathname':'Planeshift',
}, },
'AP':{'name':'Apocalypse', 'AP':{'name':'Apocalypse',
'dir':'AP', 'dir':'AP',
'abbrev':'AP', 'abbrev':'AP',
'gathabbrev': 'AP', 'gathabbrev': 'AP',
'gathname':'Apocalypse', 'gathname':'Apocalypse',
}, },
'OD':{'name':'Odyssey', 'OD':{'name':'Odyssey',
'dir':'OD', 'dir':'OD',
'abbrev':'OD', 'abbrev':'OD',
'gathabbrev': 'OD', 'gathabbrev': 'OD',
'gathname':'Odyssey', 'gathname':'Odyssey',
}, },
'TO':{'name':'Torment', 'TO':{'name':'Torment',
'dir':'TO', 'dir':'TO',
'abbrev':'TO', 'abbrev':'TO',
'gathabbrev': 'TOR', 'gathabbrev': 'TOR',
'gathname':'Torment', 'gathname':'Torment',
}, },
'JD':{'name':'Judgment', 'JD':{'name':'Judgment',
'dir':'JD', 'dir':'JD',
'abbrev':'JD', 'abbrev':'JD',
'gathabbrev': 'JUD', 'gathabbrev': 'JUD',
'gathname':'Judgment', 'gathname':'Judgment',
}, },
'ON':{'name':'Onslaught', 'ON':{'name':'Onslaught',
'dir':'ON', 'dir':'ON',
'abbrev':'ON', 'abbrev':'ON',
'gathabbrev': 'ONS', 'gathabbrev': 'ONS',
'gathname':'Onslaught', 'gathname':'Onslaught',
}, },
'LE':{'name':'Legions', 'LE':{'name':'Legions',
'dir':'LE', 'dir':'LE',
'abbrev':'LE', 'abbrev':'LE',
'gathabbrev': 'LGN', 'gathabbrev': 'LGN',
'gathname':'Legions', 'gathname':'Legions',
}, },
'SC':{'name':'Scourge', 'SC':{'name':'Scourge',
'dir':'SC', 'dir':'SC',
'abbrev':'SC', 'abbrev':'SC',
'gathabbrev': 'SCG', 'gathabbrev': 'SCG',
'gathname':'Scourge', 'gathname':'Scourge',
}, },
'MR':{'name':'Mirrodin', 'MR':{'name':'Mirrodin',
'dir':'MR', 'dir':'MR',
'abbrev':'MR', 'abbrev':'MR',
'gathabbrev': 'MRD', 'gathabbrev': 'MRD',
'gathname':'Mirrodin', 'gathname':'Mirrodin',
}, },
'DS':{'name':'Darksteel', 'DS':{'name':'Darksteel',
'dir':'DS', 'dir':'DS',
'abbrev':'DS', 'abbrev':'DS',
'gathabbrev': 'DST', 'gathabbrev': 'DST',
'gathname':'Darksteel', 'gathname':'Darksteel',
}, },
'FD':{'name':'Fifth Dawn', 'FD':{'name':'Fifth Dawn',
'dir':'FD', 'dir':'FD',
'abbrev':'FD', 'abbrev':'FD',
'gathabbrev': '5DN', 'gathabbrev': '5DN',
'gathname':'FifthDawn', 'gathname':'FifthDawn',
}, },
'CK':{'name':'Champions of Kamigawa', 'CK':{'name':'Champions of Kamigawa',
'dir':'CK', 'dir':'CK',
'abbrev':'CK', 'abbrev':'CK',
'gathabbrev': 'CHK', 'gathdirs':['CHK/en-us'],
'gathname':'ChampionsofKamigawa', 'gathabbrev': 'CHK',
}, 'gathname':'ChampionsofKamigawa',
'BK':{'name':'Betrayers of Kamigawa', },
'dir':'BK', 'BK':{'name':'Betrayers of Kamigawa',
'abbrev':'BK', 'dir':'BK',
'gathabbrev': 'BOK', 'abbrev':'BK',
'gathname':'BetrayersofKamigawa', 'gathabbrev': 'BOK',
}, 'gathname':'BetrayersofKamigawa',
'SK':{'name':'Saviors of Kamigawa', },
'dir':'SK', 'SK':{'name':'Saviors of Kamigawa',
'abbrev':'SK', 'dir':'SK',
'gathabbrev': 'SOK', 'abbrev':'SK',
'gathname':'SaviorsofKamigawa', 'gathabbrev': 'SOK',
}, 'gathname':'SaviorsofKamigawa',
'RA':{'name':'Ravnica: City of Guilds', },
'dir':'RA', 'RA':{'name':'Ravnica: City of Guilds',
'abbrev':'RA', 'dir':'RA',
'gathabbrev': 'RAV', 'abbrev':'RA',
'gathname':'RavnicaCityofGuilds', 'gathabbrev': 'RAV',
}, 'gathname':'RavnicaCityofGuilds',
'GP':{'name':'Guildpact', },
'dir':'GP', 'GP':{'name':'Guildpact',
'abbrev':'GP', 'dir':'GP',
'gathabbrev': 'GPT', 'abbrev':'GP',
'gathname':'Guildpact', 'gathabbrev': 'GPT',
}, 'gathname':'Guildpact',
'DI':{'name':'Dissension', },
'dir':'DI', 'DI':{'name':'Dissension',
'abbrev':'DI', 'dir':'DI',
'gathabbrev': 'DIS', 'abbrev':'DI',
'gathname':'Dissension', 'gathabbrev': 'DIS',
}, 'gathname':'Dissension',
'CS':{'name':'Coldsnap', },
'dir':'CS', 'CS':{'name':'Coldsnap',
'abbrev':'CS', 'dir':'CS',
'gathabbrev':'CSP', 'abbrev':'CS',
'gathname':'Coldsnap', 'gathabbrev':'CSP',
}, 'gathname':'Coldsnap',
'TS':{'name':'Time Spiral', },
'gathname':'TimeSpiralBlock', 'TS':{'name':'Time Spiral',
'gathabbrev':'(?:(?:TSP)|(?:TSB))', 'gathname':'TimeSpiralBlock',
'dir':'TS', 'gathabbrev':'(?:(?:TSP)|(?:TSB))',
'abbrev':'TS', 'dir':'TS',
'gathdirs' : ('TSP','TSB'), 'abbrev':'TS',
}, 'gathdirs' : ('TSP','TSB'),
'PC':{'name':'Planar Chaos', },
'gathname':'Planar%20Chaos', 'PC':{'name':'Planar Chaos',
'gathabbrev':'PLC', 'gathname':'Planar%20Chaos',
'dir':'PC', 'gathabbrev':'PLC',
'abbrev':'PC', 'dir':'PC',
}, 'abbrev':'PC',
'S1':{'name':'Starter 1999', },
'gathname':'Starter%201999', 'S1':{'name':'Starter 1999',
'gathabbrev':'P3', 'gathname':'Starter%201999',
'gathdirs':['P3'], 'gathabbrev':'P3',
'dir':'S1', 'gathdirs':['P3'],
'abbrev':'S1' 'dir':'S1',
}, 'abbrev':'S1'
'S2':{'name':'Starter 2000', },
'gathname':'Starter%202000', 'S2':{'name':'Starter 2000',
'gathabbrev':'P4', 'gathname':'Starter%202000',
'dir':'S1', 'gathabbrev':'P4',
'abbrev':'S1' 'dir':'S1',
}, 'abbrev':'S1'
'FS':{'name':'Future Sight', },
'gathname':'Future%20Sight', 'FS':{'name':'Future Sight',
'gathabbrev':'FUT', 'gathname':'Future%20Sight',
'gathdirs':['FUT'], 'gathabbrev':'FUT',
'dir':'FS', 'gathdirs':['FUT'],
'abbrev':'FS' 'dir':'FS',
}, 'abbrev':'FS'
} },
}
def maketransU(s1, s2, todel=""):
trans_tab = dict( zip( map(ord, s1), map(ord, s2) ) ) def maketransU(s1, s2, todel=""):
trans_tab.update( (ord(c),None) for c in todel ) trans_tab = dict( zip( map(ord, s1), map(ord, s2) ) )
return trans_tab trans_tab.update( (ord(c),None) for c in todel )
return trans_tab
imagetrans = maketransU(u'\xe2\xea\xee\xf4\xfb\xe1\xe9\xed\xf3\xfa\xfd\xe4\xeb\xef\xf6\xfc\xff\xe5\xc2\xca\xce\xd4\xdb\xc1\xc9\xcd\xd3\xda\xdd\xc4\xcb\xcf\xd6\xdc\xc5',u'aeiouaeiouyaeiouyaAEIOUAEIOUYAEIOUA',u"'/,. &;!")
imagetrans[198]=u'AE' imagetrans = maketransU(u'\xe2\xea\xee\xf4\xfb\xe1\xe9\xed\xf3\xfa\xfd\xe4\xeb\xef\xf6\xfc\xff\xe5\xc2\xca\xce\xd4\xdb\xc1\xc9\xcd\xd3\xda\xdd\xc4\xcb\xcf\xd6\xdc\xc5',u'aeiouaeiouyaeiouyaAEIOUAEIOUYAEIOUA',u"'/,. &;!")
imagetrans[198]=u'AE'
nametrans = maketransU(u'\xe2\xea\xee\xf4\xfb\xe1\xe9\xed\xf3\xfa\xfd\xe4\xeb\xef\xf6\xfc\xff\xe5\xc2\xca\xce\xd4\xdb\xc1\xc9\xcd\xd3\xda\xdd\xc4\xcb\xcf\xd6\xdc\xc5',u'aeiouaeiouyaeiouyaAEIOUAEIOUYAEIOUA')
nametrans[198]=u'AE' nametrans = maketransU(u'\xe2\xea\xee\xf4\xfb\xe1\xe9\xed\xf3\xfa\xfd\xe4\xeb\xef\xf6\xfc\xff\xe5\xc2\xca\xce\xd4\xdb\xc1\xc9\xcd\xd3\xda\xdd\xc4\xcb\xcf\xd6\xdc\xc5',u'aeiouaeiouyaeiouyaAEIOUAEIOUYAEIOUA')
nametrans[198]=u'AE'
cleanuptrans = {ord(u'\r'):u' ',
ord(u'"'):u'&quot;', cleanuptrans = {ord(u'\r'):u' ',
ord(u'\u2018'):ord(u'\''), ord(u'"'):u'&quot;',
ord(u'&'):u'&amp;', ord(u'\u2018'):ord(u'\''),
} ord(u'&'):u'&amp;',
}
colorSymbols = {'red':'R',
'green' : 'G', colorSymbols = {'red':'R',
'blue':'U', 'green' : 'G',
'black':'B', 'blue':'U',
'white':'W'} 'black':'B',
symbolColors = dict([reversed(a) for a in colorSymbols.items()]) 'white':'W'}
basic_lands = ('Mountain','Forest','Island','Swamp','Plains') symbolColors = dict([reversed(a) for a in colorSymbols.items()])
color_re = re.compile(".*(?P<color>[Rr]ed|[Gg]reen|[Bb]lue|[Bb]lack|[Ww]hite).*") basic_lands = ('Mountain','Forest','Island','Swamp','Plains')
mana_re = re.compile(".*Symbol_(?P<type>.*)_mana\.gif.*") color_re = re.compile(".*(?P<color>[Rr]ed|[Gg]reen|[Bb]lue|[Bb]lack|[Ww]hite).*")
tap_re = re.compile(".*tap.gif.*") mana_re = re.compile(".*Symbol_(?P<type>.*)_mana\.gif.*")
basicLand_re = re.compile("\[(?P<mana>.)\]") tap_re = re.compile(".*tap.gif.*")
split_re = re.compile("(?P<t1>.*) // (?P<name2>.*) (?P<mana2>\{.*\}) (?P<type2>.*) (?P<t2>.*)") basicLand_re = re.compile("\[(?P<mana>.)\]")
id_re = re.compile(".*id=(?P<id>\d*).*") split_re = re.compile("(?P<t1>.*) // (?P<name2>.*) (?P<mana2>\{.*\}) (?P<type2>.*) (?P<t2>.*)")
reminder_re = re.compile('(\A[^\(]*)|((?<=\))[^\(]*)') id_re = re.compile(".*id=(?P<id>\d*).*")
reminder_re = re.compile('(\A[^\(]*)|((?<=\))[^\(]*)')
_stripReminderText = True;
_stripReminderText = True;
def replaceSymbols(soup):
for symbol in soup.findAll('img'): def replaceSymbols(soup):
m = color_re.match(str(symbol['src'])) for symbol in soup.findAll('img'):
if m: m = color_re.match(str(symbol['src']))
s = colorSymbols[m.group('color').lower()] if m:
symbol.replaceWith('{' + s + '}') s = colorSymbols[m.group('color').lower()]
symbol.replaceWith('{' + s + '}')
m = mana_re.match(str(symbol))
if m: m = mana_re.match(str(symbol))
if m.group('type') == "Snow": if m:
symbol.replaceWith('{S}') if m.group('type') == "Snow":
else: symbol.replaceWith('{S}')
symbol.replaceWith('{' + m.group('type') + '}') else:
symbol.replaceWith('{' + m.group('type') + '}')
m = tap_re.match(str(symbol))
if m: m = tap_re.match(str(symbol))
symbol.replaceWith('{T}') if m:
symbol.replaceWith('{T}')
return soup
return soup
def getCardTypes(soup):
types = [t.strip() def getCardTypes(soup):
for t in soup('td')[2]('font')[0].string.split('-',1)] types = [t.strip()
if (len(types) == 2): for t in soup('td')[2]('font')[0].string.split('-',1)]
supertype = types[0] if (len(types) == 2):
subtype = types[1] supertype = types[0]
else: subtype = types[1]
supertype = types[0] else:
subtype = '' supertype = types[0]
# replace entities, since gccg doesn't undertand them in attributes subtype = ''
subtype = subtype.replace("&#226;", u"\342") # replace entities, since gccg doesn't undertand them in attributes
subtype = subtype.replace("&#226;", u"\342")
return supertype, subtype
return supertype, subtype
def cleanupHTMLText(htmlText, stripReminder = _stripReminderText):
for i in htmlText.findAll('br'): def cleanupHTMLText(htmlText, stripReminder = _stripReminderText):
i.replaceWith(' ') for i in htmlText.findAll('br'):
for i in htmlText.findAll('i'): i.replaceWith(' ')
i.replaceWith(''.join(i.contents)) for i in htmlText.findAll('i'):
for i in htmlText.findAll('b'): i.replaceWith(''.join(i.contents))
i.replaceWith(''.join(i.contents)) for i in htmlText.findAll('b'):
i.replaceWith(''.join(i.contents))
text = htmlText('font')[0].renderContents(None)
# add text for Basic Land text = htmlText('font')[0].renderContents(None)
m = basicLand_re.match(text) # add text for Basic Land
if m: m = basicLand_re.match(text)
text = u"{T}: Add {" + m.group('mana') + u"} to your mana pool." if m:
if text == u"&nbsp;": text = u"{T}: Add {" + m.group('mana') + u"} to your mana pool."
text = u"" if text == u"&nbsp;":
text = u""
text = text.translate(cleanuptrans)
text = text.translate(cleanuptrans)
if stripReminder:
text = ''.join([''.join(m) for m in reminder_re.findall(text)]) if stripReminder:
text = ''.join([''.join(m) for m in reminder_re.findall(text)])
return text
return text