Math和Graphics:Analog Clock示例程序
本章介绍Python的math模块,该模块可以执行计算,如常见的三角正弦函数、余弦函数、正切函数等。

使用正弦和余弦函数绘制圆
创建Anlog Clock示例程序

关于math模块
https://docs.python.org/3/library/math.html
https://docs.python.org/2.7/library/math.html

math.cos(x)
    Return the cosine of x radians.

math.sin(x)
    Return the sine of x radians.

math.tan(x)
    Return the tangent of x radians.

math.degrees(x)
    Convert angle x from radians to degrees.

math.radians(x)
    Convert angle x from degrees to radians.

math.pi
    The mathematical constant π = 3.141592..., to available precision.

math.e
    The mathematical constant e = 2.718281..., to available precision.

注意:
    对于负数的取模
    余数应该是大于等于0小于该数绝对值的那个数,比方说(-5)%3=1,认为-5=3*(-2)+1

书中给出的示例可以优化。

Draw circle in hard way

import sys,pygame,math,random
from pygame.locals import *
pygame.init()

screen=pygame.display.set_mode((600,500))
pygame.display.set_caption("Circle Demo")
angle=0
color=random.randint(0,255),random.randint(0,255),random.randint(0,255)
while True:
    for event in pygame.event.get():
        if event.type==QUIT:
            sys.exit()
    keys=pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        sys.exit()
    
    screen.fill((255,255,255))

x=300
    y=250
    radius=200
    
    
    circle_x=x+radius*math.cos(math.radians(angle))
    circle_y=y+radius*math.sin(math.radians(angle))

pygame.draw.circle(screen,color,(int(circle_x),int(circle_y)),10,0)
    angle+=1
    if angle>359:
        color=random.randint(0,255),random.randint(0,255),random.randint(0,255)
        angle=0    
    
    pygame.display.update()

Anlog Clock示例程序

import sys,datetime,pygame,math
from pygame.locals import *
from datetime import datetime,date,time
pygame.init()
def print_text(font,x,y,text,color=(255,255,255)):
    imgtext=font.render(text,True,color)
    screen.blit(imgtext,(x,y))

def wrap_angle(angle):
    return angle%360

#main program begins
screen=pygame.display.set_mode((600,500))
pygame.display.set_caption("Anlog Clock Demo")
font=pygame.font.Font(None,36)
orange=220,180,0
white=255,255,255
yellow=255,255,0
pink=255,100,100

pos_x=300
pos_y=250
radius=250
angle=360

#repeating loop
while True:
    for event in pygame.event.get():
        if event.type==QUIT:
            sys.exit()
    keys=pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        sys.exit()
    
    screen.fill((0,0,100))
    #draw one step around the circle
    pygame.draw.circle(screen,white,(pos_x,pos_y),radius,6)
    
    #draw the clock numbers1-12
    for n in range(1,13):
        angle=math.radians(n*30-90)
        x=(radius-20)*math.cos(angle)+pos_x-10
        y=(radius-20)*math.sin(angle)+pos_y-10
        print_text(font,int(x),int(y),str(n))
    
    #get the time of day
    today=datetime.today()
    hours=today.hour%12
    minutes=today.minute
    seconds=today.second
    
    #draw the hours hand
    hour_angle=wrap_angle(hours*30-90)
    hour_angle=math.radians(hour_angle)
    hour_x=pos_x+math.cos(hour_angle)*(radius-80)
    hour_y=pos_y+math.sin(hour_angle)*(radius-80)
    target_h=(int(hour_x),int(hour_y))
    pygame.draw.line(screen,pink,(pos_x,pos_y),target_h,25)
    
    #draw the minutes hand
    minute_angle=wrap_angle(minutes*6-90)
    minute_angle=math.radians(minute_angle)
    minute_x=pos_x+math.cos(minute_angle)*(radius-60)
    minute_y=pos_y+math.sin(minute_angle)*(radius-60)
    target_m=(int(minute_x),int(minute_y))
    pygame.draw.line(screen,orange,(pos_x,pos_y),target_m,12)
    
    #draw the seconds hand
    second_angle=wrap_angle(seconds*6-90)
    second_angle=math.radians(second_angle)
    second_x=pos_x+math.cos(second_angle)*(radius-40)
    second_y=pos_y+math.sin(second_angle)*(radius-40)
    target_s=(int(second_x),int(second_y))
    pygame.draw.line(screen,yellow,(pos_x,pos_y),target_s,6)
    
    #cover the center
    pygame.draw.circle(screen,white,(pos_x,pos_y),20)

print_text(font,0,0,str(hours)+":"+str(minutes)+":"+str(seconds))

pygame.display.update()

wrap_angle函数是多余的,因为在三角函数的运算中+-360°对于结果没有影响。
去除所有带有 wrap_angle()的部分,程序运行正常。

