电脑时间 发表于 2022-10-18 19:52:25

Python小游戏:飞机大战{更新1.9}

本帖最后由 电脑时间 于 2023-2-8 09:25 编辑

更新:
1 使用exe
2 修复 飞机过大
3 有彩蛋
链接:
https://pan.huang1111.cn/s/mzEoS1
提取码:DNSJ

飞机大战就是玩家飞机通过发射子弹来击落敌机
已知问题:
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.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 =
    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 =
            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.rect)
            player.img_index = shoot_frequency // 8
      else:
            player.img_index = player_down_index // 8
            screen.blit(player.image, 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.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 =
      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 or key_pressed:
            player.moveUp()
      if key_pressed or key_pressed:
            player.moveDown()
      if key_pressed or key_pressed:
            player.moveLeft()
      if key_pressed or key_pressed:
            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').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').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 \
                  and event.pos <= screen.get_rect().centerx + 50 \
                  and screen.get_rect().centery + 100 <= event.pos \
                  and screen.get_rect().centery + 140 >= event.pos:
                startGame()
            if screen.get_rect().centerx - 70 <= event.pos \
                  and event.pos <= screen.get_rect().centerx + 50 \
                  and screen.get_rect().centery + 160 <= event.pos \
                  and screen.get_rect().centery + 200 >= event.pos:
                gameRanking()
    pygame.display.update()

电脑时间 发表于 2022-11-3 07:54:16

要装Pygame
要不然只会有命令行窗口一闪而过

电脑时间 发表于 2022-10-18 19:52:49

放不了图片{:16:}

314 发表于 2022-10-18 20:04:35

emmm。。。我电脑打不开。

yangeryuner 发表于 2022-10-18 21:13:07

我发现咱们论坛好多坛友都会python啊,厉害!

OOO 发表于 2022-10-18 23:13:27

不放点图么?
我比较好奇,飞机是啥样的。

314 发表于 2022-10-18 23:32:19

OOO 发表于 2022-10-18 23:13
不放点图么?
我比较好奇,飞机是啥样的。

压缩包里有图片。

0Percent 发表于 2022-10-19 08:33:10

看起来不错 下回来玩玩

jyssysz 发表于 2022-10-19 08:59:55

其实可以截个图放上来!
小朋友佳作不断呀。
页: [1] 2 3 4 5
查看完整版本: Python小游戏:飞机大战{更新1.9}