Exemple #1
0
class Background:
    '''此类用于描述背景对象'''
    __image = res.load_image("background.gif")

    def __init__(self, canvas, *, speed=1):
        self.__canvas = canvas
        self.__speed = speed

        # self.__canvas_height = canvas_height = int(canvas.config("height")[-1])
        self.__image_height = image_height = self.__image.height()

        self.__images_pos = [[0, 0], [0, -image_height]]
        self.__images_id = [
            self.__canvas.create_image(*pos, image=self.__image, anchor="nw")
            for pos in self.__images_pos
        ]

    def on_timer(self):
        '''刷新背景'''
        for pos in self.__images_pos:
            pos[1] += self.__speed
            if pos[1] > self.__image_height:
                pos[1] -= self.__image_height * 2
        for i, pos in enumerate(self.__images_pos):
            self.__canvas.coords(self.__images_id[i], *pos)
Exemple #2
0
class PlaneLabel:
    '''此类用于描述飞机个数的图片控件'''
    __image = res.load_image("plane_count.gif")

    def __init__(self, canvas, *, count=0):
        self.__canvas = canvas
        image = self.__image
        self.__pos = position = (image.width() * .75,
                                 canvas.height() - image.height() * .75)
        self.__images_id = self.__canvas.create_image(*position,
                                                      image=self.__image)
        self.__size = size = (image.width(), image.height())  # 宽和高(元组)

        text = self.__get_str(count)
        self.__font_id = canvas.create_text(position[0],
                                            position[1] + 20,
                                            text=text,
                                            font=("黑体", 18),
                                            fill='#333')

    def set_count(self, count):
        self.__canvas.itemconfigure(self.__font_id, text=self.__get_str(count))
        self.__canvas.tag_raise(self.__images_id)
        self.__canvas.tag_raise(self.__font_id)

    def __get_str(self, n):
        return "x" + str(n)
Exemple #3
0
class Bullet(Arm):
    __images = [
        res.load_image("bullet.gif")
    ]
    # image = res.load_image("bullet.gif")

    def __init__(self, canvas,  *, position, destroy_cb=None):
        self.__canvas = canvas
        image = self.__images[0]
        # 先算宽和高
        size = (image.width(), image.height())
        self.__image_id = canvas.create_image(*position, image=image)
        # self.__image = image
        self.__destroy_cb = destroy_cb

        super().__init__(position=position, size=size, speed=(0, -20))
        # 图片管理器
        self.__image_manager = FlyingImageManager(canvas,
                                                  self.__image_id,
                                                  position)

    def set_destroy(self):
        '''设置为击中销毁状态'''
        self.__canvas.delete(self.__image_id)
        if self.__destroy_cb:
            self.__destroy_cb(self)
   
    def on_timer(self):
        self.move()
        self.__image_manager.draw(self.pos())
        if self.pos()[1] < 0:
            self.set_destroy()
Exemple #4
0
def run():
    #create screen
    pygame.init()
    screen = pygame.display.set_mode(WINDOW_SIZE, RESIZABLE)

    #load res
    font = res.load_font(FONT_NAME, FONT_SIZE, FONTS_FOLDER)
    background_texture = res.load_image("back.png")[0]

    card_deck = CardDeck()
    card_deck.smart_locate_on_rect(screen.get_rect())
    text = font.render(TEXT_FOR_FORMAT.format(*card_deck.get_number_states()), 1, FONT_COLOR)

    sprites = pygame.sprite.Group(card_deck.cards)

    def create_background(size, tex):
        b = pygame.Surface(size)
        fill_fullsurface(b, tex)
        return b

    background = create_background(WINDOW_SIZE, background_texture)

    while 1:
        pressed_key = pygame.key.get_pressed()
        for event in pygame.event.get():
            if event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE:
                return
            elif event.type == KEYDOWN and event.key == K_SPACE or event.type == MOUSEBUTTONDOWN and event.button == 2:
                card_deck.all_set_states(Card.OPEN)
                text = font.render(TEXT_FOR_FORMAT.format(*card_deck.get_number_states()), 1, FONT_COLOR)
            elif event.type == MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                c = card_deck.get_by_point(pos)
                if event.button == 1 and pressed_key[K_TAB] or event.button == 3:
                    if c:
                        c.set_state(Card.YOUR if c.state != Card.YOUR else Card.OPEN)
                elif event.button == 1:
                    if c:
                        c.set_state(Card.CLOSE if c.state != Card.CLOSE else Card.OPEN)
                text = font.render(TEXT_FOR_FORMAT.format(*card_deck.get_number_states()), 1, FONT_COLOR)
            elif event.type == VIDEORESIZE:
                screen = pygame.display.set_mode(event.size, RESIZABLE)
                card_deck.smart_locate_on_rect(screen.get_rect())

                if not TABLE_COLOR:
                    background = create_background(event.size, background_texture)

        if TABLE_COLOR:
            screen.fill(TABLE_COLOR)
        else:
            screen.blit(background, (0, 0))

        sprites.draw(screen)

        screen.blit(text, (2, 0))

        pygame.display.flip()

        time.sleep(1. / FPS)
