In this paper, we describe the method of generating random numbers in Python3. Share to everyone for your reference. The implementation method is as follows:
The example is based on a book saw a random number of small programs, after their own changes, into a guess the number of small game, now Python3 under the rewrite again.
This is a console under the guessing program, WINXP+PYTHON3.2+ERIC5 and idle test pass, but directly with the WinXP command line run a problem, the reason is unknown, slowly find. ubuntu+python3.1 test passed.
The specific implementation code is as follows:
The code is as follows:
#-*-Coding:utf-8-*-
Import Image,imagedraw,imagefont
Import Random
Import Math, string
Class Randomchar ():
"" for random generation of Chinese characters "" "
@staticmethod
Def Unicode ():
val = Random.randint (0x4e00, 0X9FBF)
Return UNICHR (Val)
@staticmethod
Def GB2312 ():
Head = Random.randint (0xb0, 0xCF)
BODY = Random.randint (0xA, 0xF)
tail = random.randint (0, 0xF)
val = (head << 8) | (Body << 4) | Tail
str = "%x"% val
return Str.decode (' hex '). Decode (' gb2312 ')
Class Imagechar ():
def __init__ (self, fontcolor = (0, 0, 0),
Size = (100, 40),
Fontpath = ' WQY.TTC ',
BgColor = (255, 255, 255),
FontSize = 20):
Self.size = Size
Self.fontpath = Fontpath
Self.bgcolor = BgColor
Self.fontsize = FontSize
Self.fontcolor = FontColor
Self.font = Imagefont.truetype (Self.fontpath, Self.fontsize)
Self.image = image.new (' RGB ', size, BgColor)
def rotate (self):
Self.image.rotate (random.randint (0), expand=0)
def drawText (self, POS, txt, fill):
Draw = Imagedraw.draw (self.image)
Draw.text (POS, TXT, font=self.font, Fill=fill)
Del Draw
def randrgb (self):
Return (random.randint (0, 255),
Random.randint (0, 255),
Random.randint (0, 255))
def randpoint (self):
(width, height) = self.size
Return (Random.randint (0, width), random.randint (0, height))
def randline (self, num):
Draw = Imagedraw.draw (self.image)
For I in range (0, num):
Draw.line ([Self.randpoint (), Self.randpoint ()], Self.randrgb ())
Del Draw
def randchinese (self, num):
Gap = 5
Start = 0
For I in range (0, num):
char = Randomchar (). GB2312 ()
x = start + self.fontsize * i + random.randint (0, GAP) + gap * I
Self.drawtext ((x, Random.randint ( -5, 5)), Randomchar (). GB2312 (), Self.randrgb ())
Self.rotate ()
Self.randline (18)
def save (Self, path):
Self.image.save (PATH)
Hopefully this article will help you with Python programming.