import pygame
import sys
import mathpygame. init ( ) screen = pygame. display. set_mode ( ( 800 , 600 ) )
pygame. display. set_caption ( "Rotate and Shoot Bullets" ) # 定义子弹类
class Bullet: def __init__ ( self, x, y, angle) : self. x = xself. y = yself. angle = angleself. speed = 5 def update ( self) : rad_angle = math. radians ( self. angle) self. x = self. x+ math. cos ( rad_angle) * 5 self. y = self. y- math. sin ( rad_angle) * 5 def draw ( self) : p= pygame. draw. rect ( screen, ( 255 , 0 , 0 ) , ( int ( self. x) , int ( self. y) , 6 , 6 ) ) if ( p. collidelistall ( qsz) ) : # 碰撞检测xiansz. clear ( ) # 先清空数组,前面有初始化# self. endx, self. endy = self. x, self. yxiansz. append ( ( self. x, self. y) ) # 使用对象外的数组,要是对象自己的变量,在碰撞后会覆盖碰撞位置的x,yq = [ [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] ]
qsz= [ ]
bullets = [ ] # 子弹列表
player_x, player_y = 400 , 300 # 玩家位置初始值
player_angle = 0 # 玩家初始角度
c= pygame. time. Clock ( )
xiansz= [ ( 0 , 0 ) ]
while True: for event in pygame. event. get ( ) : if event. type == pygame. QUIT: pygame. quit ( ) sys. exit ( ) keys = pygame. key. get_pressed ( ) if keys[ pygame. K_LEFT] : player_angle += 1 # 左箭头键逆时针旋转elif keys[ pygame. K_RIGHT] : player_angle -= 1 # 右箭头键顺时针旋转elif keys[ pygame. K_SPACE] : bullets. append ( Bullet ( player_x, player_y, player_angle) ) # 空格键发射子弹screen. fill ( ( 255 , 255 , 255 ) ) # 清空屏幕c. tick ( 70 ) for h in range ( len ( q) ) : #画墙#print ( q[ h] , "行" , h) for g in range ( len ( q[ h] ) ) : if q[ h] [ g] == 1 : #print ( q[ h] [ g] , "个" , g, h) pz= pygame. draw. rect ( screen, ( 140 , 240 , 40 ) , ( 100 + h* 60 , 100 + g* 60 , 60 , 60 ) ) qsz. append ( pz) for bullet in bullets: bullet. update ( ) bullet. draw ( ) for i in ( bullets) : #画射线pygame. draw. line ( screen, ( 40 , 140 , 40 ) , ( player_x, player_y) , ( xiansz[ 0 ] ) ) p= pygame. math. Vector2 ( player_x, player_y) #角色位置p1= pygame. math. Vector2 ( xiansz[ 0 ] ) #碰撞点x,yjuli= p. distance_to ( p1) #计算距离,其实有距离后不用再画射线,后面画墙,画射线是为了理解pygame. display. flip ( )