Exemple #5
0
    def __init__(self, number):
        pygame.sprite.Sprite.__init__(self)

        self.image, self.rect = res.load_image("{0}.png".format(number), CARDS_FOLDER)
        self.original_image, self.original_rect = self.image, self.rect
        self.scaled_image = self.original_image

        self.state = Card.OPEN
Exemple #6
0
def main():
    global FPSCLOCK, DISPLAYSURF, BASICFONT, L_SQUIR_IMG, R_SQUIR_IMG, GRASSIMAGES

    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    pygame.display.set_icon(load_image('gameicon.png'))
    DISPLAYSURF = pygame.display.set_mode((WINWIDTH, WINHEIGHT))
    pygame.display.set_caption('Squirrel Eat Squirrel')
    BASICFONT = pygame.font.Font('freesansbold.ttf', 32)

    # load the image files
    L_SQUIR_IMG = load_image('squirrel.png')
    R_SQUIR_IMG = pygame.transform.flip(L_SQUIR_IMG, True, False)
    GRASSIMAGES = load_images("grass*.png")

    while True:
        runGame()
Exemple #7
0
def main():
    global FPSCLOCK, DISPLAYSURF, REDPILERECT, BLACKPILERECT, REDTOKENIMG
    global BLACKTOKENIMG, BOARDIMG, ARROWIMG, ARROWRECT, HUMANWINNERIMG
    global COMPUTERWINNERIMG, WINNERRECT, TIEWINNERIMG

    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    pygame.display.set_caption('Four in a Row')

    REDPILERECT = pygame.Rect(int(SPACESIZE / 2), WINDOWHEIGHT - int(3 * SPACESIZE / 2), SPACESIZE, SPACESIZE)
    BLACKPILERECT = pygame.Rect(WINDOWWIDTH - int(3 * SPACESIZE / 2), WINDOWHEIGHT - int(3 * SPACESIZE / 2), SPACESIZE, SPACESIZE)
    REDTOKENIMG = scale_image(load_image('4row_red.png'),SPACESIZES)
    BLACKTOKENIMG = scale_image(load_image('4row_black.png'),SPACESIZES)
    BOARDIMG = scale_image(load_image('4row_board.png'),SPACESIZES)

    HUMANWINNERIMG = load_image('4row_humanwinner.png')
    COMPUTERWINNERIMG = load_image('4row_computerwinner.png')
    TIEWINNERIMG = load_image('4row_tie.png')
    WINNERRECT = HUMANWINNERIMG.get_rect()
    WINNERRECT.center = (int(WINDOWWIDTH / 2), int(WINDOWHEIGHT / 2))

    ARROWIMG = load_image('4row_arrow.png')
    ARROWRECT = ARROWIMG.get_rect()
    ARROWRECT.left = REDPILERECT.right + 10
    ARROWRECT.centery = REDPILERECT.centery

    isFirstGame = True

    while True:
        runGame(isFirstGame)
        isFirstGame = False
Exemple #8
0
class Gameover:
    '''此类用于描述游戏结束窗口'''
    __image = res.load_image("gameover.gif")

    def __init__(self, canvas):
        self.__canvas = canvas
        self.__images_id = self.__canvas.create_image(canvas.width() / 2,
                                                      canvas.height() / 2,
                                                      image=self.__image)
