Pygame简单入门学习笔记

首先先放出我的第一个使用Pygame写的程序“菜虚鲲大战蔡徐坤”。 

import random
import pygame
import sys
import time
pygame.init()#初始化
#主窗口
screen_image = pygame.display.set_mode((800,600))#设置分辨率
screen_rect = screen_image.get_rect()

#标题栏
pygame.display.set_caption('人工智能2x0xXXX2021xxxxxx')#设置文件名

#飞船
ship_image = pygame.image.load('image/cai1.bmp')
ship_rect = ship_image.get_rect()
ship_rect.center = screen_rect.center#居中对齐

#子弹1
bullet_rect = pygame.Rect(0,0,3,15)
bullet_rect.midbottom = ship_rect.midtop
bullet_rect.x=0
bullet_rect.y=0

#散弹枪
grape_rect = pygame.Rect(0,0,3,15)
grape_rect.midbottom=ship_rect.midtop
grape_rect.x=bullet_rect.x+5
grape_rect.x=0
grape_rect.y=0

#怪物

monster_image = pygame.image.load('image/cai2.bmp')
monster_rect = ship_image.get_rect()
monster_rect.x = 360

#文字
txt_font = pygame.font.SysFont(None,48)
txt_image = txt_font.render('caixukun',True,(60,60,60),(255,0,0))
txt_rect = txt_image.get_rect()


while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()
        elif event.type==pygame.KEYDOWN:
            if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                ship_rect.x-=20
            if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                ship_rect.x+=20
            if event.key == pygame.K_UP or event.key == pygame.K_w:
                ship_rect.y-=20
            if event.key == pygame.K_DOWN or event.key == pygame.K_s:
                ship_rect.y+=20
            if event.key == pygame.K_j:
                bullet_rect.midbottom = ship_rect.midtop
            if event.key == pygame.K_k:
                #bullet_rect.midbottom = ship_rect.midtop
                grape_rect.midbottom = ship_rect.midtop
                grape_rect.x+=10

    # if monster_rect.x == bullet_rect.x or monster_rect.y == bullet_rect.y:
    #     monster_rect.y = 0
    #     monster_rect.x +=10
    #     pass
    # if monster_rect.y-bullet_rect.y<=10:
    #     if bullet_rect.x <= monster_rect.x:
    #         monster_rect.x+=1
    #         pass
    #     elif bullet_rect.x > monster_rect.x:
    #         monster_rect.x-=1
    #     pass
    if abs(monster_rect.x-bullet_rect.x)<=100 and abs(monster_rect.y-bullet_rect.y)<=100:
        bullet_rect.y = 0
        monster_rect.y=0
        monster_rect.x = random.randint(0,600)
        pass

    monster_rect.y+=1
    bullet_rect.y-=20
    grape_rect.y-=1
    time.sleep(0.05)
    #绘制图像
    screen_image.fill((0,128,128))#设置背景颜色
    screen_image.blit(ship_image,ship_rect)#设置飞船
    screen_image.blit(monster_image,monster_rect)
    pygame.draw.rect(screen_image,(60,60,60),bullet_rect)
    pygame.draw.rect(screen_image,(80,80,80),grape_rect)
    screen_image.blit(txt_image,txt_rect)
    pygame.display.flip()#刷新

我在学习python的时候,学习的方向以及顺序都跟去年学习C++差不多,大致就是先从输入输出开始,然后是基本的语句,字典、列表、元组等等,然后是文件输入输出以及类与对象、继承多态等等。

这其中有很多知识我都是早早学完了,python我在去年就把基础的知识学的差不多了,Scott自学python——字符串学习笔记_轩Scott的博客-CSDN博客

Scott自学python——字典学习笔记_轩Scott的博客-CSDN博客

Scott自学python——元组学习笔记_轩Scott的博客-CSDN博客

Scott自学python——列表学习笔记_轩Scott的博客-CSDN博客

这些都是我以前学习python的博客笔记。

暑假期间我主要是学习了pygame和python的文件输入输出以及类与对象、继承多态等等,以下是我在练习中写的核酸检测登记系统

import datetime
import csv
class Nuclear_Test():#核酸检测结果
    def __init__(self,id):
        self.time = datetime.datetime.now()
        self.result = False
        self.id = id
        pass

    def Output(self):
        print('Nuclear test time is',self.time,',result=',self.result)
    pass

class Person():#核酸检测人员信息
    def __init__(self,name,id):
        self.name = name#名
        self.id = id#身份证号
        self.Nuclear = []#
        self.Nuclear_Number = 0#次数
        pass
    def Add_Nuclear_Test(self,result = False):#
        index = Nuclear_Test(self.id)
        index.result=result
        self.Nuclear.append(index)
        self.Nuclear_Number+=1
        pass

    def Output(self):
        print('Chinaman name',self.name.title(),'Chinaman id',self.id)
        for i in range(self.Nuclear_Number):
            self.Nuclear[i].Output()
            pass
        pass
    pass
