Monday, June 30, 2008

Handle Chinese in Python while using Pydev and Pygame

I never really try to program anything that has to deal with the Chinese before, even though I'm a 100% Chinese. However, I recently came accross a problem of renaming some of my files, which have Chinese in them. I decided to write a little script to do the task in order to practice my Python skill. Very soon I encountered the unicode problem. After some searching and hacking, I was able to solve the problem. To avoid forgetting the solution, I put down this sample program as my note for future reference.

To display the string correctly in the eclipse console, set the encoding to UTF-8 under "Run Dialog => Common". Also in the project properties, set the "Text file encoding" to UTF-8.

# -*- coding: UTF-8 -*-

import sys
import pygame
from pygame.locals import QUIT

pygame
.init()

# This string contains both simplified Chinese and traditional Chinese.
unicode_string
= u'Hello Unicode String!简体!繁體!'
# Test the string in Eclipse console.
print unicode_string

# Must use a font that is capable of displaying Chinese.
string_font
= pygame.font.SysFont('simsun&nsimsun', 16, True, False);
string_surface
= string_font.render(unicode_string, True, (0, 255, 0))

# Display the string to the pygame screen.
screen
= pygame.display.set_mode((300, 40), 0, 32)

while True:
# Missing this event handle loop will cause the pygame window freezes somehow.
for event in pygame.event.get():
if event.type == QUIT:
exit()

screen
.fill((0, 0, 0))
screen
.blit(string_surface, (10, 10))
pygame
.display.update()


1 comment:

Anonymous said...

Need to indent the 3 lines at the bottom as part of the while loop before it will work.