Exemple #9
0
class ResumeWidet(EventObject):
    '''此类用于描述临停窗口'''
    __image = res.load_image("pause.gif")

    # 此窗口的状态:
    # NORMAL = 1  # 显示状态
    # DESTROY = 2  # 销毁状态
    def __init__(self, canvas, *, resume_cb=None, destroy_cb=None):
        # self.__status = self.NORMAL  # 设置显示状态
        self.__canvas = canvas
        self.__image_id = self.__canvas.create_image(canvas.width() / 2,
                                                     canvas.height() / 2,
                                                     image=self.__image)
        self.__resume_cb = resume_cb
        self.__destroy_cb = destroy_cb
        self.__destroy_count = 75
        print("in resume Fred")

    # def __del__(self):
    #     print("PauseWidget 对象已销毁")

    def resume(self):
        if self.__resume_cb:
            self.__resume_cb()
        self.__canvas.delete(self.__image_id)
        canvas = self.__canvas
        self.__image_id = canvas.create_text(canvas.width() / 2,
                                             canvas.height() / 2,
                                             text="3",
                                             font=("黑体", 200),
                                             fill='yellow')

    def on_key_down(self, event):
        '''处理按键按下'''
        if event.keysym == 'r':
            self.resume()
            print("Fred in resume on_key_down")
        return True

    def on_mouse_down(self, event):
        '''处理鼠标左键按键按下'''
        if event.num == 1:
            self.resume()
        return True

    def on_timer(self):
        self.__destroy_count -= 1
        if self.__destroy_count % 25 == 0:
            n = self.__destroy_count // 25
            self.__canvas.itemconfigure(self.__image_id, text=str(n))
        if self.__destroy_count <= 0:
            self.__canvas.delete(self.__image_id)
            if self.__destroy_cb:
                self.__destroy_cb()
        return True
Exemple #10
0
def main():
    global MAINCLOCK, DISPLAYSURF, FONT, BIGFONT, BGIMAGE

    pygame.init()
    MAINCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    pygame.display.set_caption('Flippy')
    FONT = pygame.font.Font('freesansbold.ttf', 16)
    BIGFONT = pygame.font.Font('freesansbold.ttf', 32)

    # Set up the background image.
    boardImage = scale_image(load_image('flippyboard.png'),(BOARDWIDTH * SPACESIZE, BOARDHEIGHT * SPACESIZE))
    boardImageRect = boardImage.get_rect()
    boardImageRect.topleft = (XMARGIN, YMARGIN)
    BGIMAGE = scale_image(load_image('flippybackground.png'),(WINDOWWIDTH, WINDOWHEIGHT))
    BGIMAGE.blit(boardImage, boardImageRect)

    # Run the main game.
    while True:
        if runGame() == False:
            break
Exemple #11
0
class PauseButton(EventObject):
    '''此类用于描述暂停控件'''
    __image = res.load_image("game_pause_nor.gif")

    def __init__(self, canvas, *, callback=None):
        self.__canvas = canvas
        image = self.__image
        self.__pos = position = (image.width() * 0.75, image.height() * 0.75)
        self.__images_id = self.__canvas.create_image(*position,
                                                      image=self.__image)
        self.__click_cb = callback

        self.__size = (image.width(), image.height())  # 宽和高(元组)

    def on_key_down(self, event):
        '''处理按键按下'''
        if event.keysym == 'p':
            if self.__click_cb:
                self.__click_cb()
                return True

    def is_touch(self, x, y):
        if y > self.__pos[1] + self.__size[1] / 2:
            return False
        if x < self.__pos[0] - self.__size[0] / 2:
            return False
        if x > self.__pos[0] + self.__size[0] / 2:
            return False
        if y < self.__pos[1] - self.__size[1] / 2:
            return False
        return True

    def on_mouse_down(self, event):
        '''处理鼠标左键按键按下'''
        if event.num == 1 and self.is_touch(event.x, event.y):
            if self.__click_cb:
                self.__click_cb()
                return True
