一、pygame的窗口制作
开发环境是vscode 1.43.0 python版本是3.7.6
代码
import pygamefrom pygame.locals import *import sysdef hello_world():
pygame.init()
pygame.display.set_mode((640,480)) pygame.display.set_caption("hello world")
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()if __name__=="__main__": hello_world()
运行截图
二、游戏案例1:坦克大战
参考代码
import pygame,sysfrom pygame.locals import *def play_tank():
pygame.init()
window_size=(width,height)=(640,480)
speed=[1,1]
color_white=(255,255,255) screen=pygame.display.set_mode(window_size) pygame.display.set_caption("坦克大战") tank_image=pygame.image.load(r'tankU.bmp') tank_rect=tank_image.get_rect()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
tank_rect=tank_rect.move(speed)
if(tank_rect.left<0) or (tank_rect.right>width): speed[0]=-speed[0]
if(tank_rect.top<0) or (tank_rect.bottom>height): speed[1]=-speed[1]
screen.fill(color_white) screen.blit(tank_image,tank_rect) pygame.display.update()if __name__=="__main__": play_tank()
完善代码
import pygame,sysfrom pygame.locals import *def play_tank():
pygame.init()
window_size=(width,height)=(640,480)
speed=[1,1]
color_white=(255,255,255) screen=pygame.display.set_mode(window_size) pygame.display.set_caption("坦克大战") tank_image=pygame.image.load(r'tankU.bmp') tank_rect=tank_image.get_rect()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
tank_rect=tank_rect.move(speed)
if(tank_rect.left<0) or (tank_rect.right>width): speed[0]=-speed[0]
if(tank_rect.top<0) or (tank_rect.bottom>height): speed[1]=-speed[1]
screen.fill(color_white) screen.blit(tank_image,tank_rect) pygame.display.update()if __name__=="__main__": play_tank()
运行截图
福利:私信回复【01】可免费获取python入门教程视频
三、精灵类测试
参考代码
import pygame,syspygame.init()class Tank(pygame.sprite.Sprite):
def __init__(self,filename,initial_position): pygame.sprite.Sprite.__init__(self) self.image=pygame.image.load(filename) self.rect=self.image.get_rect() self.rect.bottomright=initial_positionscreen=pygame.display.set_mode([640,480])screen.fill([255,255,255])fi='tankU.bmp'b=Tank(fi,[150,100])while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
screen.blit(b.image,b.rect) pygame.display.update()
运行截图
最后,如果你的时间不是很紧张,并且又想快速的提高,最重要的是不怕吃苦,建议你可以价位@762459510 ,那个真的很不错,很多人进步都很快,需要你不怕吃苦哦!大家可以去添加上看一下~
完善代码
import pygamefrom pygame.locals import *class MySprite(pygame.sprite.Sprite):
def __init__(self,target): pygame.sprite.Sprite.__init__(self) self.sprite_surface=target
self.image=None
self.master_image=None
self.rect=None
self.topleft=0,0
self.frame=0
self.old_fram=-1
self.fram_width=1
self.fram_height=1
self.first_fram=0
self.last_fram=0
self.columns=1
self.last_time=0
def load(self,fi