The text before

These days I am busy writing a game program for a graduation activity of the college… I’m still in charge of MMP. So are in the rush to make this game program!! Today I finally completed the logical design, just need to add some pictures later, and expand the question bank!

The body of the

In fact, today is mainly to solve a problem, that is why can not display Chinese? !!!!!

In the beginning, I did copy a file from Windows, which resulted in a BOM or something. But it was worked out. And spend all day coding and decoding… Only to find out in the end, there is no egg!! Both GBK and UTF-8 are boxes on my interface. Garbled code!! Voji ah!!

Then I happened to do a search on how PyGame displays Chinese. Because the previous search python display Chinese, the result is asking me to encode and decode!! Oh my god!!

As a result, a lot of answers!!

The most useful is this:

How to display Chinese in PyGame

Very useful!!

There are two ways to solve the Chinese display problem.

  • The first method: take away font Download a Chinese font file from the Internet, put this file in the same folder with our program, if the file name is Chinese, change it to English file name. For example, download mini Jane felt pen black. TTF, change the file name to MNJZBH. TTF, and change the first sentence of the program to:ZiTiDuiXiang=pygame.font.Font('mnjzbh.ttf',32)In this way, Chinese will display correctly. However, some downloaded font files can not be displayed normally, you can download a few more try.
  • Second method: Use the system font to change the first sentence of the program to:ZiTiDuiXiang=pygame.font.SysFont('SimHei',32)That is to use SysFont instead of Font, and use the system’s own Font, can also normally display Chinese. However, the system has a lot of fonts, to choose the Chinese font. How to check which fonts are in the system? You can use:
ZiTi=pygame.font.get_font()
for i in ZiTi:
   print(i)
Copy the code

To view all system fonts.

So I went to the two fonts.

Download the address here, some pay, some free!

Webmaster font is free of charge. To find!


And then today also found a few good websites, recommended to everyone!!

RGB color table is very complete and intimate color table, much stronger than the 114

www.pygame.org/docs/ref/im…

Writing games with Python and Pygame – From beginner to Master (1) Excellent personal blogger content. Deeply touched!

Below is my code and picture file!

#! /usr/bin/python
#coding:utf-8

import time
import math
import pygame
import sys
from pygame.locals import *
white=255.255.255
blue = 1.1.200

def print_text( font, x, y, text, color=white, shadow=True ):
    if shadow:
        imgText = font.render(text,  True,  (0.0.0))
        screen.blit(imgText,  (x2 -,  y2 -))
    imgText=font.render(text,  True,  color)
    screen.blit(imgText,  (x,  y))


class Trivia(object):
    def __init__(self, filename):
        self.data = []
        self.current = 0
        self.total = 0
        self.correct = 0
        self.score1 = 0
        self.score2 = 0
        self.scored = False
        self.failed = False
        self.wronganswer = 0
        self.colors = [white,  white,  white,  white]

        f=open(filename,  'r', encoding="utf-8")
        tdata = f.readlines()
        for x in tdata:
            self.data.append(x.strip())
            self.total += 1

    def show_question(self):
        print_text(font1,  width/5, height/15."Mechanical School level 14" "Brainstorming" "Knowledge contest!", blue)
        print_text(font3,  width/3, height/20*19."*** The student Union of Grade 14, School of Mechanical Engineering reserves the right of final interpretation ***", white)
        print_text(font2,  width/12, height/25*4."SCORE1", red)
        print_text(font2,  width/10*8 , height/25*4."SCORE2", red)
        self.correct = int(self.data[self.current+5])
        question=int(self.current/6) +1
        print_text(font1, width/10*4, height/20*4."Question "+str(question), orange)
        fontsize = int(1000/len(self.data[self.current]))
        if fontsize > 50:
            fontsize = 50
        if fontsize < 30:
            fontsize = 30
        if len(self.data[self.current])>35:
            str1 = self.data[self.current][0:35]
            if len(self.data[self.current])<=70:
                str2 = self.data[self.current][35:]
                print_text(pygame.font.Font('piaoyi.ttf',  fontsize),  width/6,  height/20*6,  str1, yellow)
                print_text(pygame.font.Font('piaoyi.ttf',  fontsize),  width/6,  height/20*7,  str2, yellow)
            else:
                str2 = self.data[self.current][35:70]
                str3 = self.data[self.current][70:]
                print_text(pygame.font.Font('piaoyi.ttf'.20),  width/6,  height/60*17,  str1, yellow)
                print_text(pygame.font.Font('piaoyi.ttf'.20),  width/6,  height/60*19,  str2, yellow)
                print_text(pygame.font.Font('piaoyi.ttf'.20),  width/6,  height/60*21,  str2, yellow)
        else:
            print_text(pygame.font.Font('piaoyi.ttf',  fontsize),  width/6,  height/20*6,  self.data[self.current],  yellow)

        if self.scored:
            self.colors[self.correct- 1] = green
        elif self.failed:
            self.colors[self.wronganswer- 1] = red
        print_text(font1, width/10*4, height/20*8."Answer:",  orange)
        maxlen = 0
        for i in range(4) :if len(self.data[self.current+i+1])>maxlen:
                maxlen = len(self.data[self.current+i+1])
        print_text(font2,  width/20*9-maxlen*20,  height/20*10."1 - >"+self.data[self.current+1],  self.colors[0])
        print_text(font2,  width/20*9-maxlen*20,  height/20*12."2->  "+self.data[self.current+2],  self.colors[1])
        print_text(font2,  width/20*9-maxlen*20,  height/20*14."3->  "+self.data[self.current+3],  self.colors[2])
        print_text(font2,  width/20*9-maxlen*20,  height/20*16."4->  "+self.data[self.current+4],  self.colors[3])
        print_text(font2,  width/8,  height/5+10,  str(self.score1),  red)
        print_text(font2,  width/20*17,  height/5+10, str(self.score2),  red)

    def handle_input(self, number):
        if not self.scored:
            if number == self.correct :
                self.scored = True
            else:
                self.failed = True
                self.wronganswer = number
        self.show_question()

    def next_question(self):
        if self.scored or self.failed:
            self.failed = False
            self.scored = False
            self.correct = 0
            self.colors = [white, white, white, white]
            self.current += 6
            if self.current >= self.total:
                self.current = 0