Exemple #12
0
def main():
    global FPSCLOCK, DISPLAYSURF, LOGOIMAGE, SPOTIMAGE, SETTINGSIMAGE, SETTINGSBUTTONIMAGE, RESETBUTTONIMAGE

    pygame.init()
    FPSCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))

    # Load images
    LOGOIMAGE = load_image('inkspilllogo.png')
    SPOTIMAGE = load_image('inkspillspot.png')
    SETTINGSIMAGE = load_image('inkspillsettings.png')
    SETTINGSBUTTONIMAGE = load_image('inkspillsettingsbutton.png')
    RESETBUTTONIMAGE = load_image('inkspillresetbutton.png')

    pygame.display.set_caption('Ink Spill')
    mousex = 0
    mousey = 0
    mainBoard = generateRandomBoard(boardWidth, boardHeight, difficulty)
    life = maxLife
    lastPaletteClicked = None

    while True: # main game loop
        paletteClicked = None
        resetGame = False

        # Draw the screen.
        DISPLAYSURF.fill(bgColor)
        drawLogoAndButtons()
        drawBoard(mainBoard)
        drawLifeMeter(life)
        drawPalettes()

        checkForQuit()
        for event in pygame.event.get(): # event handling loop
            if event.type == MOUSEBUTTONUP:
                mousex, mousey = event.pos
                if pygame.Rect(WINDOWWIDTH - SETTINGSBUTTONIMAGE.get_width(),
                               WINDOWHEIGHT - SETTINGSBUTTONIMAGE.get_height(),
                               SETTINGSBUTTONIMAGE.get_width(),
                               SETTINGSBUTTONIMAGE.get_height()).collidepoint(mousex, mousey):
                    resetGame = showSettingsScreen() # clicked on Settings button
                elif pygame.Rect(WINDOWWIDTH - RESETBUTTONIMAGE.get_width(),
                                 WINDOWHEIGHT - SETTINGSBUTTONIMAGE.get_height() - RESETBUTTONIMAGE.get_height(),
                                 RESETBUTTONIMAGE.get_width(),
                                 RESETBUTTONIMAGE.get_height()).collidepoint(mousex, mousey):
                    resetGame = True # clicked on Reset button
                else:
                    # check if a palette button was clicked
                    paletteClicked = getColorOfPaletteAt(mousex, mousey)

        if paletteClicked != None and paletteClicked != lastPaletteClicked:
            # a palette button was clicked that is different from the
            # last palette button clicked (this check prevents the player
            # from accidentally clicking the same palette twice)
            lastPaletteClicked = paletteClicked
            floodAnimation(mainBoard, paletteClicked)
            life -= 1

            resetGame = False
            if hasWon(mainBoard):
                for i in range(4): # flash border 4 times
                    flashBorderAnimation(WHITE, mainBoard)
                resetGame = True
                pygame.time.wait(2000) # pause so the player can bask in victory
            elif life == 0:
                # life is zero, so player has lost
                drawLifeMeter(0)
                pygame.display.update()
                pygame.time.wait(400)
                for i in range(4):
                    flashBorderAnimation(BLACK, mainBoard)
                resetGame = True
                pygame.time.wait(2000) # pause so the player can suffer in their defeat

        if resetGame:
            # start a new game
            mainBoard = generateRandomBoard(boardWidth, boardHeight, difficulty)
            life = maxLife
            lastPaletteClicked = None

        pygame.display.update()
        FPSCLOCK.tick(FPS)
Exemple #13
0
import pygame, sys
from pygame.locals import *
from res import load_image

pygame.init()

FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()

# set up the window
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption('Animation')

WHITE = (255, 255, 255)
catImg = load_image('cat.png')
catx = 10
caty = 10
direction = 'right'

while True: # the main game loop
    DISPLAYSURF.fill(WHITE)

    if direction == 'right':
        catx += 5
        if catx == 280:
            direction = 'down'
    elif direction == 'down':
        caty += 5
        if caty == 220:
            direction = 'left'
    elif direction == 'left':
Exemple #14
0
class StartWindow(EventObject):
    """此类用于实现开始窗口对象
    """
    __images = [
        res.load_image("start2.gif"),
        res.load_image("start_label.gif")
    ]
    # 此窗口的状态:
    NORMAL = 1  # 显示状态
    DESTROY = 2  # 销毁状态

    def __init__(self, canvas, *, start_callback=None, destroy=None):
        self.__status = self.NORMAL  # 设置显示状态
        self.__canvas = canvas
        self.__start_fn = start_callback
        self.__destroy_cb = destroy

        image = self.__images[0]

        # 画布尺寸
        canvas_width = canvas.width()
        canvas_height = canvas.height()

        self.__pos = [canvas_width / 2, canvas_height / 2 + 3]

        # 设置飞机的初始图片
        self.__image_id = canvas.create_image(*self.__pos, image=image)
        self.__start_id = canvas.create_image(self.__pos[0],
                                              self.__pos[1] + 20,
                                              image=self.__images[1])

    def move(self, offset):
        '''根据偏移量移动,当超出范围时较正位置'''
        self.__pos[0] += offset[0]
        self.__pos[1] += offset[1]

    def start_game(self):
        print("self in startwinodw class: ", self)
        self.__start_fn()
        self.__status = self.DESTROY

    def on_key_down(self, event):
        '''处理按键按下'''
        if event.keysym == 'space':
            self.start_game()
            return True

    def on_mouse_down(self, event):
        '''处理鼠标左键按键按下'''
        if event.num == 1:
            self.start_game()
            return True

    def on_timer(self):
        self.move((0, -20))
        self.__canvas.coords(self.__image_id, *self.__pos)
        self.__canvas.coords(self.__start_id, self.__pos[0],
                             self.__pos[1] + 20)
        # if self.__pos[1] < -100 and self.__destroy_cb:  # 调试用
        if self.__pos[1] < -500 and self.__destroy_cb:
            self.__canvas.delete(self.__image_id)
            self.__canvas.delete(self.__start_id)
            self.__destroy_cb(self)
