相关文件
关注小编,私信小编领取哟! 当然别忘了一件三连哟~~
公众号:Python日志 可以关注小编公众号,会不定时的发布一下Python小技巧,还有很多资源可以免费领取哟!! 源码领取:加Python学习交流群:773162165 可以领取哟
开发工具
Python版本:3.7.8 相关模块: pytorch模块; pyqt5模块; numpy模块; pyttsx3模块; 以及一些python自带的模块。
环境搭建
安装Python并添加到环境变量,pip安装需要的相关模块即可。
一:超级玛丽
效果展示 部分源码
class Box(pg.sprite.Sprite):
def __init__(self, x, y, type, group=None, name=c.MAP_BOX):
pg.sprite.Sprite.__init__(self)
self.frames = []
self.frame_index = 0
self.load_frames()
self.image = self.frames[self.frame_index]
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.rest_height = y
self.animation_timer = 0
self.first_half = True
self.state = c.RESTING
self.y_vel = 0
self.gravity = 1.2
self.type = type
self.group = group
self.name = name
def load_frames(self):
sheet = setup.GFX['tile_set']
frame_rect_list = [(384, 0, 16, 16), (400, 0, 16, 16),
(416, 0, 16, 16), (400, 0, 16, 16), (432, 0, 16, 16)]
for frame_rect in frame_rect_list:
self.frames.append(tools.get_image(sheet, *frame_rect,
c.BLACK, c.BRICK_SIZE_MULTIPLIER))
def update(self, game_info):
self.current_time = game_info[c.CURRENT_TIME]
if self.state == c.RESTING:
self.resting()
elif self.state == c.BUMPED:
self.bumped()
def resting(self):
time_list = [375, 125, 125, 125]
if (self.current_time - self.animation_timer) > time_list[self.frame_index]:
self.frame_index += 1
if self.frame_index == 4:
self.frame_index = 0
self.animation_timer = self.current_time
self.image = self.frames[self.frame_index]
def bumped(self):
self.rect.y += self.y_vel
self.y_vel += self.gravity
if self.rect.y > self.rest_height + 5:
self.rect.y = self.rest_height
self.state = c.OPENED
if self.type == c.TYPE_MUSHROOM:
self.group.add(powerup.Mushroom(self.rect.centerx, self.rect.y))
elif self.type == c.TYPE_FIREFLOWER:
self.group.add(powerup.FireFlower(self.rect.centerx, self.rect.y))
elif self.type == c.TYPE_LIFEMUSHROOM:
self.group.add(powerup.LifeMushroom(self.rect.centerx, self.rect.y))
self.frame_index = 4
self.image = self.frames[self.frame_index]
def start_bump(self, score_group):
self.y_vel = -6
self.state = c.BUMPED
if self.type == c.TYPE_COIN:
self.group.add(coin.Coin(self.rect.centerx, self.rect.y, score_group))
class Coin(pg.sprite.Sprite):
def __init__(self, x, y, score_group):
pg.sprite.Sprite.__init__(self)
self.frames = []
self.frame_index = 0
self.load_frames()
self.image = self.frames[self.frame_index]
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.bottom = y - 5
self.gravity = 1
self.y_vel = -15
self.animation_timer = 0
self.initial_height = self.rect.bottom - 5
self.score_group = score_group
def load_frames(self):
sheet = setup.GFX[c.ITEM_SHEET]
frame_rect_list = [(52, 113, 8, 14), (4, 113, 8, 14),
(20, 113, 8, 14), (36, 113, 8, 14)]
for frame_rect in frame_rect_list:
self.frames.append(tools.get_image(sheet, *frame_rect,
c.BLACK, c.BRICK_SIZE_MULTIPLIER))
def update(self, game_info):
self.current_time = game_info[c.CURRENT_TIME]
self.spinning()
def spinning(self):
self.image = self.frames[self.frame_index]
self.rect.y += self.y_vel
self.y_vel += self.gravity
if (self.current_time - self.animation_timer) > 80:
if self.frame_index < 3:
self.frame_index += 1
else:
self.frame_index = 0
self.animation_timer = self.current_time
if self.rect.bottom > self.initial_height:
self.kill()
class FlashCoin(pg.sprite.Sprite):
def __init__(self, x, y):
pg.sprite.Sprite.__init__(self)
self.frame_index = 0
self.frames = []
self.load_frames()
self.image = self.frames[self.frame_index]
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.animation_timer = 0
def load_frames(self):
sheet = setup.GFX[c.ITEM_SHEET]
frame_rect_list = [(1, 160, 5, 8), (9, 160, 5, 8),
(17, 160, 5, 8), (9, 160, 5, 8)]
for frame_rect in frame_rect_list:
self.frames.append(tools.get_image(sheet, *frame_rect,
c.BLACK, c.BRICK_SIZE_MULTIPLIER))
def update(self, current_time):
time_list = [375, 125, 125, 125]
if self.animation_timer == 0:
self.animation_timer = current_time
elif (current_time - self.animation_timer) > time_list[self.frame_index]:
self.frame_index += 1
if self.frame_index == 4:
self.frame_index = 0
self.animation_timer = current_time
self.image = self.frames[self.frame_index]
class StaticCoin(pg.sprite.Sprite):
def __init__(self, x, y):
pg.sprite.Sprite.__init__(self)
self.frame_index = 0
self.frames = []
self.load_frames()
self.image = self.frames[self.frame_index]
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.animation_timer = 0
def load_frames(self):
sheet = setup.GFX[c.ITEM_SHEET]
frame_rect_list = [(3, 98, 9, 13), (19, 98, 9, 13),
(35, 98, 9, 13), (51, 98, 9, 13)]
for frame_rect in frame_rect_list:
self.frames.append(tools.get_image(sheet, *frame_rect,
c.BLACK, c.BRICK_SIZE_MULTIPLIER))
def update(self, game_info):
self.current_time = game_info[c.CURRENT_TIME]
time_list = [375, 125, 125, 125]
if self.animation_timer == 0:
self.animation_timer = self.current_time
elif (self.current_time - self.animation_timer) > time_list[self.frame_index]:
self.frame_index += 1
if self.frame_index == 4:
self.frame_index = 0
self.animation_timer = self.current_time
self.image = self.frames[self.frame_index]
二:天天酷跑
效果展示 部分源码
class Role:
def __init__(self,surface=None,y=None):
self.surface=surface
self.y=y
self.w=(surface.get_width())/12
self.h=surface.get_height()/2
self.currentFrame=-1
self.state=0
self.g=1
self.vy=0
self.vy_start=-20
def getRect(self):
return (0,self.y+12,self.w,self.h)
class Object:
def __init__(self,surface,x=0,y=0):
self.surface=surface
self.x=x
self.y=y
self.w=surface.get_width()
self.h=surface.get_height()
self.currentFrame=random.randint(0,6)
self.w = 100
self.h = 100
def getRect(self):
return (self.x,self.y,self.w,self.h)
def collision(self,rect1,rect2):
if (rect2[0]>=rect1[2]-20) or (rect1[0]+40>=rect2[2])or (rect1[1]+rect1[3]<rect2[1]+20) or (rect2[1]+rect2[3]<rect1[1]+20):
return False
return True
class Bg:
def __init__(self,surface):
self.surface=surface
self.dx=-10
self.w=surface.get_width()
self.rect=surface.get_rect()
def initGame():
global bg,role,clock,gameState,surObject,surGameOver,score,myFont,myFont1,objectList
score=0
objectList=[]
myFont=pygame.font.Font("./freesansbold.ttf",32)
myFont1=pygame.font.Font("./freesansbold.ttf",64)
clock = pygame.time.Clock()
gameState=0
surBg=pygame.image.load("image/bg.bmp").convert_alpha()
bg=Bg(surBg)
surGameOver=pygame.image.load("image/gameover.bmp").convert_alpha()
surRole=pygame.image.load("image/role.png").convert_alpha()
role=Role(surRole,508-85)
surObject=pygame.image.load("image/object.png").convert_alpha()
def addObject():
global surObject,object,objectList,object
rate=4
if not random.randint(0,300)<rate:
return
y=random.choice([height-100,height-200,height-300,height-400])
object=Object(surObject,width+40,y)
objectList.append(object)
def updateLogic():
global gameState,score
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type==pygame.KEYDOWN:
if gameState==0:
if event.key==pygame.K_SPACE:
if role.state==0:
role.state=1
role.vy=role.vy_start
elif role.state==1:
role.state=2
role.vy=role.vy_start
elif gameState==1:
if event.key==pygame.K_SPACE:
initGame()
if gameState==0:
bg.dx+=10
if bg.dx==1200:
bg.dx=0
if role.state==0:
role.currentFrame+=1
if role.currentFrame==12:
role.currentFrame=0
else:
role.y+=role.vy
role.vy+=role.g
if role.y>=508-85:
role.y=508-85
role.state=0
addObject()
for object in objectList:
object.x-=10
if object.x+object.w<=0:
objectList.remove(object)
score+=10
print("移除了一个目标")
if object.collision(role.getRect(),object.getRect()):
if(object.currentFrame==6):
objectList.remove(object)
score+=100
print(score)
print("吃了一个金币")
else:
gameState=1
print("发生了碰撞!")
三:我的世界
效果展示 部分代码展示
class Model(object):
def __init__(self):
self.batch = pyglet.graphics.Batch()
self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())
self.world = {}
self.shown = {}
self._shown = {}
self.sectors = {}
self.queue = deque()
self._initialize()
def _initialize(self):
""" Initialize the world by placing all the blocks.
"""
n = 80
s = 1
y = 0
for x in xrange(-n, n + 1, s):
for z in xrange(-n, n + 1, s):
self.add_block((x, y - 2, z), GRASS, immediate=False)
self.add_block((x, y - 3, z), STONE, immediate=False)
if x in (-n, n) or z in (-n, n):
for dy in xrange(-2, 3):
self.add_block((x, y + dy, z), STONE, immediate=False)
o = n - 10
for _ in xrange(120):
a = random.randint(-o, o)
b = random.randint(-o, o)
c = -1
h = random.randint(1, 6)
s = random.randint(4, 8)
d = 1
t = random.choice([GRASS, SAND, BRICK])
for y in xrange(c, c + h):
for x in xrange(a - s, a + s + 1):
for z in xrange(b - s, b + s + 1):
if (x - a) ** 2 + (z - b) ** 2 > (s + 1) ** 2:
continue
if (x - 0) ** 2 + (z - 0) ** 2 < 5 ** 2:
continue
self.add_block((x, y, z), t, immediate=False)
s -= d
def hit_test(self, position, vector, max_distance=8):
""" Line of sight search from current position. If a block is
intersected it is returned, along with the block previously in the line
of sight. If no block is found, return None, None.
Parameters
----------
position : tuple of len 3
The (x, y, z) position to check visibility from.
vector : tuple of len 3
The line of sight vector.
max_distance : int
How many blocks away to search for a hit.
"""
m = 8
x, y, z = position
dx, dy, dz = vector
previous = None
for _ in xrange(max_distance * m):
key = normalize((x, y, z))
if key != previous and key in self.world:
return key, previous
previous = key
x, y, z = x + dx / m, y + dy / m, z + dz / m
return None, None
def exposed(self, position):
""" Returns False is given `position` is surrounded on all 6 sides by
blocks, True otherwise.
"""
x, y, z = position
for dx, dy, dz in FACES:
if (x + dx, y + dy, z + dz) not in self.world:
return True
return False
def add_block(self, position, texture, immediate=True):
""" Add a block with the given `texture` and `position` to the world.
Parameters
----------
position : tuple of len 3
The (x, y, z) position of the block to add.
texture : list of len 3
The coordinates of the texture squares. Use `tex_coords()` to
generate.
immediate : bool
Whether or not to draw the block immediately.
"""
if position in self.world:
self.remove_block(position, immediate)
self.world[position] = texture
self.sectors.setdefault(sectorize(position), []).append(position)
if immediate:
if self.exposed(position):
self.show_block(position)
self.check_neighbors(position)
def remove_block(self, position, immediate=True):
""" Remove the block at the given `position`.
Parameters
----------
position : tuple of len 3
The (x, y, z) position of the block to remove.
immediate : bool
Whether or not to immediately remove block from canvas.
"""
del self.world[position]
self.sectors[sectorize(position)].remove(position)
if immediate:
if position in self.shown:
self.hide_block(position)
self.check_neighbors(position)
四:魔塔游戏
效果展示 部分代码展示
ef init_actions():
def quit(e):
global running
running = False
return True
action_control.register_action('QUIT', pygame.QUIT, quit)
action_control.register_action('BOOK', pygame.KEYUP, global_var.get_value('BOOK').action)
action_control.register_action('STARTMENU', pygame.KEYUP, global_var.get_value('STARTMENU').action)
action_control.register_action('BACKPACK', pygame.KEYUP, global_var.get_value('BACKPACK').action)
action_control.register_action('SAVE', pygame.KEYUP, global_var.get_value('SAVE').action)
action_control.register_action('LOAD', pygame.KEYUP, global_var.get_value('LOAD').action)
action_control.register_action('FLY', pygame.KEYUP, global_var.get_value('FLY').action)
action_control.register_action('HELP', pygame.KEYUP, global_var.get_value('HELP').action)
action_control.register_action('Shop1', pygame.KEYUP, global_var.get_value('Shop1').action)
action_control.register_action('Shop2', pygame.KEYUP, global_var.get_value('Shop2').action)
action_control.register_action('TEXTBOX', pygame.KEYUP, global_var.get_value('TEXTBOX').action)
action_control.register_action('CHOICEBOX', pygame.KEYUP, global_var.get_value('CHOICEBOX').action)
action_control.register_action('SHOWDAMAGE', pygame.KEYUP, global_var.get_value('SHOWDAMAGE').action)
action_control.register_action('STATUSBAR', pygame.KEYUP, global_var.get_value('STATUSBAR').action)
action_control.register_action('CURTAIN', pygame.KEYUP, global_var.get_value('CURTAIN').action)
WriteLog.info(__name__, "事件全部注册完成")
def init_sound():
Music = music.MusicWrapper()
global_var.set_value("Music", Music)
WriteLog.info(__name__, "初始化音效完成")
def init_event_flow():
EVENTFLOW = EventFlow()
global_var.set_value("EVENTFLOW", EVENTFLOW)
EVENT = Event()
global_var.set_value("EVENT", EVENT)
EVENT.get_event_flow_module()
EVENTFLOW.get_event_module()
WriteLog.info(__name__, "初始化事件流完成")
def init_function():
FUNCTION = global_var.get_value("FUNCTION")
FUNCTION.init_var()
WriteLog.info(__name__, "初始化function完成")
if DEBUG:
import threading
def console():
while running:
r = input()
try:
print(eval(r))
except:
try:
exec(r)
except Exception as e:
print("error:", str(e))
t = threading.Thread(target=console)
t.start()
init()
init_actions()
init_sound()
init_event_flow()
init_function()
clock = pygame.time.Clock()
STARTMENU = global_var.get_value("STARTMENU")
while running:
if STARTMENU.new_game == True:
STARTMENU.open()
STARTMENU.new_game = False
show_damage = global_var.get_value("SHOWDAMAGE")
show_damage.open()
status_bar = global_var.get_value("STATUSBAR")
status_bar.open()
CurrentMap.active = True
EVENTFLOW = global_var.get_value("EVENTFLOW")
with open(os.path.join(os.getcwd(),"project", "start_text.json")) as f:
start_text = json.load(f)
EVENTFLOW.insert_action(start_text["startText"])
pygame.display.update()
RootScreen.flush(screen)
action_control.action_render()
五:雷霆战机
效果展示 部分代码展示
class Menu(object):
"""每个页面的父类"""
def __init__(self, image, music):
pygame.mixer.music.load(music)
pygame.mixer.music.set_volume(0.4)
pygame.mixer.music.play(-1)
self.screen = pygame.display.set_mode(SCREEN_RECT.size)
pygame.display.set_caption("雷霆战机 公众号:Python日志 学习交流群:685237705")
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
def event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
exit()
self.mouse_press = pygame.mouse.get_pressed()
self.mouse_pos = pygame.mouse.get_pos()
@staticmethod
def clicks():
pygame.mixer.music.load("./music/mouse.mp3")
pygame.mixer.music.set_volume(0.5)
pygame.mixer.music.play(loops=0, start=0.5)
pygame.mixer.music.fadeout(500)
class MainMenu(Menu):
"""游戏主菜单"""
def __init__(self):
music = "./music/menu1.mp3"
image = "./images/background2.png"
super().__init__(image, music)
def update_menu(self):
while True:
super().event()
start = pygame.image.load("./images/start1.png")
start_rect = start.get_rect()
rule = pygame.image.load("./images/rule1.png")
rule_rect = rule.get_rect()
start_rect.centerx = SCREEN_RECT.centerx
start_rect.y = SCREEN_RECT.height * 0.3
rule_rect.centerx = SCREEN_RECT.centerx
rule_rect.y = SCREEN_RECT.height * 0.45
if (start_rect.left < self.mouse_pos[0] < start_rect.right) and (
start_rect.top < self.mouse_pos[1] < start_rect.bottom):
start = pygame.image.load("./images/start2.png")
if self.mouse_press[0]:
Menu.clicks()
GameType().update_menu()
if (rule_rect.left < self.mouse_pos[0] < rule_rect.right) and (
rule_rect.top < self.mouse_pos[1] < rule_rect.bottom):
rule = pygame.image.load("./images/rule2.png")
if self.mouse_press[0]:
Menu.clicks()
RuleMenu().update_menu()
self.screen.blit(self.image, self.rect)
self.screen.blit(start, start_rect)
self.screen.blit(rule, rule_rect)
pygame.display.update()
class GameType(Menu):
"""游戏模式选择"""
def __init__(self):
music = "./music/type1.mp3"
image = "./images/background4.png"
super().__init__(image, music)
def update_menu(self):
while True:
super().event()
type1 = pygame.image.load("./images/first1.png")
type1_rect = type1.get_rect()
type2 = pygame.image.load("./images/second1.png")
type2_rect = type2.get_rect()
type3 = pygame.image.load("./images/third1.png")
type3_rect = type3.get_rect()
return_picture = pygame.image.load("./images/return5.png")
return_rect = return_picture.get_rect()
type1_rect.centerx = SCREEN_RECT.centerx
type1_rect.y = SCREEN_RECT.height * 0.15
type2_rect.centerx = type1_rect.centerx
type2_rect.y = SCREEN_RECT.height * 0.3
type3_rect.centerx = SCREEN_RECT.centerx
type3_rect.y = SCREEN_RECT.height * 0.45
return_rect.x = 10
return_rect.y = 10
record1 = self.__record(str(1))
record2 = self.__record(str(2))
if (type1_rect.left < self.mouse_pos[0] < type1_rect.right) and (
type1_rect.top < self.mouse_pos[1] < type1_rect.bottom):
type1 = pygame.image.load("./images/first2.png")
if self.mouse_press[0]:
Menu.clicks()
plane_main_1.Game().start_game()
if (type2_rect.left < self.mouse_pos[0] < type2_rect.right) and (
type2_rect.top < self.mouse_pos[1] < type2_rect.bottom):
type2 = pygame.image.load("./images/second2.png")
if self.mouse_press[0]:
Menu.clicks()
if 0 <= int(record1) <= 3:
plane_main_2.Game().start_game()
else:
ProhibitMenu().update_menu()
if (type3_rect.left < self.mouse_pos[0] < type3_rect.right) and (
type3_rect.top < self.mouse_pos[1] < type3_rect.bottom):
type3 = pygame.image.load("./images/third2.png")
if self.mouse_press[0]:
Menu.clicks()
if 0 <= int(record2) <= 3:
plane_main_3.Game().start_game()
else:
ProhibitMenu().update_menu()
if return_rect.left < self.mouse_pos[0] < return_rect.right and (
return_rect.top < self.mouse_pos[1] < return_rect.bottom):
return_picture = pygame.image.load("./images/return6.png")
if self.mouse_press[0]:
Menu.clicks()
MainMenu().update_menu()
self.screen.blit(self.image, self.rect)
self.screen.blit(type1, type1_rect)
self.screen.blit(type2, type2_rect)
self.screen.blit(type3, type3_rect)
self.screen.blit(return_picture, return_rect)
pygame.display.update()
|