请选择 进入手机版 | 继续访问电脑版

萝卜头IT论坛

了解更多
搜索
查看: 424|回复: 31
收起左侧

Python小游戏:飞机大战

  [复制链接]
发表于 2022-10-18 19:52:25 | 显示全部楼层 |阅读模式
本帖最后由 电脑时间 于 2022-10-21 09:21 编辑

没打包
飞机大战.zip (724.75 KB, 下载次数: 36)
飞机大战就是玩家飞机通过发射子弹来击落敌机
已知问题:
1 玩家飞机图片过大
2 敌机有可能出生在角落
3 可以漏过敌机
源代码(PyCharm上的色)


# -*- coding: utf-8 -*-
import pygame      
from pygame.locals import *
from sys import exit
import random
import codecs

SCREEN_WIDTH = 480
SCREEN_HEIGHT = 800

# 子弹类
class Bullet(pygame.sprite.Sprite):
    def __init__(self, bullet_img, init_pos):

        pygame.sprite.Sprite.__init__(self)
        self.image = bullet_img
        self.rect = self.image.get_rect()
        self.rect.midbottom = init_pos
        self.speed = 10

    def move(self):
        self.rect.top -= self.speed

# 玩家飞机类
class Player(pygame.sprite.Sprite):
    def __init__(self, player_rect, init_pos):
        pygame.sprite.Sprite.__init__(self)
        self.image = []
        for i in range(len(player_rect)):
            self.image.append(player_rect.convert_alpha())

        self.rect = player_rect[0].get_rect()
        self.rect.topleft = init_pos
        self.speed = 8
        self.bullets = pygame.sprite.Group()
        self.img_index = 0
        self.is_hit = False

    def shoot(self, bullet_img):
        bullet = Bullet(bullet_img, self.rect.midtop)
        self.bullets.add(bullet)

    def moveUp(self):
        if self.rect.top <= 0:
            self.rect.top = 0
        else:
            self.rect.top -= self.speed

    def moveDown(self):
        if self.rect.top >= SCREEN_HEIGHT - self.rect.height:
            self.rect.top = SCREEN_HEIGHT - self.rect.height
        else:
            self.rect.top += self.speed

    def moveLeft(self):
        if self.rect.left <= 0:
            self.rect.left = 0
        else:
            self.rect.left -= self.speed

    def moveRight(self):
        if self.rect.left >= SCREEN_WIDTH - self.rect.width:
            self.rect.left = SCREEN_WIDTH - self.rect.width
        else:
            self.rect.left += self.speed

class Enemy(pygame.sprite.Sprite):
    def __init__(self, enemy_img, enemy_down_imgs, init_pos):
        pygame.sprite.Sprite.__init__(self)
        self.image = enemy_img
        self.rect = self.image.get_rect()
        self.rect.topleft = init_pos
        self.down_imgs = enemy_down_imgs
        self.speed = 2
        self.down_index = 0

    # 敌机移动,边界判断及删除在游戏主循环里处理
    def move(self):
        self.rect.top += self.speed

def write_txt(content, strim, path):
    f = codecs.open(path, strim, 'utf8')
    f.write(str(content))
    f.close()

def read_txt(path):
    with open(path, 'r', encoding='utf8') as f:
        lines = f.readlines()
    return lines


pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
ic_launcher = pygame.image.load('resources/image/ic_launcher.png').convert_alpha()
pygame.display.set_caption('彩图版飞机大战 By 电脑时间')
pygame.display.set_icon(ic_launcher)
background = pygame.image.load('resources/image/background.png').convert_alpha()
game_over = pygame.image.load('resources/image/gameover.png')
plane_bullet = pygame.image.load('resources/image/bullet.png')
player_img1= pygame.image.load('resources/image/player1.png')
player_img2= pygame.image.load('resources/image/player2.png')
player_img3= pygame.image.load('resources/image/player_off1.png')
player_img4= pygame.image.load('resources/image/player_off2.png')
player_img5= pygame.image.load('resources/image/player_off3.png')
enemy_img1= pygame.image.load('resources/image/enemy1.png')
enemy_img2= pygame.image.load('resources/image/enemy2.png')
enemy_img3= pygame.image.load('resources/image/enemy3.png')
enemy_img4= pygame.image.load('resources/image/enemy4.png')
def startGame():
    player_rect = []
    player_rect.append(player_img1)
    player_rect.append(player_img2)
    player_rect.append(player_img2)
    player_rect.append(player_img3)
    player_rect.append(player_img4)
    player_rect.append(player_img5)
    player_pos = [200, 600]
    player = Player(player_rect, player_pos)
    bullet_img = plane_bullet
    enemy1_img = enemy_img1
    enemy1_rect=enemy1_img.get_rect()
    enemy1_down_imgs = []
    enemy1_down_imgs.append(enemy_img1)
    enemy1_down_imgs.append(enemy_img2)
    enemy1_down_imgs.append(enemy_img3)
    enemy1_down_imgs.append(enemy_img4)
    enemies1 = pygame.sprite.Group()
    enemies_down = pygame.sprite.Group()
    shoot_frequency = 0
    enemy_frequency = 0
    player_down_index = 16
    score = 0
    clock = pygame.time.Clock()
    running = True
    while running:
        screen.fill(0)
        screen.blit(background, (0, 0))
        clock.tick(60)
        if not player.is_hit:
            if shoot_frequency % 15 == 0:
                player.shoot(bullet_img)
            shoot_frequency += 1
            if shoot_frequency >= 15:
                shoot_frequency = 0
        for bullet in player.bullets:
            bullet.move()
            if bullet.rect.bottom < 0:
                player.bullets.remove(bullet)
        player.bullets.draw(screen)
        if enemy_frequency % 50 == 0:
            enemy1_pos = [random.randint(0, SCREEN_WIDTH - enemy1_rect.width), 0]
            enemy1 = Enemy(enemy1_img, enemy1_down_imgs, enemy1_pos)
            enemies1.add(enemy1)
        enemy_frequency += 1
        if enemy_frequency >= 100:
            enemy_frequency = 0
        for enemy in enemies1:
            enemy.move()
            if pygame.sprite.collide_circle(enemy, player):
                enemies_down.add(enemy)
                enemies1.remove(enemy)
                player.is_hit = True
                break
            if enemy.rect.top < 0:
                enemies1.remove(enemy)
        enemies1_down = pygame.sprite.groupcollide(enemies1, player.bullets, 1, 1)
        for enemy_down in enemies1_down:
            enemies_down.add(enemy_down)
        if not player.is_hit:
            screen.blit(player.image[player.img_index], player.rect)
            player.img_index = shoot_frequency // 8
        else:
            player.img_index = player_down_index // 8
            screen.blit(player.image[player.img_index], player.rect)
            player_down_index += 1
            if player_down_index > 47:
                running = False
        for enemy_down in enemies_down:
            if enemy_down.down_index == 0:
                pass
            if enemy_down.down_index > 7:
                enemies_down.remove(enemy_down)
                score += 100
                continue
            screen.blit(enemy_down.down_imgs[enemy_down.down_index // 2], enemy_down.rect)
            enemy_down.down_index += 1
        enemies1.draw(screen)
        score_font = pygame.font.Font(None, 36)
        score_text = score_font.render(str(score), True, (255, 255, 255))
        text_rect = score_text.get_rect()
        text_rect.topleft = [10, 10]
        screen.blit(score_text, text_rect)
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
        key_pressed = pygame.key.get_pressed()
        if key_pressed[K_w] or key_pressed[K_UP]:
            player.moveUp()
        if key_pressed[K_s] or key_pressed[K_DOWN]:
            player.moveDown()
        if key_pressed[K_a] or key_pressed[K_LEFT]:
            player.moveLeft()
        if key_pressed[K_d] or key_pressed[K_RIGHT]:
            player.moveRight()

    screen.blit(game_over, (0, 0))
    font = pygame.font.Font(None, 48)
    text = font.render('Score: ' + str(score), True, (255, 255, 255))
    text_rect = text.get_rect()
    text_rect.centerx = screen.get_rect().centerx
    text_rect.centery = screen.get_rect().centery + 24
    screen.blit(text, text_rect)
    xtfont = pygame.font.SysFont('SimHei', 30)
    textstart = xtfont.render('重新开始 ', True, (255, 255, 255))
    text_rect = textstart.get_rect()
    text_rect.centerx = screen.get_rect().centerx
    text_rect.centery = screen.get_rect().centery + 120
    screen.blit(textstart, text_rect)
    textstart = xtfont.render('排行榜 ', True, (255, 255, 255))
    text_rect = textstart.get_rect()
    text_rect.centerx = screen.get_rect().centerx
    text_rect.centery = screen.get_rect().centery + 180
    screen.blit(textstart, text_rect)

    j = 0
    arrayscore = read_txt(r'score.txt')[0].split('mr')
    for i in range(0, len(arrayscore)):
        if score > int(arrayscore):
            j = arrayscore
            arrayscore = str(score)
            score = 0
        if int(j) > int(arrayscore):
            k = arrayscore
            arrayscore = str(j)
            j = k
    for i in range(0, len(arrayscore)):
        if i == 0:
            write_txt(arrayscore + 'mr', 'w', r'score.txt')
        else:
            if (i == 9):
                write_txt(arrayscore, 'a', r'score.txt')
            else:
                write_txt(arrayscore + 'mr', 'a', r'score.txt')

def gameRanking():
    screen2 = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    screen2.fill(0)
    screen2.blit(background, (0, 0))
    xtfont = pygame.font.SysFont('SimHei', 30)
    textstart = xtfont.render('排行榜 ', True, (255, 0, 0))
    text_rect = textstart.get_rect()
    text_rect.centerx = screen.get_rect().centerx
    text_rect.centery = 50
    screen.blit(textstart, text_rect)
    textstart = xtfont.render('重新开始 ', True, (255, 0, 0))
    text_rect = textstart.get_rect()
    text_rect.centerx = screen.get_rect().centerx
    text_rect.centery = screen.get_rect().centery + 120
    screen2.blit(textstart, text_rect)
    arrayscore = read_txt(r'score.txt')[0].split('mr')
    for i in range(0, len(arrayscore)):
        font = pygame.font.Font(None, 48)
        k=i+1
        text = font.render(str(k) +"  " +arrayscore, True, (255, 0, 0))
        text_rect = text.get_rect()
        text_rect.centerx = screen2.get_rect().centerx
        text_rect.centery = 80 + 30*k
        screen2.blit(text, text_rect)

startGame()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if screen.get_rect().centerx - 70 <= event.pos[0] \
                    and event.pos[0] <= screen.get_rect().centerx + 50 \
                    and screen.get_rect().centery + 100 <= event.pos[1] \
                    and screen.get_rect().centery + 140 >= event.pos[1]:
                startGame()
            if screen.get_rect().centerx - 70 <= event.pos[0] \
                    and event.pos[0] <= screen.get_rect().centerx + 50 \
                    and screen.get_rect().centery + 160 <= event.pos[1] \
                    and screen.get_rect().centery + 200 >= event.pos[1]:
                gameRanking()
    pygame.display.update()

评分

1

查看全部评分

回复

使用道具 举报

回复过本主题
的还回复过:
 楼主| 发表于 2022-11-3 07:54:16 | 显示全部楼层
要装Pygame
要不然只会有命令行窗口一闪而过
回复

使用道具 举报

 楼主| 发表于 2022-10-18 19:52:49 | 显示全部楼层
放不了图片
回复

使用道具 举报

发表于 2022-10-18 20:04:35 | 显示全部楼层
emmm。。。我电脑打不开。
回复

使用道具 举报

发表于 2022-10-18 21:13:07 | 显示全部楼层
我发现咱们论坛好多坛友都会python啊,厉害!
回复

使用道具 举报

发表于 2022-10-18 23:13:27 | 显示全部楼层
不放点图么?
我比较好奇,飞机是啥样的。
回复

使用道具 举报

发表于 2022-10-18 23:32:19 | 显示全部楼层
OOO 发表于 2022-10-18 23:13
不放点图么?
我比较好奇,飞机是啥样的。

压缩包里有图片。
回复

使用道具 举报

发表于 2022-10-19 08:33:10 | 显示全部楼层
看起来不错 下回来玩玩
回复

使用道具 举报

发表于 2022-10-19 08:59:55 | 显示全部楼层
其实可以截个图放上来!
小朋友佳作不断呀。
回复

使用道具 举报

联系我们(Contact)|手机版|萝卜头IT论坛 ( 苏ICP备15050961号-1 )

GMT+8, 2022-12-4 05:51 , Processed in 0.177965 second(s), 39 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表