Exemple #15
0
class HeroPlane(Arm):
    """此类是英雄飞机类,此类继承自飞机对象,所有的飞机地象有相同的行为:
    移动、发射子弹等的对象是一个或多个同样的英雄飞机
    """
    __images = [
        res.load_image("hero2.gif"),
        res.load_image("hero1.gif"),
        res.load_image("hero_blowup_n1.gif"),
        res.load_image("hero_blowup_n2.gif"),
        res.load_image("hero_blowup_n3.gif"),
        res.load_image("hero_blowup_n4.gif"),
    ]
    # 飞机的状态:
    NORMAL = 1  # 正常飞行状态
    DESTROY = 2  # 被击中状态,正在销毁中

    def __init__(self, canvas, *, destroy_cb=None):

        self.__status = self.NORMAL  # 设置飞行状态为正常飞行
        self.__canvas = canvas
        self.__destroy_cb = destroy_cb

        image = self.__images[0]
        # self.old_image = self.new_image = self.__images[0]  # 设置当前显示图片

        # 画布尺寸
        canvas_width = canvas.width()
        canvas_height = canvas.height()
        # canvas_width = int(canvas.config("width")[-1])
        # canvas_height = int(canvas.config("height")[-1])

        # 计算飞机能够飞行的的上下左右边缘
        self.__left_side = image.width()/2  # 左边缘
        self.__right_side = canvas_width - image.width()/2  # 右边缘
        self.__top_side = image.height()/2  # 上边缘
        self.__bottom_side = canvas_height - image.height()/2  # 下边缘

        # 把飞机的初始放在图片的底部 (x坐标,y轴坐标)
        x = int(canvas_width / 2)
        y = int(canvas_height - image.height() / 2)
        pos = (x, y)
        # self.set_position((x, y))
        size = (image.width(), image.height())
        super().__init__(position=pos, size=size)

        # 此集合用于存放用户操作的按键或鼠标事件
        self.__key_evens = set()

        # 设置飞机的初始图片
        self.__image_id = canvas.create_image(pos, image=image)

        # 正常飞行时采用正常飞行图片管理器
        self.__image_manager = HeroPlaneImageManager(canvas,
                                                     self.__image_id,
                                                     self.__images[:2],
                                                     pos)
        # 鼠示的按下状态
        self.__mouse_down = False

        # -----子弹相关----
        from gamelist import TimerList
        self.__bullet_list = TimerList()
        self.__bullet_interval = 10  # 每秒钟2.5 发子弹
        self.__bullet_count = 0  # 子弹计数
    
    # def __del__(self):
    #     print("英雄飞机已销毁..........")

    def destory_self(self):
        self.__image_manager = None
        self.__canvas.delete(self.__image_id)
        self.__bullet_list.clear()
        if self.__destroy_cb:
            self.__destroy_cb(self)

    def is_flying(self):
        '''判断是否是正常飞行状态'''
        return self.__status == self.NORMAL

    def is_destroy(self):
        '''判断是否是击中销毁状态'''
        return self.__status == self.DESTROY

    def set_destroy(self):
        '''设置为击中销毁状态'''
        self.__status = self.DESTROY
        # self.__image_manager = DestroyImageAnimate(self.__canvas,
        #                                             self.__image_id,
        #                                             self.__destroy_images,
        #                                             callback=self.destory_self)
        self.__image_manager = DestroyImageAnimate(
            self.__canvas, self.__image_id, self.__images[2:],
            callback=self.destory_self)

    def __adjust_pos(self, position):
        '''校正飞机的坐标,如果超出地图,则修改正回来'''
        x, y = position
        if x < self.__left_side:
            x = self.__left_side
        if x > self.__right_side:
            x = self.__right_side
        if y < self.__top_side:
            y = self.__top_side
        if y > self.__bottom_side:
            y = self.__bottom_side
        super().set_position((x, y))

    def set_position(self, position):
        self.__adjust_pos(position)

    def move(self, offset):
        '''根据偏移量移动,当超出范围时较正位置'''
        x, y = self.pos()
        x += offset[0]
        y += offset[1]
        self.__adjust_pos((x, y))
        if offset[1] < 0:
            self.__image_manager.set_acelerator()
        else:
            self.__image_manager.set_acelerator(False)

    def on_key_down(self, event):
        '''处理按键按下'''
        # 当有铵键按下,把按键加入到集合中记录下来
        self.__key_evens.add(event.keysym.lower())

    def on_key_up(self, event):
        '''处理按键抬起'''
        # 当有铵键抬起,把按键从集合中移除
        self.__key_evens.discard(event.keysym.lower())

    def on_mouse_down(self, event):
        '''处理鼠标左键按键按下'''
        if event.num == 2:
            # self.set_destroy()
            self.fire()
            return
        if event.num != 1:
            return

        self.__mouse_down = True
        self.mouse_pos = (event.x, event.y)

    def on_mouse_up(self, event):
        '''处理鼠标左键按键抬起'''
        if event.num != 1:
            return
        self.__mouse_down = False
        if self.is_flying():
            self.__image_manager.set_acelerator(False)

    def on_mouse_move(self, event):
        '''处理鼠标左键按下的同时移动'''
        if not self.__mouse_down:
            return

        # x = event.x
        # y = event.y
        offset = (event.x - self.mouse_pos[0], event.y - self.mouse_pos[1])
        self.mouse_pos = (event.x, event.y)  # 用新位置替换旧位置
        self.move(offset)

    def process_key_event(self):
        '''检查键盘状态,计算飞机飞行移动位置'''
        if self.is_destroy():  # 如果飞机已被击中,键盘无效
            return
        if self.__mouse_down:
            return

        assert self.is_flying()
        speed = 5
        self.__image_manager.set_acelerator(False)
        if 'a' in self.__key_evens or 'left' in self.__key_evens:
            self.move((-speed, 0))
        if 'd' in self.__key_evens or 'right' in self.__key_evens:
            self.move((speed, 0))
        if 'w' in self.__key_evens or 'up' in self.__key_evens:
            self.move((0, -speed))
            self.__image_manager.set_acelerator()
        if 's' in self.__key_evens or 'down' in self.__key_evens:
            self.move((0, speed))

    def fire(self):
        '''英雄飞机开火 '''
        x, y = self.pos()
        # y -= 60

        if False:
            # 单子弹位置(0, -60)
            pos = (x, y-60)
            b1 = Bullet(self.__canvas, position=pos,
                        destroy_cb=self.__bullet_list.remove)
            self.__bullet_list.append(b1)
        else:
            # 双子弹位置(-32, -18)和 (32, -18)
            pos1 = (x-32, y-18)
            pos2 = (x+32, y-18)
            b1 = Bullet(self.__canvas, position=pos1, destroy_cb=self.__bullet_list.remove)
            self.__bullet_list.append(b1)
            b1 = Bullet(self.__canvas, position=pos2, destroy_cb=self.__bullet_list.remove)
            self.__bullet_list.append(b1)

    def check_attack(self, lst):
        '''此方法检测英雄飞机及子弹是否打印敌机,以及是否与英雄飞机进行碰幢
        返回元组:
           第一个元素: 飞机是否幢True/False
           第二个元素: 本次得分
           return (False, 20)  # 本次得到20飞机没有被幢到
        '''
        score = 0
        # 检查子弹是否打到敌机
        i = 0
        bullet_list = self.__bullet_list.get_objs()
        while i < len(bullet_list):
            bullet = bullet_list[i]
            for j, ep  in enumerate(lst):
                if bullet.is_touch(ep):
                    ep.set_destroy()
                    del lst[j]
                    bullet.set_destroy()
                    score += 1
                    break
            else:
                i += 1

        # 检查飞机是否被幢 
        for i, ep in enumerate(lst):
            if self.is_touch(ep):
                ep.set_destroy()
                self.set_destroy()
                del lst[i]
                break
        return score

    # def is_touch(self, other):
    #     '''自定义飞机的碰幢检测'''
    #     if super().is_touch(other):
    #         return True
    #     return False

    def on_timer(self):
        if self.is_flying():
            self.process_key_event()  # 先处理按键事件
            # --- begin处理子弹是否发射---------
            self.__bullet_count += 1
            if self.__bullet_count >= self.__bullet_interval:
                self.__bullet_count = 0
                self.fire()
            # --- end 处理子弹是否发射---------
            self.__image_manager.draw(self.int_position())
        elif self.is_destroy():
            if self.__image_manager:
                self.__image_manager.draw()
        self.__bullet_list.on_timer()
