python 3 비행기 대전 실현

12628 단어 python비행기 전쟁
본 논문 의 사례 는 python 3 비행기 대전 을 실현 하 는 구체 적 인 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.
다음은 파 이 썬 비행기 대전 의 모든 코드 를 직접 측정 하여 pygame 환경 지원 을 확보 하고 파 이 썬 3 해석 기 가 있 으 면 전혀 문제 가 없습니다!
마음 에 드 시 면 좋아요 눌 러 주세요!
다음 그림 과 같이 실행 효과:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#          
import pygame
from pygame.locals import *
from sys import exit 
import random

#          
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 800
import codecs
#    
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,plane_img,player_rect,init_pos):
  pygame.sprite.Sprite.__init__(self)
  self.image=[]
  for i in range(len(player_rect)):
   self.image.append(plane_img.subsurface(player_rect[i]).convert_alpha()) 
  self.rect = player_rect[0]
  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(contert, strim, path):
 f = codecs.open(path,strim, 'utf8')
 f.write(str(contert))
 f.close()

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




#    pygame
pygame.init()
#          ,    ,  
#   startGame(
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
#   
pygame.display.set_caption('    ')
#   
ic_launcher = pygame.image.load('resources/image/ic_launcher.png').convert_alpha()
pygame.display.set_icon(ic_launcher)
#    
background = pygame.image.load('resources/image/background.png').convert()
#     
game_over = pygame.image.load('resources/image/gameover.png')
#         
plane_img = pygame.image.load('resources/image/shoot.png')

def startGame():
 # 1.               ,           
 player_rect = []
 #        
 player_rect.append(pygame.Rect(0,99,102,126))
 player_rect.append(pygame.Rect(165,360,102,126))
 #          
 player_rect.append(pygame.Rect(165,234,102,126))
 player_rect.append(pygame.Rect(330,634,102,126))
 player_rect.append(pygame.Rect(330,498,102,126))
 player_rect.append(pygame.Rect(432,624,102,126))
 player_pos = [200,600]
 #        
 player = Player(plane_img,player_rect,player_pos)
 #        
 bullet_rect = pygame.Rect(69,77,10,21)
 bullet_img = plane_img.subsurface(bullet_rect)

 #       
 enemy1_rect = pygame.Rect(534,612,57,43) #        
 enemy1_img = plane_img.subsurface(enemy1_rect)
 enemy1_down_imgs = [] #        
 enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(267,347,57,43)))
 enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(873,679,57,43)))
 enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(267,296,57,43)))
 enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(930,697,57,43)))
 #        
 enmies1 = pygame.sprite.Group()
 #            
 enemies_down = pygame.sprite.Group()


 #         
 shoot_frequency = 0
 #          
 enemy_frequency = 0
 #              
 player_down_index = 16

 #        
 clock = pygame.time.Clock()
 #      
 score = 0
 #          
 running = True
 while running:
  for event in pygame.event.get():
   if event.type == pygame.QUIT:
    exit()
  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)
   #       
   enmies1.add(enemy1) 
  enemy_frequency += 1
  #       100      
  if enemy_frequency >= 100:
   enemy_frequency = 0
  #      
  for enemy in enmies1:
   enemy.move()
   #            
   if pygame.sprite.collide_circle(enemy,player): # pygame         
    enemies_down.add(enemy)  #             
    enmies1.remove(enemy)  #          
    player.is_hit = True 
    break 
   #         
   if enemy.rect.top < 0:
    enmies1.remove(enemy)
  #      
  enemies1_down = pygame.sprite.groupcollide(enmies1,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
  
  #     
  enmies1.draw(screen)
  #       
  score_font = pygame.font.Font(None,36)
  score_text = score_font.render(str(score),True,(128,128,128))
  text_rect = score_text.get_rect()
  text_rect.topleft = [10,10]
  screen.blit(score_text,text_rect)
  #        
  key_pressed = pygame.key.get_pressed()
  if key_pressed[K_UP] or key_pressed[K_w]:
   player.moveUp()
  if key_pressed[K_DOWN] or key_pressed[K_s]:
   player.moveDown()
  if key_pressed[K_LEFT] or key_pressed[K_a]:
   player.moveLeft()
  if key_pressed[K_RIGHT] or key_pressed[K_d]:
   player.moveRight()

  pygame.display.update()
 #         
 screen.blit(game_over,(0,0))
 #   Game Over      
 font = pygame.font.Font(None,48)
 text = font.render("Score:"+str(score),True,(255,0,0))
 text_rect = text.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x   
 text_rect.centery = screen.get_rect().centery + 24 # y   
 screen.blit(text,text_rect)
 #     
 xtfont = pygame.font.SysFont("jamrul",30)
 #         
 textstart = xtfont.render('Start',True,(255,0,0))
 text_rect = textstart.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x   
 text_rect.centery = screen.get_rect().centery + 120 # y   
 screen.blit(textstart,text_rect)
 #      
 textstart = xtfont.render('Ranking',True,(255,0,0))
 text_rect = textstart.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x   
 text_rect.centery = screen.get_rect().centery + 180 # y   
 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[i]):
   #                       
   j = arraysco.re[i]
   arrayscore[i] = str(score)
   score = 0
  #            
  if int(j) > int(arrayscore[i]):
   k = arrayscore[i]
   arrayscore[i] = str(j)
   j = k
 #            
 for i in range(0,len(arrayscore)):
  #           
  if i == 0:
   write_txt(arrayscore[i]+'mr','w',r'score.txt')
  else:
   #          
   if (i==9):
    #                mr
    write_txt(arrayscore[i],'a',r'score.txt')
   else:
    #         ,       mr
    write_txt(arrayscore[i]+'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('jamrul',30)
 # 1.    
 textstart = xtfont.render('Ranking',True,(255,0,0))
 text_rect = textstart.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x   
 text_rect.centery = 50 # y   
 screen.blit(textstart,text_rect)
 # 2.        
 textstart = xtfont.render('Start',True,(255,0,0))
 text_rect = textstart.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x   
 text_rect.centery = screen.get_rect().centery + 120 # y   
 screen.blit(textstart,text_rect)
 # 3.        
 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[i],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:
   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()
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기