1、修改circle程序,以使得在每个角度绘制不同的形状,而不是绘制一个小的填充的圆。
import sys,pygame,math,random
from pygame.locals import *
pygame.init()

screen=pygame.display.set_mode((600,500))
pygame.display.set_caption("Circle Demo")
angle=0
color=random.randint(0,255),random.randint(0,255),random.randint(0,255)
while True:
    for event in pygame.event.get():
        if event.type==QUIT:
            sys.exit()
    keys=pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        sys.exit()
    
    screen.fill((0,0,0))

x=300
    y=250
    radius=200
    
    
    circle_x=int(x+radius*math.cos(math.radians(angle)))
    circle_y=int(y+radius*math.sin(math.radians(angle)))
    
    if angle%3==0:
        pygame.draw.circle(screen,color,(circle_x,circle_y),12)
    elif angle%3==1:
        pygame.draw.rect(screen,color,(circle_x-10,circle_y-10,20,20))
    elif angle%3==2:
        pygame.draw.ellipse(screen,color,(circle_x-15,circle_y-10,30,20))

angle+=1
    if angle>359:
        color=random.randint(0,255),random.randint(0,255),random.randint(0,255)
        angle=0    
    
    pygame.display.update()

感觉画了一个会蠕动的小东西,有一点意思。

2、Analog Circle变得更好看些。这个我没去实现,我把时针的角度做了微调,感觉更符合习惯。现在
时针不会一直指向整点的位置了,而是会根据分钟数指向两个整点之间。
import sys,datetime,pygame,math
from pygame.locals import *
from datetime import datetime,date,time
pygame.init()
def print_text(font,x,y,text,color=(255,255,255)):
    imgtext=font.render(text,True,color)
    screen.blit(imgtext,(x,y))

def wrap_angle(angle):
    return angle%360

#main program begins
screen=pygame.display.set_mode((600,500))
pygame.display.set_caption("Anlog Clock Demo")
font=pygame.font.Font(None,36)
orange=220,180,0
white=255,255,255
yellow=255,255,0
pink=255,100,100

pos_x=300
pos_y=250
radius=250
angle=360

#repeating loop
while True:
    for event in pygame.event.get():
        if event.type==QUIT:
            sys.exit()
    keys=pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        sys.exit()
    
    screen.fill((0,0,100))
    #draw one step around the circle
    pygame.draw.circle(screen,white,(pos_x,pos_y),radius,6)
    
    #draw the clock numbers1-12
    for n in range(1,13):
        angle=math.radians(n*30-90)
        x=(radius-20)*math.cos(angle)+pos_x-10
        y=(radius-20)*math.sin(angle)+pos_y-10
        print_text(font,int(x),int(y),str(n))
    
    #get the time of day
    today=datetime.today()
    hours=today.hour%12
    minutes=today.minute
    seconds=today.second
    
    #draw the hours hand
    hour_angle=wrap_angle(hours*30-90+minutes*0.5)  #对比原来的程序修改了这一行。
    hour_angle=math.radians(hour_angle)
    hour_x=pos_x+math.cos(hour_angle)*(radius-80)
    hour_y=pos_y+math.sin(hour_angle)*(radius-80)
    target_h=(int(hour_x),int(hour_y))
    pygame.draw.line(screen,pink,(pos_x,pos_y),target_h,25)
    
    #draw the minutes hand
    minute_angle=wrap_angle(minutes*6-90)
    minute_angle=math.radians(minute_angle)
    minute_x=pos_x+math.cos(minute_angle)*(radius-60)
    minute_y=pos_y+math.sin(minute_angle)*(radius-60)
    target_m=(int(minute_x),int(minute_y))
    pygame.draw.line(screen,orange,(pos_x,pos_y),target_m,12)
    
    #draw the seconds hand
    second_angle=wrap_angle(seconds*6-90)
    second_angle=math.radians(second_angle)
    second_x=pos_x+math.cos(second_angle)*(radius-40)
    second_y=pos_y+math.sin(second_angle)*(radius-40)
    target_s=(int(second_x),int(second_y))
    pygame.draw.line(screen,yellow,(pos_x,pos_y),target_s,6)
    
    #cover the center
    pygame.draw.circle(screen,white,(pos_x,pos_y),20)

print_text(font,0,0,str(hours)+":"+str(minutes)+":"+str(seconds))

pygame.display.update()

看起来更符合习惯了。至于美观的要求就算了。