Exemple #16
0
def main():
    global FPSCLOCK, DISPLAYSURF, IMAGESDICT, TILEMAPPING, OUTSIDEDECOMAPPING, BASICFONT, PLAYERIMAGES, currentImage

    # Pygame initialization and basic set up of the global variables.
    pygame.init()
    FPSCLOCK = pygame.time.Clock()

    # Because the Surface object stored in DISPLAYSURF was returned
    # from the pygame.display.set_mode() function, this is the
    # Surface object that is drawn to the actual computer screen
    # when pygame.display.update() is called.
    DISPLAYSURF = pygame.display.set_mode((WINWIDTH, WINHEIGHT))

    pygame.display.set_caption('Star Pusher')
    BASICFONT = pygame.font.Font('freesansbold.ttf', 18)

    # A global dict value that will contain all the Pygame
    # Surface objects returned by load_image().
    IMAGESDICT = {'uncovered goal': load_image('RedSelector.png'),
                  'covered goal': load_image('Selector.png'),
                  'star': load_image('Star.png'),
                  'corner': load_image('Wall_Block_Tall.png'),
                  'wall': load_image('Wood_Block_Tall.png'),
                  'inside floor': load_image('Plain_Block.png'),
                  'outside floor': load_image('Grass_Block.png'),
                  'title': load_image('star_title.png'),
                  'solved': load_image('star_solved.png'),
                  'princess': load_image('princess.png'),
                  'boy': load_image('boy.png'),
                  'catgirl': load_image('catgirl.png'),
                  'horngirl': load_image('horngirl.png'),
                  'pinkgirl': load_image('pinkgirl.png'),
                  'rock': load_image('Rock.png'),
                  'short tree': load_image('Tree_Short.png'),
                  'tall tree': load_image('Tree_Tall.png'),
                  'ugly tree': load_image('Tree_Ugly.png')}

    # These dict values are global, and map the character that appears
    # in the level file to the Surface object it represents.
    TILEMAPPING = {'x': IMAGESDICT['corner'],
                   '#': IMAGESDICT['wall'],
                   'o': IMAGESDICT['inside floor'],
                   ' ': IMAGESDICT['outside floor']}
    OUTSIDEDECOMAPPING = {'1': IMAGESDICT['rock'],
                          '2': IMAGESDICT['short tree'],
                          '3': IMAGESDICT['tall tree'],
                          '4': IMAGESDICT['ugly tree']}

    # PLAYERIMAGES is a list of all possible characters the player can be.
    # currentImage is the index of the player's current player image.
    currentImage = 0
    PLAYERIMAGES = [IMAGESDICT['princess'],
                    IMAGESDICT['boy'],
                    IMAGESDICT['catgirl'],
                    IMAGESDICT['horngirl'],
                    IMAGESDICT['pinkgirl']]

    startScreen() # show the title screen until the user presses a key

    # Read in the levels from the text file. See the readLevelsFile() for
    # details on the format of this file and how to make your own levels.
    levels = readLevelsFile('starPusherLevels.txt')
    currentLevelIndex = 0

    # The main game loop. This loop runs a single level, when the user
    # finishes that level, the next/previous level is loaded.
    while True: # main game loop
        # Run the level to actually start playing the game:
        result = runLevel(levels, currentLevelIndex)

        if result in ('solved', 'next'):
            # Go to the next level.
            currentLevelIndex += 1
            if currentLevelIndex >= len(levels):
                # If there are no more levels, go back to the first one.
                currentLevelIndex = 0
        elif result == 'back':
            # Go to the previous level.
            currentLevelIndex -= 1
            if currentLevelIndex < 0:
                # If there are no previous levels, go to the last one.
                currentLevelIndex = len(levels)-1
        elif result == 'reset':
            pass # Do nothing. Loop re-calls runLevel() to reset the level