class System():
    def __init__(self):
        print('Initializing the system.')
        self.Person_Data = []
        self.number=int(0)
        pass
    def Add_Data(self,data):
        self.Person_Data.append(data)
        self.number+=1
        pass
    def Find_Data(self,id):
        index = False
        for i in range(self.number):
            if self.Person_Data[i].id == id:
                print('Found the monster data.',end=' ')
                self.Person_Data[i].Output()
                index = True
                pass
            pass
        if index == False:
            print('The Chinaman data was not found.')
        pass
    def Be_Infected(self,id):#强制阳性
        for i in range(self.number):
            if self.Person_Data[i].id == id:
                self.Person_Data[i].Add_Nuclear_Test(True)
                pass
            pass
        pass
    def Do_Nuclear_Test(self,id):#默认阴性
        for i in range(self.number):
            if self.Person_Data[i].id == id:
                self.Person_Data[i].Add_Nuclear_Test()
                pass
            pass
        pass

    def Load_Data(self):
        with open("Person_Data.csv", mode='r', encoding='utf-8-sig', newline='') as f:
            reader = csv.reader(f)
            for i,j in enumerate(reader):
                index = Person(j[0],j[1])
                index.Nuclear_Number = j[2]
                self.Add_Data(index)
                pass
            pass
        # with open("Nuclear_Test.csv", mode='r', encoding='utf-8-sig', newline='') as f:
        #     reader = csv.reader(f)
        #     for i,j in enumerate(reader):
        #         print(j[0],j[1],j[2])
        pass
    def Save_Data(self):
        Person_Data_Index = []
        for i in range(self.number):
            index = [self.Person_Data[i].name, self.Person_Data[i].id, self.Person_Data[i].Nuclear_Number]
            Person_Data_Index.append(index)
            pass
        with open("Person_Data.csv", mode='w', encoding='utf-8-sig', newline='') as f:
            f.truncate()
            writer = csv.writer(f)
            writer.writerows(Person_Data_Index)
            pass
        # Nuclear_Test_Index = []
        # for i in range(self.number):
        #     for j in range(int(self.Person_Data[i].Nuclear_Number)):
        #         # index = [self.Person_Data[i].Nuclear[j].id,self.Person_Data[i].Nuclear[j].time,self.Person_Data[i].Nuclear[j].result]
        #         print(self.Person_Data[i].Nuclear[j].id)
        #         # Nuclear_Test_Index.append(index)
        #         pass
        # with open("Nuclear_Test.csv", mode='w', encoding='utf-8-sig', newline='')as f:
        #     f.truncate()
        #     writer = csv.writer(f)
        #     writer.writerows(Nuclear_Test_Index)
        #     pass
        # pass
    def Output(self):
        for i in range(self.number):
            self.Person_Data[i].Output()
            pass
        pass
    def __del__(self):
        print('The system is shut down.')

    pass
People1 = Person('Hu',114514)
People2 = Person('Xi',114515)
A = System()
A.Load_Data()
A.Add_Data(People1)#增
A.Add_Data(People2)#增
A.Be_Infected(114514)#改
A.Do_Nuclear_Test(114514)#查
A.Be_Infected(114515)
A.Do_Nuclear_Test(114515)
A.Find_Data(114514)#查
A.Find_Data(114516)#查
#A.Save_Data()

 知识不用罗列,全部呈现在代码中了。

现在我们有一组从2006年到2016年1000部最流行的电影数据,
数据来源:https://www.kaggle.com/damianpanek/sunday-eda/data
(数据是本文件下的 IMDB-Movie-Data)
·问题1:我们想知道这些电影数据中评分的平均分,导演的人数等信息,我们应该怎么获
取?
·问题2∶对于这一组电影数据,如果我们想rating,runtime的分布情况,应该如何呈现数
据?
·问题3∶对于这一组电影数据,如果我们希望统计电影分类(genre)的情况,应该如何处理数据?

 问题1

import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

imdb = pd.DataFrame(pd.read_csv('IMDB-Movie-Data.csv'))
rating = imdb['Rating'].values
print('电影数据中评分的平均分 ' , rating.mean())

dir=imdb['Director'].values
director = list(set(dir))
print('导演的人数 ',len(director))

问题2

import IMDB
import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

r1=r2=r3=r4=r5=r6=r7=r8=r9=int(0)
for i in range(IMDB.rating.size):
    if IMDB.rating[i] >= 1 and IMDB.rating[i] < 2:
        r1 = r1 + 1
    elif IMDB.rating[i] >= 2 and IMDB.rating[i] < 3:
        r2 = r2 + 1
    elif IMDB.rating[i] >= 3 and IMDB.rating[i] < 4:
        r3 = r3 + 1
    elif IMDB.rating[i] >= 4 and IMDB.rating[i] < 5:
        r4 = r4 + 1
    elif IMDB.rating[i] >= 5 and IMDB.rating[i] < 6:
        r5 = r5 + 1
    elif IMDB.rating[i] >= 6 and IMDB.rating[i] < 7:
        r6 = r6 + 1
    elif IMDB.rating[i] >= 7 and IMDB.rating[i] < 8:
        r7 = r7 + 1
    elif IMDB.rating[i] >= 8 and IMDB.rating[i] < 9:
        r8 = r8 + 1
    elif IMDB.rating[i] >= 9 and IMDB.rating[i] < 10:
        r9 = r9 + 1

rat = list(range(1,10))
rating_distribution = [r1,r2,r3,r4,r5,r6,r7,r8,r9]
plt.xlabel('分数',fontproperties='simhei')
plt.ylabel('Rating_Number')
plt.title('rating分布情况',fontproperties='simhei',fontsize=14)
plt.xticks(rat)
plt.bar(rat,rating_distribution)
plt.show()

import IMDB
import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

Runtime = IMDB.imdb['Runtime (Minutes)'].values
runtime = {}
for i in range(Runtime.min(),Runtime.max()+1):
    runtime[i]=0
    pass
for i in range(Runtime.size):
    runtime[Runtime[i]]+=1
    pass
plt.xlabel('Runtime (Minutes)',fontproperties='simhei')
plt.ylabel('Runtime_Number')
plt.title('Runtime分布情况',fontproperties='simhei',fontsize=14)
plt.bar(runtime.keys(),runtime.values())
plt.show()

 

猜你喜欢

转载自blog.csdn.net/m0_61789994/article/details/125920977