invaders.py

Created by schraf

Created on May 03, 2025

1.79 KB

Explications en vidéo


from ion import *
from kandinsky import *
import time
import random

W, H = 320, 240
PLAYER_Y = 200
BULLET, ENEMY, PLAYER = '|', 'W', 'A'
BL, WH, RD = (0, 0, 0), (255, 255, 255), (255, 0, 0)

player_x = 150
enemies = [[random.randint(0, 30)*10, 20]]
bullets = []
score = 0

start_time = time.monotonic()
duration = 60

def draw_text(x, y, char): draw_string(char, x, y, WH, BL)

def clear(): fill_rect(0, 0, W, H, BL)

def update_enemies():
 for e in enemies:  e[1] += 2
 if random.random() < 0.05:
  enemies.append([random.randint(0, 30)*10, 20])

def update_bullets():
 global bullets
 for b in bullets:  b[1] -= 10
 bullets = [b for b in bullets if b[1] > 0]

def check_collisions():
 global enemies, bullets, score
 new_enemies = []
 for ex, ey in enemies:
  hit = False
  for b in bullets:
   if -2 <= b[0] + 6 - ex <= 12 and 0 <= b[1] - ey <= 18:
    hit = True
    bullets.remove(b)
    score += 1
    break
  if not hit and ey < 220: new_enemies.append([ex, ey])
 enemies = new_enemies

def draw(seconds_left):
 clear()
 draw_text(player_x, PLAYER_Y, PLAYER)
 for b in bullets: draw_text(b[0], b[1], BULLET)
 for e in enemies: draw_text(e[0], e[1], ENEMY)
 draw_text(5, 5, "Time: {}s".format(seconds_left))
 draw_text(5, 25, "Score: {}".format(score))

def game_over():
 clear()
 draw_string("GAME OVER", 100, 90, RD, BL)
 draw_string("Score : {}".format(score), 100, 110, RD, BL)
 while True: continue

while True:
 elapsed = int(time.monotonic() - start_time)
 seconds_left = duration - elapsed
 if seconds_left <= 0: game_over()
 if keydown(KEY_LEFT) and player_x >= 5: player_x -= 5
 elif keydown(KEY_RIGHT) and player_x <= W - 15: player_x += 5
 elif keydown(KEY_OK):
  bullets.append([player_x, PLAYER_Y - 10])

 update_enemies()
 update_bullets()
 check_collisions()
 draw(seconds_left)
 time.sleep(0.02)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.