Python游戏编程入门4的更多相关文章

  1. Python游戏编程入门

    <Python游戏编程入门>这些文章负责整理在这本书中的知识点.注意事项和课后习题的尝试实现.并且对每一个章节给出的最终实例进行分析和注释. 初识pygame:pie游戏pygame游戏库 ...

  2. Python游戏编程入门 中文pdf扫描版|网盘下载内附地址提取码|

    Python是一种解释型.面向对象.动态数据类型的程序设计语言,在游戏开发领域,Python也得到越来越广泛的应用,并由此受到重视. 本书教授用Python开发精彩游戏所需的[]为重要的该你那.本书不 ...

  3. Python游戏编程入门2

    I/O.数据和字体:Trivia游戏 本章包括如下内容:Python数据类型获取用户输入处理异常Mad Lib游戏操作文本文件操作二进制文件Trivia游戏 其他的不说,我先去自己学习文件类型和字符串 ...

  4. python编程学习--Pygame - Python游戏编程入门(0)---转载

    原文地址:https://www.cnblogs.com/wuzhanpeng/p/4261015.html 引言 博客刚开,想把最近学习的东西记录下来,算是一种笔记.最近打算开始学习Python,因 ...

  5. Pygame - Python游戏编程入门(0) 转

    博客刚开,想把最近学习的东西记录下来,算是一种笔记.最近打算开始学习Python,因为我感觉Python是一门很有意思的语言,很早以前就想学了(碍于懒),它的功能很强大,你可以用它来做科学运算,或者数 ...

  6. Pygame - Python游戏编程入门

    >>> import pygame>>> print(pygame.ver)1.9.2a0 如果没有报错,应该是安装好了~ 如果报错找不到模块,很可能是安装版本的问 ...

  7. Python游戏编程入门3

    用户输入:Bomb Catcher游戏本章介绍使用键盘和鼠标获得用户输入.包括如下主题:学习pygame事件学习实时循环学习键盘和鼠标事件学习轮询键盘和鼠标的状态编写Bomb Catcher游戏 1本 ...

  8. PC游戏编程(入门篇)(前言写的很不错)

    PC游戏编程(入门篇) 第一章 基石 1. 1 BOSS登场--GAF简介 第二章 2D图形程式初体验 2.l 饮水思源--第一个"游戏"程式 2.2 知其所以然一一2D图形学基础 ...

  9. 分享《Python 游戏编程快速上手(第3版)》高清中文版PDF+高清英文版PDF+源代码

    通过编写一个个小巧.有趣的游戏来学习Python,通过实例来解释编程的原理的方式.14个游戏程序和示例,介绍了Python基础知识.数据类型.函数.流程控制.程序调试.流程图设计.字符串操作.列表和字 ...

随机推荐

  1. 本地浏览器Websql数据库操作

    前几天看到一个小姐姐问我一个添加修改的我看了一下案例弄了一个出来.... 参考案例:HTML5本地数据库(WebSQL)[转] - 狂流 - 博客园  https://www.cnblogs.com/ ...

  2. python读取数据库并把数据写入本地文件

    一,介绍 上周用jmeter做性能测试时,接口B传入的参数需要依赖接口A生成的借贷申请ID,接口A运行完需要把生成的借贷申请ID导出来到一个文件,作为参数传给接口B,刚开始的时候,手动去数据库倒, 倒 ...

  3. less命令查看文件时的常用操作

    下键或者回车:往下一行 D:往下半页 空格和f:往下一页 上键:往上一行 B:往上一页 shift+G:直接切到末尾 ?+搜索条件:从下往上搜索 /+搜索条件:从上往下搜索

  4. python练习题-day22

    1.编写程序, 编写一个学生类, 要求有一个计数器的属性, 统计总共实例化了多少个学生 class Student: count=0 def __init__(self,name,age,gender ...

  5. 《图解HTTP》读书笔记(二:各种协议与HTTP协议之间的关系)

    涉及到DNS协议.TCP协议.IP协议,话不多说,上图:

  6. 66.ajax--ajax请求多个url解决办法

    ajax请求多个url解决办法 以下四种方法是我找的,我也进行实践过. 测试中有四个请求接口,原本需要13S,用了第三种方法缩减到7S,但是仍不能达到2S以内. 所以仅供参考,待我找到能缩减到2S以内 ...

  7. C++ 赋值构造函数的返回值到底有什么用?且返回值是否为引用类型有什么区别吗?

    首先定义类Person class Person{ public: string name; Person()=default; //默认构造函数 Person(string nam):name(na ...

  8. zabbix监控实战<2>----zabbix-server的安装与部署

    第一章     zabbix-server的安装与部署 1.1  环境部署 eth0                               eth1 master      10.0.0.71  ...

  9. 在Ubuntu中,vi命令编辑异常

    在Ubuntu中,进入vi命令的编辑模式,发现按方向键不能移动光标,而是会输出ABCD,以及退格键也不能正常删除字符.这是由于Ubuntu预装的是vim-tiny,而我们需要使用的是vim-full, ...

  10. 201902<<百岁人生>>

    过年的那段时间,在家看到公司推荐的10本2019年必读书籍,里面有这本书,于是就开始了.... 第一次这么认真的看这类书籍,看完之后感触颇多,毕竟这个问题我从没思考过,很少站在这样的高度去看所有方方面 ...