pygame开发zombie mob游戏

1.游戏简介

zombie游戏规则, 玩家必须从僵尸中逃脱, 并寻找食物生存下去, 获得食物增加生命值, 被僵尸咬到减少生命值

2.游戏素材

food.png
player.png
zombie.png

3.游戏MyLibrary.py库源码

import sys
import pygame
import random
import math
import time
import datetime
from pygame.locals import *

def print_text(font, x, y, text, color=(255,255,255)):
    imageText = font.render(text, True, color)
    screen = pygame.display.get_surface()
    screen.blit(imageText, (x,y))

class MySprite(pygame.sprite.Sprite):
    def __init__(self, target):
        pygame.sprite.Sprite.__init__(self)
        self.master_image = None
        self.old_frame = -1
        self.frame = 0
        self.frame_width = 1
        self.frame_height = 1
        self.first_frame = 0
        self.last_frame = 0
        self.columns = 1
        self.last_time = 0
        self.direction = 0
        self.velocity = Point(0,0)

    def get_x(self):
        return self.rect.x

    def set_x(self, value):
        self.rect.x = value

    #X = property(_getx,_setx)

    def get_y(self):
        return self.rect.y

    def set_y(self, value):
        self.rect.y = value

    #Y = property(_gety,_sety)

    def add_x(self, value):
        self.rect.x += value

    def add_y(self, value):
        self.rect.y += value

    def get_pos(self):
        return self.rect.topleft

    def set_pos(self, pos):
        self.rect.topleft = pos

    def load(self, filename, width, height, columns):
        self.master_image = pygame.image.load(filename).convert_alpha()
        self.image = self.master_image
        self.frame_width = width
        self.frame_height = height
        self.rect = Rect(0,0,width,height)
        self.columns = columns
        rect = self.master_image.get_rect()
        self.last_frame = (rect.width//width) * (rect.height//height) - 1

    def update(self, current_time, rate=30):
        if current_time > self.last_time + rate:
            self.frame += 1
            if self.frame > self.last_frame:
                self.frame = self.first_frame
            self.last_time = current_time
            if self.frame != self.old_frame:
                frame_x = (self.frame % self.columns) * self.frame_width
                frame_y = (self.frame // self.columns) * self.frame_height
                rect = Rect(frame_x, frame_y, self.frame_width, self.frame_height)
                self.image = self.master_image.subsurface(rect)
                self.old_frame = self.frame

    def __str__(self):
        return str(self.frame)+","+str(self.first_frame)+","+ \
               str(self.last_frame)+","+str(self.frame_width) + "," + \
               str(self.frame_height)+","+str(self.columns)+","+ str(self.rect)

class Point:
    def __init__(self, x, y):
        self.move(x, y)

    def move(self,x, y):
        self.x = x
        self.y = y

    def reset(self):
        self.move(0, 0)

4.游戏主程序源码

import itertools
import sys
import time
import datetime
import random
import math
import pygame
from pygame.locals import *
from MyLibrary import *

def calc_velocity(direction, vel=1.0):
    velocity = Point(0,0)
    if direction == 0:
        velocity.y = vel
    elif direction == 2:
        velocity.x = -vel
    elif direction == 4:
        velocity.x = vel
    elif direction == 6:
        velocity.y = -vel

    return velocity

def reverse_direction(sprite):
    if sprite.direction == 0:
        sprite.direction = 6
    elif sprite.direction == 2:
        sprite.direction = 4
    elif sprite.direction == 4:
        sprite.direction = 2
    elif sprite.direction == 6:
        sprite.direction = 0

pygame.init()
width = 600
height = 500
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption("Collision Demo")
font = pygame.font.Font(None,36)
timer = pygame.time.Clock()

player_group = pygame.sprite.Group()
zombie_group = pygame.sprite.Group()
health_group = pygame.sprite.Group()

player = MySprite(screen)
player.load("player.png", 32, 48, 4)
player.set_pos((80,80))
player.direction = 4
player_group.add(player)

#zombie_image = pygame.image.load("zombie_walk.png").convert_alpha()

for n in range(0, 10):
    zombie = MySprite(screen)
    zombie.load("zombie.png", 36, 120, 4)
    zombie.set_pos((random.randint(0,width-zombie.frame_width), random.randint(0,height-zombie.frame_height)))
    zombie.direction = random.randint(0, 3) * 2
    zombie_group.add(zombie)

health = MySprite(screen)
health.load("food.png", 100, 100, 1)
health.set_pos((400,300))
health_group.add(health)

game_over = False
player_moving = False
player_health = 100

while True:

    timer.tick(30)
    ticks = pygame.time.get_ticks()

    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()

    keys = pygame.key.get_pressed()

    if keys[K_ESCAPE]:
        sys.exit()
    elif keys[K_UP] or keys[K_w]:
        player.direction = 6
        player_moving = True
    elif keys[K_RIGHT] or keys[K_d]:
        player.direction = 4
        player_moving = True
    elif keys[K_DOWN] or keys[K_s]:
        player.direction = 0
        player_moving = True
    elif keys[K_LEFT] or keys[K_a]:
        player.direction = 2
        player_moving = True
    else:
        player_moving = False

    if not game_over:
        #玩家逻辑
        player.first_frame = player.direction * player.columns / 2
        player.last_frame = player.first_frame + player.columns - 1
        if player.frame < player.first_frame:
            player.frame = player.first_frame

        if not player_moving:
            player.frame = player.first_frame = player.last_frame
        else:
            player.velocity = calc_velocity(player.direction, 1.5)
            player.velocity.x *= 1.5
            player.velocity.y *= 1.5

        player_group.update(ticks, 50)

        if player_moving:
            player.add_x(player.velocity.x)
            player.add_y(player.velocity.y)
            if player.get_x() < 0:
                player.set_x(0)
            elif player.get_x() > width-player.frame_width:
                player.set_x(width-player.frame_width)
            if player.get_y() < 0:
                player.set_y(0)
            elif player.get_y() > height-player.frame_height:
                player.set_y(height-player.frame_height)

        #僵尸逻辑
        zombie_group.update(ticks, 50)

        for z in zombie_group:
            z.first_frame = z.direction * z.columns / 2
            z.last_frame = z.first_frame + z.columns - 1
            if z.frame < z.first_frame:
                z.frame = z.first_frame
            z.velocity = calc_velocity(z.direction)
            z.add_x(z.velocity.x)
            z.add_y(z.velocity.y)
            if z.get_x() < 0 or z.get_x() > width-z.frame_width or z.get_y() < 0 or z.get_y() > height-z.frame_height:
                reverse_direction(z)

        #检查僵尸与玩家的冲突
        attacker = None
        attacker = pygame.sprite.spritecollideany(player, zombie_group)

        if attacker != None:
            if pygame.sprite.collide_rect_ratio(0.5)(player, attacker):
                player_health -= 10
                if attacker.get_x() < player.get_x():
                    attacker.add_x(-10)
                elif attacker.get_x() > player.get_x():
                    attacker.add_x(10)
            else:
                attacker = None

        #食物逻辑
        health_group.update(ticks, 50)

        #检查玩家与食物的冲突
        if pygame.sprite.collide_rect_ratio(0.5)(player, health):
            player_health += 10
            if player_health > 100:
                player_health = 100
            if player_health <= 0:
                player_health = 0
                game_over = True
            health.set_pos((random.randint(0,width-health.frame_width),random.randint(0,height-health.frame_height)))

        screen.fill((50, 50, 100))

        health_group.draw(screen)
        zombie_group.draw(screen)
        player_group.draw(screen)

        pygame.draw.rect(screen, (50,150,50,180), Rect(200,470,player_health*2,25))
        pygame.draw.rect(screen, (100,200,100,180), Rect(200,470,200,25), 2)

        if game_over:
            print_text(font, 200, 100, "GAME OVER")

        pygame.display.update()

    time.sleep(1.0/60)

5.游戏展示

捕获.PNG
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,794评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,050评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,587评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,861评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,901评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,898评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,832评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,617评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,077评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,349评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,483评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,199评论 5 341
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,824评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,442评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,632评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,474评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,393评论 2 352

推荐阅读更多精彩内容

  • 2018年2月12日红源悟语 不忘初心,牢记使命,努力奋斗! 今日成长 人,一定要悟透自己。 今日感悟 每到春节都...
    红源随笔阅读 117评论 0 0
  • 她是一个越来越自卑的女孩,明明很优秀,却被周围的人说得一无是处,有的时候她会徘徊不定! 不...
    流云蓝心阅读 1,284评论 12 42
  • 手机突然停机,我在想,如果我就这样消失不见,会不会就这样被人遗忘,事实证明,我就是个容易被遗忘的人,走在空旷的街道...
    赵大撞阅读 175评论 0 1
  • 小桥相望有人来,口哨频吹笑脸开。 碧水只同花逝去,白云共与月徘徊。 酒常催句兴无倦,鬓已染霜心尚孩。 一醉不知身是...
    雪窗_武立之阅读 719评论 0 3