国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python3生成隨機數實例

2019-11-25 18:07:57
字體:
來源:轉載
供稿:網友

本文實例講述了python3生成隨機數的方法。分享給大家供大家參考。具體實現方法如下:

該實例是根據一本書上看到過一個隨機數的小程序,經過自己改動,變為了一個猜數字的小游戲,現在在python3下重寫了一遍。

這是一個控制臺下的猜數程序,winxp+python3.2+eric5和IDLE測試通過,但直接用winxp的命令行運行有問題,原因還未知,慢慢找。ubuntu+python3.1測試通過。

具體實現代碼如下:

復制代碼 代碼如下:
# -*- coding: utf-8 -*-
import Image,ImageDraw,ImageFont
import random
import math, string 
 
class RandomChar():
  """用于隨機生成漢字"""
  @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, 30), 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)

希望本文所述對大家的Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 邳州市| 五家渠市| 阿勒泰市| 华坪县| 普陀区| 定州市| 临夏市| 株洲市| 铜陵市| 祁阳县| 留坝县| 通江县| 华坪县| 阿合奇县| 军事| 沙坪坝区| 邛崃市| 宁阳县| 阿瓦提县| 开平市| 曲阜市| 苏尼特左旗| 鸡泽县| 昭通市| 木兰县| 安宁市| 新民市| 南丰县| 五华县| 莲花县| 尉氏县| 济南市| 东丽区| 伽师县| 兴仁县| 枣强县| 绍兴市| 洞口县| 修文县| 许昌县| 独山县|