pygame.init()
width,  height = 1378.776
screen = pygame.display.set_mode((width, height))
background = pygame.image.load("kate.png").convert()
frontground = pygame.image.load("dragon.png").convert_alpha()
pygame.display.set_caption("Mechanical School level 14" "Brainstorming" "Knowledge contest!")
font1 = pygame.font.Font('piaoyi.ttf'.60)
font2 = pygame.font.Font('piaoyi.ttf'.40)
font3 = pygame.font.Font('piaoyi.ttf'.20)

cyan = 0.255.255
yellow = 255.255.0
purple = 255.0.255
green = 0.255.0
red = 255.0.0
gray = 63.63.63
black = 8.8.8
orange = 255.165.0
Magenta = 255.0.255
trivia = Trivia("test.txt")

while True:
    screen.blit(background,  (0.0))
    # screen. The fill ((0255, 0))
    # screen.blit(frontground, (-100, 88))
    trivia.show_question()
    pygame.display.update()
    Flag = True
    while Flag:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_ESCAPE:
                    sys.exit()
                elif event.key == pygame.K_w:
                    trivia.handle_input(1)
                elif event.key == pygame.K_h:
                    trivia.score1 += 2
                    pygame.display.update()
                elif event.key == pygame.K_j:
                    trivia.score2 += 2
                    pygame.display.update()
                elif event.key == pygame.K_k:
                    if trivia.score1>0:
                        trivia.score1 -= 1
                    pygame.display.update()
                elif event.key == pygame.K_l:
                    if trivia.score2>0:
                        trivia.score2 -= 1
                    pygame.display.update()
                elif event.key == pygame.K_a:
                    trivia.handle_input(2)
                elif event.key == pygame.K_s:
                    trivia.handle_input(3)
                elif event.key == pygame.K_d:
                    trivia.handle_input(4)
                elif event.key == pygame.K_n:
                    trivia.next_question()
                    Flag = False
                pygame.display.update()
Copy the code

In the same folder named test. TXT, test content:

Which system is noise harmful to the human body: cardiovascular system digestive system respiratory system urinary system1People on Earth see a clear sky as blue because the sea water on the continents reflects the sky blue. The blue reflected by objects in the sun is blue. The blue light in the sun is scattered blue by particles in the sky3Plants are food for many animals, but they themselves mainly use photosynthesis to make food. In addition to using solar energy and chlorophyll, plants also need carbon dioxide, carbon monoxide, oxygen and nitric oxide from the air for photosynthesis1The following types of water should not be used: after a meal drink a lot of water thirsty water according to the composition of dietary nutrients and other factors increase or decrease the amount of water to drink after exercise water1Mammals, the highest vertebrate, rely on the mother's mammary gland to secrete milk to feed their young. Which of the following is a mammal? Dolphins seahorses starfish sea dragons1The ping-pong ball is flat. What can I do to make it bulge? Put it in the freezer and blow it in and soak it in boiling water and hold it in your hand3Why do bats catch mosquitoes at night without their eyes? Ultrasonic wave electromagnetic wave brainwave mindfulness1Freeze food with ice, preferably on the top, bottom, middle and outside of the food2
Copy the code

There are two font files that can’t be uploaded? !!!!! Heartache.

After the body

Let’s go ahead and do some effect demonstration, although ugly. But mine works! Just expand the question bank and beautify the interface. Kidding!!