前言
既做了雏形,不稍微完善一点心里总有点小疙瘩。
效果图
补充说明
1、游戏通关通过rect判断而不是碰撞(两个终点)
2、增加人物行走的动作(布尔标志位)
3、箱子覆盖于终点之上有特殊颜色(image_alt)
4、选素材用心了些
源代码
import tkinter as tk
import pygame
import time
import numpy as np
import sys
from PIL import ImageTk,Image,ImageGrab
from tkinter import StringVar,IntVar,messagebox,Radiobutton
#屏幕大小的常量
SCREEN_RECT = pygame.Rect(0,0,640,640)
#刷新的帧率
FRAME_PER_SEC = 60
#墙体
class GameSprite(pygame.sprite.Sprite): #(继承父类) 其中sprite是模块 Sprite是类名称
'''精灵基类'''
#构造函数/初始化
image_name = 0
def __init__(self,image_name,x=0,y=0,z=1):
self.move_num = 0
self.leftorright = True
#调用父类初始化方法
super().__init__()
#定义对象的属性
self.image_name = image_name
self.image = pygame.image.load(self.image_name)
if z == 0:
self.rect = pygame.Rect(0,0,64,64)
else :
self.rect = self.image.get_rect() #图像的属性
self.rect.x = x*64
self.rect.y = y*64
class hero(GameSprite):
'''英雄类'''
def __init__(self,x,y):
super().__init__("./image/character1.png",x,y,0)
self.num = 0
def move(self,num):
self.num = num
def update(self,hero_group,wall_group,box_group):
#print(self.rect)
# 传入 1 2 3 4 分别对应上下左右 1-1
if self.num == 1:
if self.leftorright:
self.image_name = './image/Character7.png'
else :
self.image_name = './image/Character8.png'
self.rect.y -= 64
if len(pygame.sprite.groupcollide(hero_group, wall_group, False, False)) > 0:
self.rect.y += 64
if len(pygame.sprite.groupcollide(hero_group, box_group, False, False)) > 0:
self.rect.y -= 64
if len(pygame.sprite.groupcollide(hero_group, wall_group, False, False)) + len(
pygame.sprite.groupcollide(hero_group, box_group, False, False)) > 0:
self.rect.y += 64
self.rect.y += 64
elif self.num ==2 :
if self.leftorright:
self.image_name = './image/Character4.png'
else :
self.image_name = './image/Character5.png'
self.rect.y += 64
if len(pygame.sprite.groupcollide(hero_group, wall_group, False, False)) > 0:
self.rect.y -= 64
if len(pygame.sprite.groupcollide(hero_group, box_group, False, False)) > 0:
self.rect.y += 64
if len(pygame.sprite.groupcollide(hero_group, wall_group, False, False)) + len(
pygame.sprite.groupcollide(hero_group, box_group, False, False)) > 0:
self.rect.y -= 64
self.rect.y -= 64
elif self.num == 3:
if self.leftorright:
self.image_name = './image/Character1.png'
else :
self.image_name = './image/Character10.png'
self.rect.x -= 64
if len(pygame.sprite.groupcollide(hero_group, wall_group, False, False)) > 0:
self.rect.x += 64
if len(pygame.sprite.groupcollide(hero_group, box_group, False, False)) > 0:
self.rect.x -= 64
if len(pygame.sprite.groupcollide(hero_group, wall_group, False, False)) + len(
pygame.sprite.groupcollide(hero_group, box_group, False, False)) > 0:
self.rect.x += 64
self.rect.x += 64
elif self.num == 4:
if self.leftorright:
self.image_name = './image/Character2.png'
else :
self.image_name = './image/Character3.png'
self.rect.x += 64
if len(pygame.sprite.groupcollide(hero_group, wall_group, False, False)) > 0:
self.rect.x -= 64
if len(pygame.sprite.groupcollide(hero_group, box_group, False, False)) > 0:
self.rect.x += 64
if len(pygame.sprite.groupcollide(hero_group, wall_group, False, False)) + len(
pygame.sprite.groupcollide(hero_group, box_group, False, False)) > 0:
self.rect.x -= 64
self.rect.x -= 64
elif self.num == 0:
pass
if self.num != 0:
self.move_num = self.num
#print('后面面:%d'%self.move_num)
self.leftorright = not self.leftorright
self.num = 0
self.image = pygame.image.load(self.image_name)
def goback(self,num):
pass
class box(GameSprite):
'''箱子类'''
def __init__(self,x,y):
self.image_alt = 0
self.num = 0
super().__init__("./image/Crate_Beige.png",x,y)
def beenpush(self,num):
self.num = num
def update(self,wall_group,box_group):
# 传入 1 2 3 4 分别对应上下左右
if self.image_alt == 1:
self.image_name ='./image/CrateDark_Red.png'
else:
self.image_name ='./image/Crate_Beige.png'
if self.num == 1:
self.rect.y -= 64
if len(pygame.sprite.groupcollide(wall_group,box_group,False,False)) > 0:
self.rect.y += 64
self.to_hero_goback = 1
elif self.num == 2:
self.rect.y += 64
if len(pygame.sprite.groupcollide(wall_group,box_group,False,False)) > 0:
self.rect.y -= 64
self.to_hero_goback = 2
elif self.num == 3:
self.rect.x -= 64
if len(pygame.sprite.groupcollide(wall_group,box_group,False,False)) > 0:
self.rect.x += 64
self.to_hero_goback = 3
elif self.num == 4:
self.rect.x += 64
if len(pygame.sprite.groupcollide(wall_group,box_group,False,False)) > 0:
self.rect.x -= 64
self.to_hero_goback = 4
elif self.num == 0:
pass
if self.num != 0:
self.moved_num = self.num
#print('当前的movednum是%d'%self.moved_num)
self.num = 0
self.image = pygame.image.load(self.image_name)
class wall(GameSprite):
def __init__(self, x, y):
super().__init__("./image/Wall_Beige.png", x, y)
class endpoint(GameSprite):
def __init__(self, x, y):
super().__init__("./image/endball.png", x, y)
class gamepushbox():
#推箱子主游戏
wall = 0
#初始化
def __init__(self):
print('初始化')
#游戏窗口
self.screen = pygame.display.set_mode(SCREEN_RECT.size)
#游戏背景
self.background = GameSprite("./image/green_background.png")
self.back_group = pygame.sprite.Group(self.background)
#英雄
self.hero = hero(1,1)
self.hero_group = pygame.sprite.Group(self.hero)
#箱子
self.box = box(3,2)
self.box1 = box(3,6)
self.box_group = pygame.sprite.Group(self.box,self.box1)
#墙体
self.wall0 = wall(2,2)
self.wall_group = pygame.sprite.Group(self.wall0)
for i in wall_list:
self.wall_group.add(wall(i[0],i[1]))
#终点
self.end_point = endpoint(7,2)
self.end_point1 = endpoint(7,6)
self.end_point_group = pygame.sprite.Group(self.end_point,self.end_point1)
#2.创建游戏的时钟
self.clock = pygame.time.Clock()
#更新精灵组
def updata_sprites(self):
self.back_group.draw(self.screen)
self.wall_group.draw(self.screen)
self.hero_group.update(self.hero_group,self.wall_group,self.box_group)
self.hero_group.draw(self.screen)
self.end_point_group.draw(self.screen)
self.box_group.update(self.wall_group,self.box_group)
self.box_group.draw(self.screen)
#碰撞检测
def check_collide(self):
#返回的是精灵
#英雄与箱子
if len(pygame.sprite.spritecollide(self.hero,self.box_group,False)) > 0:
if self.hero.move_num != 0:
#print('x : %d and y : %d and from%d' %(self.hero.rect.x,self.hero.rect.y,self.hero.move_num))
for box in self.box_group:
if box.rect.x == self.hero.rect.x and box.rect.y == self.hero.rect.y:
print(box.rect)
box.beenpush(self.hero.move_num)
# print('当前英雄移动状态:%d' %self.hero.move_num)
# print('当前箱子移动状态:%d' %box.num)
# print('当前box上移动状态:%d' %self.box.num)
# print('当前box下移动状态:%d' %self.box1.num)
self.hero.move_num = 0
#箱子与终点
# if len(pygame.sprite.groupcollide(self.end_point_group,self.box_group,False,False)) > 0:
# result = tk.messagebox.askokcancel(title = '恭喜',message = '通关了')
# self.game_over()
goal = 0
for box in self.box_group:
box.image_alt = 0
print('%d : %d' %(box.rect.y,box.image_alt))
if box.rect.x/64 == 7 and box.rect.y/64 ==2:
box.image_alt = 1
print("box %d" %box.rect.y)
goal+=1
elif box.rect.x/64 == 7 and box.rect.y/64 ==6:
box.image_alt = 1
goal+=1
#print(goal)
if goal == 2:
result = tk.messagebox.askokcancel(title = '恭喜',message = '通关了')
self.game_over()
#事件监听
def event_handler(self):
for event in pygame.event.get():
# 退出事件
if event.type == pygame.QUIT:
print('游戏已结束')
self.game_over()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
self.hero.move(4)
#print("向右移动")
if event.key == pygame.K_LEFT:
self.hero.move(3)
#print("向左移动")
if event.key == pygame.K_UP:
self.hero.move(1)
#print("向上移动")
if event.key == pygame.K_DOWN:
self.hero.move(2)
#print("向下移动")
#游戏检测
def game_over(self): #静态方法 就不接受self的东西
print("游戏结束")
pygame.quit()
sys.exit()
class gamepushbox_menu():
def draw_menu(self):
self.window = tk.Tk()
self.window.title('推箱子')
Image_way = './image/star_main_background.jpg'
img = Image.open(Image_way)
window_background = ImageTk.PhotoImage(img)
w = window_background.width()
h = window_background.height()
print(w,h)
self.window.geometry('%dx%d+0+0' % (w, h))
self.background_label = tk.Label(self.window, image=window_background)
self.background_label.place(x=0, y=0, relwidth=1, relheight=1)
self.gamestart_button = tk.Button(self.window, text='开始游戏', command=self.gamestart)
self.gamestart_button.pack()
self.gamestart_button = tk.Button(self.window, text='选择背景音乐', command=self.choose_music)
self.gamestart_button.pack()
#单选框
"""
v = IntVar()
Radiobutton(window, text='One', variable=v, value=1, ).pack()
Radiobutton(window, text='Two', variable=v, value=2, ).pack()
Radiobutton(window, text='Three', variable=v, value=3, ).pack()
"""
self.window.mainloop()
def choose_music(self):
music_tk = tk.Toplevel()
music_tk.title("选取音乐")
self.v = IntVar()
Radiobutton(music_tk, text='寻找爱情', variable=self.v, value=1, ).pack()
Radiobutton(music_tk, text='爱河', variable=self.v, value=2, ).pack()
music_play_button = tk.Button(music_tk, text='播放', command=self.play_music).pack()
music_stop_button = tk.Button(music_tk, text='停止', command=self.stop_music).pack()
def play_music(self):
print(self.v.get())
if (self.v.get() == 1):
music_path = './music/find_happiness.mp3'
elif (self.v.get() == 2):
music_path = './music/love_river.mp3'
pygame.mixer.init()
pygame.mixer.music.load(music_path)
pygame.mixer.music.play(-1)
def stop_music(self):
pygame.mixer.music.stop()
def gamestart(self):
pygame.init()
gameaaa = gamepushbox()
print('游戏开始了')
while 1:
#1.刷新频率
gameaaa.clock.tick(FRAME_PER_SEC)
#game.clock.tick(FRAME_PER_SEC)
# 2.事件监听
gameaaa.event_handler()
# 3.碰撞检测 是否推动箱子
gameaaa.check_collide()
# # 4.更新/绘制精灵
gameaaa.updata_sprites()
# 5.更新检测
pygame.display.update()
# print(SCREEN_RECT.size)
if __name__ == '__main__':
wall_list = []
for i in range(10):
wall_list.append((0, i))
wall_list.append((9,i))
for i in range(16):
wall_list.append((i,0))
wall_list.append((i,9))
zz = [2,4,6]
for i in zz:
wall_list.append((2,i))
wall_list.append((4,i))
wall_list.append((6,i))
wall_list.append((8,i))
a = gamepushbox_menu()
a.draw_menu()
来源:CSDN
作者:纯情渣男
链接:https://blog.csdn.net/chunqingzhanna/article/details/104106001