<commit_before>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=python:et:sw=4:ts=4:sts=4

import mwclient
import os, oursql, sqlite3, re
import time
#from progressbar import ProgressBar, Percentage, Bar, ETA, SimpleProgress, Counter
from datetime import datetime
from mwtemplates import TemplateEditor
import logging
import logging.handlers
import argparse
import simplejson as json

from eximhandler import EximHandler

parser = argparse.ArgumentParser( description = 'CatMonitor' )
parser.add_argument('--silent', action='store_true', help='No output to console')
parser.add_argument('--verbose', action='store_true', help='Output debug messages')
parser.add_argument('--config', nargs='?', default='config.json', help='Config file')
args = parser.parse_args()

config = json.load(open(args.config, 'r'))

sql = sqlite3.connect(config['local_db'])
no = mwclient.Site(config['host'])
no.login(config['user'], config['pwd'])

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(asctime)s %(levelname)s] %(message)s')

exim_handler = EximHandler(config['mail']['to'], u"[tool labs] CatMonitor crashed!")
exim_handler.setLevel(logging.ERROR)
logger.addHandler(exim_handler)

console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)

file_handler = logging.handlers.RotatingFileHandler('catmonitor.log', maxBytes=100000, backupCount=3)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

if not args.silent:
    console_handler = logging.StreamHandler()
    if args.verbose:
        console_handler.setLevel(logging.DEBUG)
    else:
        console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)

def get_date_created(article):
    o = no.api('query', prop='revisions', rvlimit=1, rvdir='newer', titles=article)['query']['pages'].itervalues().next()
    if not 'revisions' in o:
        logger.error(u"Could not find first revision for article %s", article)
        return False

    ts = o['revisions'][0]['timestamp']
    #page = no.pages[article]
    #rev = page.revisions(limit=1, dir='newer').next()
    ts = datetime.strptime(ts, '%Y-%m-%dT%H:%M:%SZ')
    #ts = datetime.fromtimestamp(time.mktime(ts))
    return ts

def get_cached(catname):
    cur = sql.cursor()
    articles = []
    cur.execute(u'SELECT article FROM articles WHERE category=?', [catname])
    articles = [r[0] for r in cur.fetchall()]
    cur.close()
    return articles

def get_live(catname, exceptions):
    # The text in the DB is UTF-8, but identified as latin1, so we need to be careful
    db = oursql.connect(host=config['mysql']['host'], db=config['mysql']['db'], charset=None, use_unicode=False,
            read_default_file=os.path.expanduser('~/replica.my.cnf'))
    cur = db.cursor()

    #pbar = ProgressBar(maxval=config['maxcats'], widgets=['Categories: ', Counter()])
    #pbar.start()

    cats = [catname]
    articles = []
    for catname in cats:
        cur.execute('SELECT page.page_title, page.page_namespace, categorylinks.cl_type FROM categorylinks,page WHERE categorylinks.cl_to=? AND categorylinks.cl_from=page.page_id AND (page.page_namespace=0 OR page.page_namespace=1 OR page.page_namespace=14)', [catname.encode('utf-8')])
        for row in cur.fetchall():
            if row[2] == 'subcat':
                cat = row[0].decode('utf-8')
                if cat not in exceptions and cat not in cats:
                    cats.append(cat)
                    #print cat
            elif row[2] == 'page':
                pg = row[0].decode('utf-8')
                #if pg not in articles: expensive!
                articles.append(pg)
        if len(cats) > config['maxcats']:
            raise StandardError("Too many categories. We should probably add exclusions")
        #    pbar.maxval = len(cats)
        #pbar.update(len(cats))
    #pbar.maxval = len(cats)
    #pbar.finish()

    articles = list(set(articles))
    logger.info(" -> Found %d cats, %d articles", len(cats), len(articles))
    #logger.info("of which %d unique articles", len(articles))
    cur.close()
    db.close()
    return articles

def update_cache(cached, live):
    now = datetime.now().strftime('%F %T')

    cached_set = set(cached)
    live_set = set(live)

    added = list(live_set.difference(cached_set))
    removed = list(cached_set.difference(live_set))

    logger.info(" -> %d articles in cache, %d articles live", len(cached), len(live))
    logger.info(" -> %d articles added, %d articles removed", len(added), len(removed))

    cur = sql.cursor()
    for article in removed:
        cur.execute(u'DELETE FROM articles WHERE category=? AND article=?', [catname, article])

    for article in added:
        #created = get_date_created(article)
        #if created != False:
        cur.execute(u'INSERT INTO articles (category, article, date_added) VALUES (?,?,?)', [catname, article, now])

    sql.commit()
    cur.close()

def update_stats(catname):
    now = datetime.now().strftime('%F %T')

    cur = sql.cursor()
    cur.execute(u'SELECT COUNT(*) FROM articles WHERE category=?', [catname])
    membercount = cur.fetchall()[0][0]

    cur.execute(u'INSERT INTO stats (category, ts, membercount) VALUES (?,?,?)', [catname, now, membercount])
    sql.commit()
    cur.close()

def update(catname, exceptions):

    if type(catname) != unicode:
        raise StandardError("catname must be unicode object")

    logger.info("Making list for %s", catname)

    cached = get_cached(catname)
    live = get_live(catname, exceptions)
    update_cache(cached, live)
    update_stats(catname)

    #ntxt = '\n
[[:Kategori:%s|Kategori:%s]] inneholder %d artikler
' % (catname, catname, len(live))

    #mindate = cur.execute(u'SELECT MIN(date_added) FROM articles WHERE category=?', [catname]).fetchall()[0][0]
    #mindate = datetime.strptime(mindate, '%Y-%m-%d %H:%M:%S')
    #logger.info("Min date is %s", mindate)

    return len(live)

def makelist(catname, txt, maxitems, header, articlecount, date_tpl, separator):

    maxitems = int(maxitems)
    if maxitems <= 0:
        raise StandardError("maxitems: invalid value")

    tagstart = u''
    tagend = u''
    posstart = txt.find(tagstart)
    if posstart == -1:
        raise StandardError("Fant ikke tagstart")
    posstart += len(tagstart)
    posend = txt.find(tagend)
    if posend == -1:
        raise StandardError("Fant ikke tagend")

    ntxt = ''
    if header != '':
        ntxt = '\n' + header % { 'category': catname, 'articlecount': articlecount }
    cur = sql.cursor()
    cur.execute(u'SELECT article, date_created FROM articles WHERE category=? ORDER BY date_created DESC LIMIT %s' % maxitems, [catname])
    #cdate = ''
    buf = { 'dato': '', 'artikler': '' }
    for r in cur.fetchall():
        #if r[1] != mindate:
        #logger.info("article date is %s", r[1])
        d = datetime.strptime(r[1], '%Y-%m-%d %H:%M:%S')
        d = d.strftime('%d.%m')
        if d != buf['dato']:
            if buf['artikler'] != '':
                ntxt += '\n' + date_tpl % buf
            buf['dato'] = d
            buf['artikler'] = ''
        else:
            buf['artikler'] += separator
        buf['artikler'] += '[[%s]]' % r[0].replace('_', ' ')
    if buf['artikler'] != '':
        ntxt += '\n' + date_tpl % buf
    cur.close()

    ntxt += '\n'
    txt = txt[:posstart] + ntxt + txt[posend:]
    return txt

def total_seconds(td):
    # for backwards compability. td is a timedelta object
    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

runstart = datetime.now()
import platform
pv = platform.python_version()
logger.info('running Python %s' % (pv))
template = no.pages[config['template']]
try:

    for page in template.embeddedin():
        logger.info("Checking: %s", page.page_title)
        #if page.page_title != u'DanmicholoBot/Sandkasse2':
        #    continue
        txt = page.text()
        te = TemplateEditor(txt)
        template = te.templates[config['template']][0]

        if 'kategori' in template.parameters:
            catname = template.parameters['kategori'].value
        else:
            catname = template.parameters[1].value

        antall = 10
        if 'antall' in template.parameters:
            antall = template.parameters['antall'].value

        utelat = []
        if 'utelat' in template.parameters:
            utelat = [u.strip().replace(' ','_') for u in template.parameters['utelat'].value.split(',')]

        overskrift = '
[[:Kategori:%(category)s|Kategori:%(category)s]] inneholder %(articlecount)s artikler
'
        if 'overskrift' in template.parameters:
            overskrift = template.parameters['overskrift'].value

        dato_mal = '%(dato)s: %(artikler)s'
        if 'dato_mal' in template.parameters:
            dato_mal = template.parameters['dato_mal'].value

        sep = '{{,}} '
        if 'skille_mal' in template.parameters:
            sep = template.parameters['skille_mal'].value

        cat = no.categories[catname]
        if cat.exists:

            catname = catname.replace(' ', '_')

            articlecount = update(catname, exceptions = utelat)

            cur = sql.cursor()
            cur.execute(u'SELECT article FROM articles WHERE category=? AND date_created IS NULL', [catname])
            articles = [r[0] for r in cur.fetchall()]
            if len(articles) > 0:
                logger.info("Backfillling creation dates for %d articles (this may take a long while)", len(articles))
                for article in articles:
                    #logger.info(article)
                    try:
                        created = get_date_created(article)
                        if created:
                            cur.execute(u'UPDATE articles set date_created=? WHERE article=?', [created, article])
                            sql.commit()
                    except ValueError:
                        logger.error(u"Could not fetch date for %s", article)
            cur.close()
            txt = makelist(catname, txt, maxitems = antall, header=overskrift, articlecount=articlecount, date_tpl=dato_mal, separator=sep)
            page.save(txt, config['edit_summary'])

    runend = datetime.now()
    runtime = total_seconds(runend - runstart)
    logger.info('Complete, runtime was %.f seconds.' % (runtime))

except Exception, e:
    logger.exception(e)

<commit_msg>Use HTTPS and send identifying UA<commit_after>#!/usr/bin/env python
# -*- coding: utf-8; mode: python; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=python:et:sw=4:ts=4:sts=4

import mwclient
import os, oursql, sqlite3, re
import time
#from progressbar import ProgressBar, Percentage, Bar, ETA, SimpleProgress, Counter
from datetime import datetime
from mwtemplates import TemplateEditor
import logging
import logging.handlers
import argparse
import simplejson as json

from eximhandler import EximHandler

parser = argparse.ArgumentParser( description = 'CatMonitor' )
parser.add_argument('--silent', action='store_true', help='No output to console')
parser.add_argument('--verbose', action='store_true', help='Output debug messages')
parser.add_argument('--config', nargs='?', default='config.json', help='Config file')
args = parser.parse_args()

config = json.load(open(args.config, 'r'))

sql = sqlite3.connect(config['local_db'])
no = mwclient.Site(config['host'], clients_useragent='CatMonitor. Run by User:Danmichaelo. Based on mwclient/%s' % mwclient.__ver__)
no.login(config['user'], config['pwd'])

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(asctime)s %(levelname)s] %(message)s')

exim_handler = EximHandler(config['mail']['to'], u"[tool labs] CatMonitor crashed!")
exim_handler.setLevel(logging.ERROR)
logger.addHandler(exim_handler)

console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)

file_handler = logging.handlers.RotatingFileHandler('catmonitor.log', maxBytes=100000, backupCount=3)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

if not args.silent:
    console_handler = logging.StreamHandler()
    if args.verbose:
        console_handler.setLevel(logging.DEBUG)
    else:
        console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)

def get_date_created(article):
    o = no.api('query', prop='revisions', rvlimit=1, rvdir='newer', titles=article)['query']['pages'].itervalues().next()
    if not 'revisions' in o:
        logger.error(u"Could not find first revision for article %s", article)
        return False

    ts = o['revisions'][0]['timestamp']
    #page = no.pages[article]
    #rev = page.revisions(limit=1, dir='newer').next()
    ts = datetime.strptime(ts, '%Y-%m-%dT%H:%M:%SZ')
    #ts = datetime.fromtimestamp(time.mktime(ts))
    return ts

def get_cached(catname):
    cur = sql.cursor()
    articles = []
    cur.execute(u'SELECT article FROM articles WHERE category=?', [catname])
    articles = [r[0] for r in cur.fetchall()]
    cur.close()
    return articles

def get_live(catname, exceptions):
    # The text in the DB is UTF-8, but identified as latin1, so we need to be careful
    db = oursql.connect(host=config['mysql']['host'], db=config['mysql']['db'], charset=None, use_unicode=False,
            read_default_file=os.path.expanduser('~/replica.my.cnf'))
    cur = db.cursor()

    #pbar = ProgressBar(maxval=config['maxcats'], widgets=['Categories: ', Counter()])
    #pbar.start()

    cats = [catname]
    articles = []
    for catname in cats:
        cur.execute('SELECT page.page_title, page.page_namespace, categorylinks.cl_type FROM categorylinks,page WHERE categorylinks.cl_to=? AND categorylinks.cl_from=page.page_id AND (page.page_namespace=0 OR page.page_namespace=1 OR page.page_namespace=14)', [catname.encode('utf-8')])
        for row in cur.fetchall():
            if row[2] == 'subcat':
                cat = row[0].decode('utf-8')
                if cat not in exceptions and cat not in cats:
                    cats.append(cat)
                    #print cat
            elif row[2] == 'page':
                pg = row[0].decode('utf-8')
                #if pg not in articles: expensive!
                articles.append(pg)
        if len(cats) > config['maxcats']:
            raise StandardError("Too many categories. We should probably add exclusions")
        #    pbar.maxval = len(cats)
        #pbar.update(len(cats))
    #pbar.maxval = len(cats)
    #pbar.finish()

    articles = list(set(articles))
    logger.info(" -> Found %d cats, %d articles", len(cats), len(articles))
    #logger.info("of which %d unique articles", len(articles))
    cur.close()
    db.close()
    return articles

def update_cache(cached, live):
    now = datetime.now().strftime('%F %T')

    cached_set = set(cached)
    live_set = set(live)

    added = list(live_set.difference(cached_set))
    removed = list(cached_set.difference(live_set))

    logger.info(" -> %d articles in cache, %d articles live", len(cached), len(live))
    logger.info(" -> %d articles added, %d articles removed", len(added), len(removed))

    cur = sql.cursor()
    for article in removed:
        cur.execute(u'DELETE FROM articles WHERE category=? AND article=?', [catname, article])

    for article in added:
        #created = get_date_created(article)
        #if created != False:
        cur.execute(u'INSERT INTO articles (category, article, date_added) VALUES (?,?,?)', [catname, article, now])

    sql.commit()
    cur.close()

def update_stats(catname):
    now = datetime.now().strftime('%F %T')

    cur = sql.cursor()
    cur.execute(u'SELECT COUNT(*) FROM articles WHERE category=?', [catname])
    membercount = cur.fetchall()[0][0]

    cur.execute(u'INSERT INTO stats (category, ts, membercount) VALUES (?,?,?)', [catname, now, membercount])
    sql.commit()
    cur.close()

def update(catname, exceptions):

    if type(catname) != unicode:
        raise StandardError("catname must be unicode object")

    logger.info("Making list for %s", catname)

    cached = get_cached(catname)
    live = get_live(catname, exceptions)
    update_cache(cached, live)
    update_stats(catname)

    #ntxt = '\n
[[:Kategori:%s|Kategori:%s]] inneholder %d artikler
' % (catname, catname, len(live))

    #mindate = cur.execute(u'SELECT MIN(date_added) FROM articles WHERE category=?', [catname]).fetchall()[0][0]
    #mindate = datetime.strptime(mindate, '%Y-%m-%d %H:%M:%S')
    #logger.info("Min date is %s", mindate)

    return len(live)

def makelist(catname, txt, maxitems, header, articlecount, date_tpl, separator):

    maxitems = int(maxitems)
    if maxitems <= 0:
        raise StandardError("maxitems: invalid value")

    tagstart = u''
    tagend = u''
    posstart = txt.find(tagstart)
    if posstart == -1:
        raise StandardError("Fant ikke tagstart")
    posstart += len(tagstart)
    posend = txt.find(tagend)
    if posend == -1:
        raise StandardError("Fant ikke tagend")

    ntxt = ''
    if header != '':
        ntxt = '\n' + header % { 'category': catname, 'articlecount': articlecount }
    cur = sql.cursor()
    cur.execute(u'SELECT article, date_created FROM articles WHERE category=? ORDER BY date_created DESC LIMIT %s' % maxitems, [catname])
    #cdate = ''
    buf = { 'dato': '', 'artikler': '' }
    for r in cur.fetchall():
        #if r[1] != mindate:
        #logger.info("article date is %s", r[1])
        d = datetime.strptime(r[1], '%Y-%m-%d %H:%M:%S')
        d = d.strftime('%d.%m')
        if d != buf['dato']:
            if buf['artikler'] != '':
                ntxt += '\n' + date_tpl % buf
            buf['dato'] = d
            buf['artikler'] = ''
        else:
            buf['artikler'] += separator
        buf['artikler'] += '[[%s]]' % r[0].replace('_', ' ')
    if buf['artikler'] != '':
        ntxt += '\n' + date_tpl % buf
    cur.close()

    ntxt += '\n'
    txt = txt[:posstart] + ntxt + txt[posend:]
    return txt

def total_seconds(td):
    # for backwards compability. td is a timedelta object
    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

runstart = datetime.now()
import platform
pv = platform.python_version()
logger.info('running Python %s' % (pv))
template = no.pages[config['template']]
try:

    for page in template.embeddedin():
        logger.info("Checking: %s", page.page_title)
        #if page.page_title != u'DanmicholoBot/Sandkasse2':
        #    continue
        txt = page.text()
        te = TemplateEditor(txt)
        template = te.templates[config['template']][0]

        if 'kategori' in template.parameters:
            catname = template.parameters['kategori'].value
        else:
            catname = template.parameters[1].value

        antall = 10
        if 'antall' in template.parameters:
            antall = template.parameters['antall'].value

        utelat = []
        if 'utelat' in template.parameters:
            utelat = [u.strip().replace(' ','_') for u in template.parameters['utelat'].value.split(',')]

        overskrift = '
[[:Kategori:%(category)s|Kategori:%(category)s]] inneholder %(articlecount)s artikler
'
        if 'overskrift' in template.parameters:
            overskrift = template.parameters['overskrift'].value

        dato_mal = '%(dato)s: %(artikler)s'
        if 'dato_mal' in template.parameters:
            dato_mal = template.parameters['dato_mal'].value

        sep = '{{,}} '
        if 'skille_mal' in template.parameters:
            sep = template.parameters['skille_mal'].value

        cat = no.categories[catname]
        if cat.exists:

            catname = catname.replace(' ', '_')

            articlecount = update(catname, exceptions = utelat)

            cur = sql.cursor()
            cur.execute(u'SELECT article FROM articles WHERE category=? AND date_created IS NULL', [catname])
            articles = [r[0] for r in cur.fetchall()]
            if len(articles) > 0:
                logger.info("Backfillling creation dates for %d articles (this may take a long while)", len(articles))
                for article in articles:
                    #logger.info(article)
                    try:
                        created = get_date_created(article)
                        if created:
                            cur.execute(u'UPDATE articles set date_created=? WHERE article=?', [created, article])
                            sql.commit()
                    except ValueError:
                        logger.error(u"Could not fetch date for %s", article)
            cur.close()
            txt = makelist(catname, txt, maxitems = antall, header=overskrift, articlecount=articlecount, date_tpl=dato_mal, separator=sep)
            page.save(txt, config['edit_summary'])

    runend = datetime.now()
    runtime = total_seconds(runend - runstart)
    logger.info('Complete, runtime was %.f seconds.' % (runtime))

except Exception, e:
    logger.exception(e)

<|endoftext|>


<commit_before>import sys
import numpy as np
import code, traceback, signal

#=============================================================================
# Tiling utilities
#=============================================================================
def amin(a, b):
    return np.vstack([a, b]).min(axis=0)

def amax(a, b):
    return np.vstack([a, b]).max(axis=0)

class Tile(object):
    def __init__(self, left, right=None, mins=None, maxs=None):
        if right is None:
            right = left
            left = np.zeros(len(left), dtype='int')

        if not hasattr(left, '__iter__'):
            left = np.array([left]*3, dtype='int')

        if not hasattr(right, '__iter__'):
            right = np.array([right]*3, dtype='int')

        if mins is not None:
            if not hasattr(mins, '__iter__'):
                mins = np.array([mins]*3)
            left = amax(left, mins)

        if maxs is not None:
            if not hasattr(maxs, '__iter__'):
                maxs = np.array([maxs]*3)
            right = amin(right, maxs)

        l, r = left, right
        self.l = np.array(l)
        self.r = np.array(r)
        self.bounds = (l, r)
        self.shape = self.r - self.l
        self.slicer = np.s_[l[0]:r[0], l[1]:r[1], l[2]:r[2]]

def cdd(d, k):
    """ Conditionally delete key (or list of keys) 'k' from dict 'd' """
    if not isinstance(k, list):
        k = [k]
    for i in k:
        if d.has_key(i):
            d.pop(i)

#=============================================================================
# Progress bar
#=============================================================================
class ProgressBar(object):
    def __init__(self, num, label='Progress', value=0, screen=79,
            bar=True, bar_symbol='=', bar_caps='[]', bar_decimals=2):
        """
        ProgressBar class which creates a dynamic ASCII progress bar of two
        different varieties:
            1) A bar chart that looks like the following:
                Progress [================      ]  63.00%

            2) A simple number completed look:
                Progress :   17 / 289

        Parameters:
        -----------
        num : integer
            The number of tasks that need to be completed

        label : string [default: 'Progress']
            The label for this particular progress indicator,

        value : integer [default: 0]
            Starting value

        screen : integer [default: 79]
            Size the screen to use for the progress bar

        bar : boolean [default: True]
            Whether or not to display the bar chart

        bar_symbol : char [default: '=']
            The character to use to fill in the bar chart

        bar_caps : string [default: '[]']
            Characters to use as the end caps of the.  The string will be split in
            half and each half put on a side of the chart

        bar_decimals: integer [default: 2]
            Number of decimal places to include in the percentage
        """
        self.num = num
        self.value = value
        self.percent = 0

        self.label = label
        self.bar = bar
        self.bar_symbol = bar_symbol
        self.bar_caps = bar_caps
        self.bar_decimals = bar_decimals
        self.screen = screen

        if len(self.bar_caps) % 2 != 0:
            raise AttributeError("End caps must be even number of symbols")

        if self.bar:
            # 3 digit percent + decimal places + '.'
            self._num_size = 3 + self.bar_decimals + 1

            # end caps size calculation
            self._cap_len = len(self.bar_caps)/2
            self._cap_l = self.bar_caps[:self._cap_len]
            self._cap_r = self.bar_caps[self._cap_len:]

            # the space available for the progress bar is
            # 79 (screen) - (label) - (number) - 2 ([]) - 2 (space) - 1 (%)
            self._bar_size = (
                    self.screen - len(self.label) - self._num_size -
                    len(self.bar_caps) - 2 - 1
                )

            self.pdict = {
                "label": self.label,
                "bars": '',
                "barsize": self._bar_size,
                "numsize": self._num_size,
                "decs": self.bar_decimals,
                "capl": self._cap_l,
                "capr": self._cap_r,
                "percent": '',
            }
            self._formatstr = '\r{label} {capl}{bars:<{barsize}}{capr} {percent:>{numsize}.{decs}f}%'
        else:
            self._digits = str(int(np.ceil(np.log10(self.num))))
            self._formatstr = '\r{label} : {value:>{_digits}} / {num:>{_digits}}'

        self.update()

    def _draw(self):
        """ Interal draw method, simply prints to screen """
        if self.bar:
            self.pdict.update({"percent": self.percent, "bars": self.bar_symbol*self.bars})
            print self._formatstr.format(**self.pdict),
        else:
            print self._formatstr.format(**self.__dict__),
        sys.stdout.flush()

    def update(self, value=0):
        """
        Update the value of the progress and update progress bar.

        Parameters:
        -----------
        value : integer
            The current iteration of the progress
        """
        self.value = value
        self.percent = 100.0 * self.value / self.num

        if self.bar:
            self.bars = int(np.round(self.percent / 100. * self._bar_size))
        self._draw()

        if self.value == self.num:
            self.end()

    def end(self):
        print '\r{lett:>{screen}}'.format(**{'lett':'', 'screen': self.screen})

#=============================================================================
# debugging / python interpreter / logging
#=============================================================================
def debug(sig, frame):
    """Interrupt running process, and provide a python prompt for
    interactive debugging."""
    d={'_frame':frame}         # Allow access to frame object.
    d.update(frame.f_globals)  # Unless shadowed by global
    d.update(frame.f_locals)

    i = code.InteractiveConsole(d)
    message  = "Signal received : entering python shell.\nTraceback:\n"
    message += ''.join(traceback.format_stack(frame))
    i.interact(message)

def listen():
    # register handler
    signal.signal(signal.SIGUSR1, debug)
<commit_msg>estimated time remaining for progress bar<commit_after>import sys
import time
import datetime
import numpy as np
import code, traceback, signal

#=============================================================================
# Tiling utilities
#=============================================================================
def amin(a, b):
    return np.vstack([a, b]).min(axis=0)

def amax(a, b):
    return np.vstack([a, b]).max(axis=0)

class Tile(object):
    def __init__(self, left, right=None, mins=None, maxs=None):
        if right is None:
            right = left
            left = np.zeros(len(left), dtype='int')

        if not hasattr(left, '__iter__'):
            left = np.array([left]*3, dtype='int')

        if not hasattr(right, '__iter__'):
            right = np.array([right]*3, dtype='int')

        if mins is not None:
            if not hasattr(mins, '__iter__'):
                mins = np.array([mins]*3)
            left = amax(left, mins)

        if maxs is not None:
            if not hasattr(maxs, '__iter__'):
                maxs = np.array([maxs]*3)
            right = amin(right, maxs)

        l, r = left, right
        self.l = np.array(l)
        self.r = np.array(r)
        self.bounds = (l, r)
        self.shape = self.r - self.l
        self.slicer = np.s_[l[0]:r[0], l[1]:r[1], l[2]:r[2]]

def cdd(d, k):
    """ Conditionally delete key (or list of keys) 'k' from dict 'd' """
    if not isinstance(k, list):
        k = [k]
    for i in k:
        if d.has_key(i):
            d.pop(i)

#=============================================================================
# Progress bar
#=============================================================================
class ProgressBar(object):
    def __init__(self, num, label='Progress', value=0, screen=79,
            time_remaining=True, bar=True, bar_symbol='=', bar_caps='[]',
            bar_decimals=2):
        """
        ProgressBar class which creates a dynamic ASCII progress bar of two
        different varieties:
            1) A bar chart that looks like the following:
                Progress [================      ]  63.00%

            2) A simple number completed look:
                Progress :   17 / 289

        Parameters:
        -----------
        num : integer
            The number of tasks that need to be completed

        label : string [default: 'Progress']
            The label for this particular progress indicator,

        value : integer [default: 0]
            Starting value

        screen : integer [default: 79]
            Size the screen to use for the progress bar

        time_remaining : boolean [default: True]
            Display estimated time remaining

        bar : boolean [default: True]
            Whether or not to display the bar chart

        bar_symbol : char [default: '=']
            The character to use to fill in the bar chart

        bar_caps : string [default: '[]']
            Characters to use as the end caps of the.  The string will be split in
            half and each half put on a side of the chart

        bar_decimals: integer [default: 2]
            Number of decimal places to include in the _percentage
        """
        # TODO -- add estimated time remaining
        self.num = num
        self.value = value
        self._percent = 0
        self.time_remaining = time_remaining
        self._deltas = []

        self.label = label
        self.bar = bar
        self._bar_symbol = bar_symbol
        self._bar_caps = bar_caps
        self._decimals = bar_decimals
        self.screen = screen

        if len(self._bar_caps) % 2 != 0:
            raise AttributeError("End caps must be even number of symbols")

        if self.bar:
            # 3 digit _percent + decimal places + '.'
            self._numsize = 3 + self._decimals + 1

            # end caps size calculation
            self._cap_len = len(self._bar_caps)/2
            self._capl = self._bar_caps[:self._cap_len]
            self._capr = self._bar_caps[self._cap_len:]

            # time remaining calculation for space
            self._time_space = 11 if self.time_remaining else 0

            # the space available for the progress bar is
            # 79 (screen) - (label) - (number) - 2 ([]) - 2 (space) - 1 (%)
            self._barsize = (
                    self.screen - len(self.label) - self._numsize -
                    len(self._bar_caps) - 2 - 1 - self._time_space
                )

            self._formatstr = '\r{label} {_capl}{_bars:<{_barsize}}{_capr} {_percent:>{_numsize}.{_decimals}f}%'

            self._percent = 0
            self._dt = '--:--:--'
            self._bars = ''

            if self.time_remaining:
                self._formatstr += " ({_dt})"
        else:
            self._digits = str(int(np.ceil(np.log10(self.num))))
            self._formatstr = '\r{label} : {value:>{_digits}} / {num:>{_digits}} ({_dt})'

            self._dt = '--:--:--'
            if self.time_remaining:
                self._formatstr += " ({_dt})"

        self.update()

    def _estimate_time(self):
        if len(self._deltas) < 3:
            self._dt = '--:--:--'
        else:
            dt = np.diff(self._deltas[-5:]).mean() * (self.num - self.value)
            self._dt = time.strftime('%H:%M:%S', time.gmtime(dt))

    def _draw(self):
        """ Interal draw method, simply prints to screen """
        print self._formatstr.format(**self.__dict__),
        sys.stdout.flush()

    def update(self, value=0):
        """
        Update the value of the progress and update progress bar.

        Parameters:
        -----------
        value : integer
            The current iteration of the progress
        """
        self._deltas.append(time.time())

        self.value = value
        self._percent = 100.0 * self.value / self.num
        self._bars = self._bar_symbol*int(np.round(self._percent / 100. * self._barsize))

        self._estimate_time()
        self._draw()

        if self.value == self.num:
            self.end()

    def end(self):
        print '\r{lett:>{screen}}'.format(**{'lett':'', 'screen': self.screen})

#=============================================================================
# debugging / python interpreter / logging
#=============================================================================
def debug(sig, frame):
    """Interrupt running process, and provide a python prompt for
    interactive debugging."""
    d={'_frame':frame}         # Allow access to frame object.
    d.update(frame.f_globals)  # Unless shadowed by global
    d.update(frame.f_locals)

    i = code.InteractiveConsole(d)
    message  = "Signal received : entering python shell.\nTraceback:\n"
    message += ''.join(traceback.format_stack(frame))
    i.interact(message)

def listen():
    # register handler
    signal.signal(signal.SIGUSR1, debug)
<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: Suhan Gui
Credit: Spacewar
Assignment: Spaceshooter
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, Sprite, ImageAsset, Frame
from ggame import TextAsset, Color
import math
from time import time

class Move(Sprite):
    image=ImageAsset("images/four_spaceship_by_albertov_with_thrust.png", Frame(100,0,225,125), 4,'vertical')
    def __init__(self, position):
        super().__init__(Move.asset, position)

class Ship(Sprite):
    image=ImageAsset("images/four_spaceship_by_albertov.png", Frame(100,0,225,125), 4, 'vertical')
    def __init__(self, position):
        super().__init__(Ship.asset, position)
        self.vx=0
        self.vy=0
        self.vr=0
        self.trust=0
        self.trustframe=0
        SpaceGame.listenKeyEvent("keydown", self.thrustOff)
        SpaceGame.listenKeyEvent("keyup", self.thrustOn)
        self.fxcenter = self.fycenter = 0.5

class Sun(Sprite):
    image=ImageAsset("images/sun.png", Frame(100,0,100,100), 1, 'vertical')
    def __init__(self, position):
        super().__init__(Sun.asset, position)

class Galaxy(Sprite):
    image=ImageAsset("images/starfield.jpg", Frame(600,0,1000,125), 4, 'vertical')
    def __init__(self, position):
        super().__init__(Galaxy.asset, position)

class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
    for x in range(self.width//Galaxy.width + 1):
        for y in range(self.height//Galaxy.height + 1):
            Stars((x*Galaxy.width, y*Galaxy.height))
    self.sun = Sun((self.width/2, self.height/2))
    self.ship1 = Ship1(self, (self.width/2-140,self.height/2), (0,-140), self.sun)
    self.ship2 = Ship2(self, (self.width/2+140,self.height/2), (0,140), self.sun)
    self.style = {k:Sprite(TextAsset(text=v, width=200, center='center',style='20px Arial', fill=Color(0,1)))

#Fin
myapp = SpaceGame(0,0)
myapp.run<commit_msg>Updated from Brython Server: 10/26/2015 2:52:51 PM<commit_after>"""
spaceshooter.py
Author: Suhan Gui
Credit: Spacewar
Assignment: Spaceshooter
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, Sprite, ImageAsset, Frame
from ggame import TextAsset, Color
import math
from time import time

class Move(Sprite):
    image=ImageAsset("images/four_spaceship_by_albertov_with_thrust.png", Frame(100,0,225,125), 4,'vertical')
    def __init__(self, position):
        super().__init__(Move.asset, position)

class Ship(Sprite):
    image=ImageAsset("images/four_spaceship_by_albertov.png", Frame(100,0,225,125), 4, 'vertical')
    def __init__(self, position):
        super().__init__(Ship.asset, position)
        self.vx=0
        self.vy=0
        self.vr=0
        self.trust=0
        self.trustframe=0
        SpaceGame.listenKeyEvent("keydown", self.thrustOff)
        SpaceGame.listenKeyEvent("keyup", self.thrustOn)
        self.fxcenter = self.fycenter = 0.5

class Sun(Sprite):
    image=ImageAsset("images/sun.png", Frame(100,0,100,100), 1, 'vertical')
    def __init__(self, position):
        super().__init__(Sun.asset, position)

class Galaxy(Sprite):
    image=ImageAsset("images/starfield.jpg", Frame(600,0,1000,125), 4, 'vertical')
    def __init__(self, position):
        super().__init__(Galaxy.asset, position)

class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)

#Fin
myapp = SpaceGame(0,0)
myapp.run<|endoftext|>


<commit_before>"""
Space game
Ryan Kynor

Checklist:
fixed star field
~~Sun sprite~~
at least one player
muliple players or multplie inanimate objects to avoid
animated rocket thrust
collisions destroy ship
moving ships
rotating ships

Source:
lines 23 - 27 based off of orininal space game code
"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class Sun(Sprite):
    """
    The Sun on the Screen
    """

    asset =  ImageAsset("images/sun.png")
    height = 80
    width = 80

    def __init__(self, position):
        super().__init__(Sun.asset, position)
        self.weight = 1
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class Star(Sprite):
    """
    The Star
    """

    asset = ImageAsset("images/starfield.png")

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 1
        self.vy = 1
        self.vr = 0.01
        self.thrust = 0
        self.thrustframe = 1
        #Thrust animation
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        #Rotation animation
        SpaceGame.listenKeyEvent("keydown",
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = RectangleAsset(width, height, noline, black)
        bg = Sprite(bg_asset, (0,0))
        Sun((SCREEN_WIDTH/2,SCREEN_HEIGHT/2))
        Star
        SpaceShip((100,100))
        #SpaceShip((150,150))
        #SpaceShip((200,50))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

#Sun((SCREEN_WIDTH/2,SCREEN_HEIGHT/2))

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()

#self rotation will give you the current angle of rotation in radians<commit_msg>Updated from Brython Server: 11/30/2015 2:32:35 PM<commit_after>"""
Space game
Ryan Kynor

Checklist:
fixed star field
~~Sun sprite~~
at least one player
muliple players or multplie inanimate objects to avoid
animated rocket thrust
collisions destroy ship
moving ships
rotating ships

Source:
lines 23 - 27 based off of orininal space game code
"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class Sun(Sprite):
    """
    The Sun on the Screen
    """

    asset =  ImageAsset("images/sun.png")
    height = 80
    width = 80

    def __init__(self, position):
        super().__init__(Sun.asset, position)
        self.weight = 1
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class Star(Sprite):
    """
    The Star
    """

    asset = ImageAsset("images/starfield.png")
    height = SCREEN_HEIGHT
    width = SCREEN_WIDTH

    def __init__(self,position):
        super().__init__(Sun.asset, position)
        self.weight = 0
        self.fxcenter = 1
        self.fycenter = 1

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 1
        self.vy = 1
        self.vr = 0.01
        self.thrust = 0
        self.thrustframe = 1
        #Thrust animation
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        #Rotation animation
        SpaceGame.listenKeyEvent("keydown",
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = RectangleAsset(width, height, noline, black)
        bg = Sprite(bg_asset, (0,0))
        Starfield((SCREEN_WIDTH,SCREEN_HEIGHT))
        Sun((SCREEN_WIDTH/2,SCREEN_HEIGHT/2))
        Star
        SpaceShip((100,100))
        #SpaceShip((150,150))
        #SpaceShip((200,50))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

#Sun((SCREEN_WIDTH/2,SCREEN_HEIGHT/2))

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()

#self rotation will give you the current angle of rotation in radians<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: Jeff
Credit: Space Game tutorial

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, RectangleAsset, ImageAsset, SoundAsset, Sprite, LineStyle, Color, Frame
import math
SCREEN_WIDTH = 1536
SCREEN_HEIGHT = 1024

class Ship1(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(Ship1.asset, position)
        self.vr = 0.00
        self.thrust = 0
        self.thrustframe = 1
        self.VX = 0
        self.VY = 0
        self.vx = 0
        self.vy = 0
        self.turn = 0
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.rotateLeft)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.lrOff)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.rotateRight)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.rrOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.rotation += 1.5*self.vr
        if self.thrust == 1:
            self.VX += self.vx
            self.VY += self.vy
        if 0 <= self.x <= SCREEN_WIDTH:
            self.x -= 0.1*self.VX
        elif self.x < 0:
            self.x += SCREEN_WIDTH
            self.x -= 0.1*self.VX
        else:
            self.x -= (0.1*self.VX + SCREEN_WIDTH)
        if 0 <= self.y <= SCREEN_HEIGHT:
            self.y -= 0.1*self.VY
        elif self.y < 0:
            self.y += SCREEN_HEIGHT
            self.y -= 0.1*self.VY
        else:
            self.y -= (0.1*self.VY + SCREEN_HEIGHT)

        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
            self.move()
        else:
            self.setImage(0)

    def move(self):
        self.X = math.sin(self.rotation)
        self.Y = math.cos(self.rotation)
        self.vx = self.X/math.sqrt(self.X*self.X + self.Y*self.Y)
        self.vy = self.Y/math.sqrt(self.X*self.X + self.Y*self.Y)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def rotateLeft(self, event):
        self.vr = 0.05

    def lrOff(self,  event):
        self.vr = 0

    def rotateRight(self, event):
        self.vr = -0.05

    def rrOff(self,  event):
        self.vr = 0

class Ship2(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(0,0,86,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(Ship2.asset, position)
        self.vr = 0.00
        self.thrust = 0
        self.thrustframe = 1
        self.VX = 0
        self.VY = 0
        self.vx = 0
        self.vy = 0
        self.turn = 0
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "a", self.rotateLeft)
        SpaceGame.listenKeyEvent("keyup", "a", self.lrOff)
        SpaceGame.listenKeyEvent("keydown", "d", self.rotateRight)
        SpaceGame.listenKeyEvent("keyup", "d", self.rrOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.rotation += 1.5*self.vr
        if self.thrust == 1:
            self.VX += self.vx
            self.VY += self.vy
        if 0 <= self.x <= SCREEN_WIDTH:
            self.x -= 0.1*self.VX
        elif self.x < 0:
            self.x += SCREEN_WIDTH
            self.x -= 0.1*self.VX
        else:
            self.x -= (0.1*self.VX + SCREEN_WIDTH)
        if 0 <= self.y <= SCREEN_HEIGHT:
            self.y -= 0.1*self.VY
        elif self.y < 0:
            self.y += SCREEN_HEIGHT
            self.y -= 0.1*self.VY
        else:
            self.y -= (0.1*self.VY + SCREEN_HEIGHT)

        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
            self.move()
        else:
            self.setImage(0)

    def move(self):
        self.X = math.sin(self.rotation)
        self.Y = math.cos(self.rotation)
        self.vx = self.X/math.sqrt(self.X*self.X + self.Y*self.Y)
        self.vy = self.Y/math.sqrt(self.X*self.X + self.Y*self.Y)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def rotateLeft(self, event):
        self.vr = 0.05

    def lrOff(self,  event):
        self.vr = 0

    def rotateRight(self, event):
        self.vr = -0.05

    def rrOff(self,  event):
        self.vr = 0

class Bullet(Sprite):

    asset1 = ImageAsset("images/blast.png", Frame(0,0,8,8), 8)
    pewasset = SoundAsset("sounds/pew1.mp3")

    def __init__(self, position):
        super().__init__(Bullet.asset1, position)
        SpaceGame.listenKeyEvent("keydown", "space", self.shoot)
        self.exist = False
        self.circularCollisionModel()
        self.pew = Sound(Bullet.pewasset)
        self.pew.volume = 10

    def step(self):
        if self.exist == 1:
            self.setImage(self.appear)
            self.appear += 1
            if self.appear == 8:
                self.appear = 1
            self.move()
        else:
            self.setImage(0)

    def shoot(self, position, velocity):
        Bullet((200,200))
        self.exist = True

class HealthBar:

    def __init__(self, indicatorasset, initvalue, position, app):
        self.sprites = [Sprite(indicatorasset, (0,app.height-75)) for i in range(initvalue)]
        for s in self.sprites:
            s.scale = 0.4
        width = self.sprites[0].width
        if position == 'left':
            x = 50
            step = width+5
        else:
            x = app.width - 50 - width
            step = -width-5
        for s in self.sprites:
            s.x = x
            x += step
        self.restart()

    def restart(self):
        for s in self.sprites:
            s.visible = True
        self.count = len(self.sprites)

    def dead(self):
        return self.count == 0

    def killone(self):
        if self.count > 0:
            self.count -= 1
            self.sprites[self.count].visible = False

class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        bg = Sprite(bg_asset, (0,0))
        bg1 = Sprite(bg_asset, (512,512))
        bg2 = Sprite(bg_asset, (0,512))
        bg3 = Sprite(bg_asset, (512,0))
        bg4 = Sprite(bg_asset, (1024,512))
        bg5 = Sprite(bg_asset, (1024,0))

        Ship1((250,250))
        Ship2((300,300))

    def step(self):
        for ship in self.getSpritesbyClass(Ship1):
            ship.step()
        for ship in self.getSpritesbyClass(Ship2):
            ship.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()
<commit_msg>Updated from Brython Server: October 27, 2015 2:50:41 PM EDT<commit_after>"""
spaceshooter.py
Author: Jeff
Credit: Space Game tutorial

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, RectangleAsset, ImageAsset, SoundAsset, Sprite, LineStyle, Color, Frame
import math
SCREEN_WIDTH = 1536
SCREEN_HEIGHT = 1024

class Ship1(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(Ship1.asset, position)
        self.vr = 0.00
        self.thrust = 0
        self.thrustframe = 1
        self.VX = 0
        self.VY = 0
        self.vx = 0
        self.vy = 0
        self.turn = 0
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.rotateLeft)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.lrOff)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.rotateRight)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.rrOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.rotation += 1.5*self.vr
        if self.thrust == 1:
            self.VX += self.vx
            self.VY += self.vy
        if 0 <= self.x <= SCREEN_WIDTH:
            self.x -= 0.1*self.VX
        elif self.x < 0:
            self.x += SCREEN_WIDTH
            self.x -= 0.1*self.VX
        else:
            self.x -= (0.1*self.VX + SCREEN_WIDTH)
        if 0 <= self.y <= SCREEN_HEIGHT:
            self.y -= 0.1*self.VY
        elif self.y < 0:
            self.y += SCREEN_HEIGHT
            self.y -= 0.1*self.VY
        else:
            self.y -= (0.1*self.VY + SCREEN_HEIGHT)

        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
            self.move()
        else:
            self.setImage(0)

    def move(self):
        self.X = math.sin(self.rotation)
        self.Y = math.cos(self.rotation)
        self.vx = self.X/math.sqrt(self.X*self.X + self.Y*self.Y)
        self.vy = self.Y/math.sqrt(self.X*self.X + self.Y*self.Y)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def rotateLeft(self, event):
        self.vr = 0.05

    def lrOff(self,  event):
        self.vr = 0

    def rotateRight(self, event):
        self.vr = -0.05

    def rrOff(self,  event):
        self.vr = 0

class Ship2(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(0,0,86,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(Ship2.asset, position)
        self.vr = 0.00
        self.thrust = 0
        self.thrustframe = 1
        self.VX = 0
        self.VY = 0
        self.vx = 0
        self.vy = 0
        self.turn = 0
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "a", self.rotateLeft)
        SpaceGame.listenKeyEvent("keyup", "a", self.lrOff)
        SpaceGame.listenKeyEvent("keydown", "d", self.rotateRight)
        SpaceGame.listenKeyEvent("keyup", "d", self.rrOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.rotation += 1.5*self.vr
        if self.thrust == 1:
            self.VX += self.vx
            self.VY += self.vy
        if 0 <= self.x <= SCREEN_WIDTH:
            self.x -= 0.1*self.VX
        elif self.x < 0:
            self.x += SCREEN_WIDTH
            self.x -= 0.1*self.VX
        else:
            self.x -= (0.1*self.VX + SCREEN_WIDTH)
        if 0 <= self.y <= SCREEN_HEIGHT:
            self.y -= 0.1*self.VY
        elif self.y < 0:
            self.y += SCREEN_HEIGHT
            self.y -= 0.1*self.VY
        else:
            self.y -= (0.1*self.VY + SCREEN_HEIGHT)

        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
            self.move()
        else:
            self.setImage(0)

    def move(self):
        self.X = math.sin(self.rotation)
        self.Y = math.cos(self.rotation)
        self.vx = self.X/math.sqrt(self.X*self.X + self.Y*self.Y)
        self.vy = self.Y/math.sqrt(self.X*self.X + self.Y*self.Y)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def rotateLeft(self, event):
        self.vr = 0.05

    def lrOff(self,  event):
        self.vr = 0

    def rotateRight(self, event):
        self.vr = -0.05

    def rrOff(self,  event):
        self.vr = 0

class Bullet(Sprite):

    asset1 = ImageAsset("images/blast.png", Frame(0,0,8,8), 8)
    pewasset = SoundAsset("sounds/pew1.mp3")

    def __init__(self, position):
        super().__init__(Bullet.asset1, position)
        SpaceGame.listenKeyEvent("keydown", "space", self.shoot)
        self.exist = False
        self.circularCollisionModel()
        self.pew = Sound(Bullet.pewasset)
        self.pew.volume = 10

    def step(self):
        if self.exist == 1:
            self.setImage(self.appear)
            self.appear += 1
            if self.appear == 8:
                self.appear = 1
            self.move()
        else:
            self.setImage(0)

    def shoot(self, position, velocity):
        Bullet((200,200))
        self.exist = True

class HealthBar:

    def __init__(self, indicatorasset, initvalue, position, app):
        self.sprites = [Sprite(indicatorasset, (0,app.height-75)) for i in range(initvalue)]
        for s in self.sprites:
            s.scale = 0.4
        width = self.sprites[0].width
        if position == 'left':
            x = 50
            step = width+5
        else:
            x = app.width - 50 - width
            step = -width-5
        for s in self.sprites:
            s.x = x
            x += step
        self.restart()

    def restart(self):
        for s in self.sprites:
            s.visible = True
        self.count = len(self.sprites)

    def dead(self):
        return self.count == 0

    def killone(self):
        if self.count > 0:
            self.count -= 1
            self.sprites[self.count].visible = False

class ExplosionSmall(Sprite):

    asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10)
    boomasset = SoundAsset("sounds/explosion1.mp3")

    def __init__(self, position):
        super().__init__(ExplosionSmall.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.boom = Sound(ExplosionSmall.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image += 1
        if self.image == 20:
            self.destroy()

class ExplosionBig(Sprite):

    asset = ImageAsset("images/explosion2.png", Frame(0,0,4800/25,195), 25)
    boomasset = SoundAsset("sounds/explosion2.mp3")

    def __init__(self, position):
        super().__init__(ExplosionBig.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.boom = Sound(ExplosionBig.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image += 1
        if self.image == 50:
            self.destroy()

class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        bg = Sprite(bg_asset, (0,0))
        bg1 = Sprite(bg_asset, (512,512))
        bg2 = Sprite(bg_asset, (0,512))
        bg3 = Sprite(bg_asset, (512,0))
        bg4 = Sprite(bg_asset, (1024,512))
        bg5 = Sprite(bg_asset, (1024,0))

        Ship1((250,250))
        Ship2((300,300))

    def step(self):
        for ship in self.getSpritesbyClass(Ship1):
            ship.step()
        for ship in self.getSpritesbyClass(Ship2):
            ship.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()
<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: Avery Wallis
Credit: Original Spacewar Code, Daniel, Payton, Ethan

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, ImageAsset, RectangleAsset, SoundAsset, Frame
from ggame import LineStyle, Sprite, Sound, Color, TextAsset
import math

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

'''
class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.visible=True
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.rotation = 0
        self.thrust = 0
        self.reset = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "a" , self.CCOn)
        SpaceGame.listenKeyEvent("keyup", "a", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "d" , self.CCthing)
        SpaceGame.listenKeyEvent("keyup", "d", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "r", self.restartOn)
        SpaceGame.listenKeyEvent("keyup", "r", self.restartOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.vx += .05*math.cos((self.rotation+math.pi/2))
            self.vy += .05*math.sin((self.rotation-math.pi/2))
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.vr == .1:
            self.rotation += .0001
        if self.vr == -.1:
            self.rotation -= .0001
        if self.vr==0:
            self.rotation=self.rotation

        col= self.collidingWithSprites(Sunthing,Spaceship2)
        if col:
            self.explode()

        if self.reset == 1:
            self.visible = True
            self.x = 300
            self.y = 300
            self.rotation = 0
            self.vx = 0
            self.vy = 0

    def thrustOn(self, event):
        self.thrust = 1
    def thrustOff(self, event):
        self.thrust = 0
    def thrustDecel(self, event):
        self.thrust=-1

    def CCOn(self, event):
        self.vr=.1
    def CCOff(self, event):
        self.vr=0
    def CCthing(self, event):
        self.vr=-.1

    def restartOn(self,event):
        self.reset = 1

    def restartOff(self, event):
        self.reset = 0

    def explode(self):
        self.visible = False
        self.vx = 0
        self.vy = 0
        ExplosionSmall(self.position)
'''
class SpaceShip2(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(0,0,86,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip2.asset, position)
        self.visible=True
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.rotation = 0
        self.thrust = 0
        self.reset = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "left arrow" , self.CCOn)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "right arrow" , self.CCthing)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "p", self.restartOn)
        SpaceGame.listenKeyEvent("keyup", "p", self.restartOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.vx += .05*math.cos((self.rotation+math.pi/2))
            self.vy += .05*math.sin((self.rotation-math.pi/2))
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.vr == .1:
            self.rotation += .0001
        if self.vr == -.1:
            self.rotation -= .0001
        if self.vr==0:
            self.rotation=self.rotation

        col= self.collidingWithSprites(None)
        if col:
            self.explode()

        if self.reset == 1:
            self.visible = True
            self.x = 700
            self.y = 500
            self.rotation = 0
            self.vx = 0
            self.vy = 0

    def thrustOn(self, event):
        self.thrust = 1
    def thrustOff(self, event):
        self.thrust = 0
    def thrustDecel(self, event):
        self.thrust=-1

    def CCOn(self, event):
        self.vr=.1
    def CCOff(self, event):
        self.vr=0
    def CCthing(self, event):
        self.vr=-.1

    def restartOn(self,event):
        self.reset = 1

    def restartOff(self, event):
        self.reset = 0

    def explode(self):
        self.visible = False
        self.vx = 0
        self.vy = 0
        ExplosionSmall(self.position)

class ExplosionSmall(Sprite):

    asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10)
    boomasset = SoundAsset("sounds/explosion1.mp3")

    def __init__(self, position):
        super().__init__(ExplosionSmall.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.vx = 0
        self.vy = 0
        self.boom = Sound(ExplosionSmall.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//5)  # slow it down
        self.image += 1
        self.boom.play()
        if self.image == 45:
            self.visible = False
            self.destroy()

class Sunthing(Sprite):
    asset=ImageAsset("images/sun.png")
    width=80
    length=76
    def __init__(self, position):
        super().__init__(Sunthing.asset, position)
        self.mass = 30*1000
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        txt_asset= TextAsset(text="Press R to Reset", width=200, align='center',style='20px Arial', fill=Color(0xff2222,1))
        star0 = Sprite(bg_asset, (0,0))
        star1= Sprite(bg_asset, (512,0))
        star2= Sprite(bg_asset, (0,512))
        star3= Sprite(bg_asset, (512, 512))
        txt = Sprite(txt_asset, (0,0))
        Sunthing((500,360))
        '''
        SpaceShip((300,300))
        '''
        SpaceShip2((500,500))

    def step(self):
        '''
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()
        '''
        for ship in self.getSpritesbyClass(SpaceShip2):
            ship.step()

        explosions = self.getSpritesbyClass(ExplosionSmall)
        for explosion in explosions:
            explosion.step()

myapp = SpaceGame(SCREEN_WIDTH*1.5, SCREEN_HEIGHT*1.5)
myapp.run()
<commit_msg>Updated from Brython Server: 3/29/2016 2:47:11 PM<commit_after>"""
spaceshooter.py
Author: Avery Wallis
Credit: Original Spacewar Code, Daniel, Payton, Ethan

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, ImageAsset, RectangleAsset, SoundAsset, Frame
from ggame import LineStyle, Sprite, Sound, Color, TextAsset
import math

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

'''
class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.visible=True
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.rotation = 0
        self.thrust = 0
        self.reset = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "a" , self.CCOn)
        SpaceGame.listenKeyEvent("keyup", "a", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "d" , self.CCthing)
        SpaceGame.listenKeyEvent("keyup", "d", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "r", self.restartOn)
        SpaceGame.listenKeyEvent("keyup", "r", self.restartOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.vx += .05*math.cos((self.rotation+math.pi/2))
            self.vy += .05*math.sin((self.rotation-math.pi/2))
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.vr == .1:
            self.rotation += .0001
        if self.vr == -.1:
            self.rotation -= .0001
        if self.vr==0:
            self.rotation=self.rotation

        col= self.collidingWithSprites(Sunthing,Spaceship2)
        if col:
            self.explode()

        if self.reset == 1:
            self.visible = True
            self.x = 300
            self.y = 300
            self.rotation = 0
            self.vx = 0
            self.vy = 0

    def thrustOn(self, event):
        self.thrust = 1
    def thrustOff(self, event):
        self.thrust = 0
    def thrustDecel(self, event):
        self.thrust=-1

    def CCOn(self, event):
        self.vr=.1
    def CCOff(self, event):
        self.vr=0
    def CCthing(self, event):
        self.vr=-.1

    def restartOn(self,event):
        self.reset = 1

    def restartOff(self, event):
        self.reset = 0

    def explode(self):
        self.visible = False
        self.vx = 0
        self.vy = 0
        ExplosionSmall(self.position)
'''
class SpaceShip2(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(0,0,86,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip2.asset, position)
        self.visible=True
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.rotation = 0
        self.thrust = 0
        self.reset = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "left arrow" , self.CCOn)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "right arrow" , self.CCthing)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "p", self.restartOn)
        SpaceGame.listenKeyEvent("keyup", "p", self.restartOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.vx += .05*math.cos((self.rotation+math.pi/2))
            self.vy += .05*math.sin((self.rotation-math.pi/2))
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.vr == .1:
            self.rotation += .0001
        if self.vr == -.1:
            self.rotation -= .0001
        if self.vr==0:
            self.rotation=self.rotation

        col= self.collidingWithSprites(Spaceship)
        if col:
            self.explode()

        if self.reset == 1:
            self.visible = True
            self.x = 700
            self.y = 500
            self.rotation = 0
            self.vx = 0
            self.vy = 0

    def thrustOn(self, event):
        self.thrust = 1
    def thrustOff(self, event):
        self.thrust = 0
    def thrustDecel(self, event):
        self.thrust=-1

    def CCOn(self, event):
        self.vr=.1
    def CCOff(self, event):
        self.vr=0
    def CCthing(self, event):
        self.vr=-.1

    def restartOn(self,event):
        self.reset = 1

    def restartOff(self, event):
        self.reset = 0

    def explode(self):
        self.visible = False
        self.vx = 0
        self.vy = 0
        ExplosionSmall(self.position)

class ExplosionSmall(Sprite):

    asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10)
    boomasset = SoundAsset("sounds/explosion1.mp3")

    def __init__(self, position):
        super().__init__(ExplosionSmall.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.vx = 0
        self.vy = 0
        self.boom = Sound(ExplosionSmall.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//5)  # slow it down
        self.image += 1
        self.boom.play()
        if self.image == 45:
            self.visible = False
            self.destroy()

class Sunthing(Sprite):
    asset=ImageAsset("images/sun.png")
    width=80
    length=76
    def __init__(self, position):
        super().__init__(Sunthing.asset, position)
        self.mass = 30*1000
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        txt_asset= TextAsset(text="Press R to Reset", width=200, align='center',style='20px Arial', fill=Color(0xff2222,1))
        star0 = Sprite(bg_asset, (0,0))
        star1= Sprite(bg_asset, (512,0))
        star2= Sprite(bg_asset, (0,512))
        star3= Sprite(bg_asset, (512, 512))
        txt = Sprite(txt_asset, (0,0))
        Sunthing((500,360))
        '''
        SpaceShip((300,300))
        '''
        SpaceShip2((500,500))

    def step(self):
        '''
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()
        '''
        for ship in self.getSpritesbyClass(SpaceShip2):
            ship.step()

        explosions = self.getSpritesbyClass(ExplosionSmall)
        for explosion in explosions:
            explosion.step()

myapp = SpaceGame(SCREEN_WIDTH*1.5, SCREEN_HEIGHT*1.5)
myapp.run()
<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: Roger Danilek
Credit: Adam, Nils, Morgan, Spacewar source code

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.goup)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.turnright)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.turnleft)
        SpaceGame.listenKeyEvent("keydown", "down arrow", self.goback)

        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def goup(self, event):
        self.vy+=(-.5*(math.cos(self.rotation)))
        self.vx+=(-.5*(math.sin(self.rotation)))

    def goback(self, event):
        self.vy+=(.5*(math.cos(self.rotation)))
        self.vx+=(.5*(math.sin(self.rotation)))

    def turnright(self, event):
        self.vr=.01

    def turnleft(self, event):
        self.vr=-.01

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        bg = Sprite(bg_asset, (0,0))
        s_asset = ImageAsset("images/sun.png")
        s = Sprite(s_asset, (0,0))
        SpaceShip((100,100))
        SpaceShip((150,150))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()

<commit_msg>Updated from Brython Server: November 3, 2015 2:47:06 PM GMT-5<commit_after>"""
spaceshooter.py
Author: Roger Danilek
Credit: Adam, Nils, Morgan, Spacewar source code

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.goup)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.turnright)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.turnleft)
        SpaceGame.listenKeyEvent("keydown", "down arrow", self.goback)

        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation = self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
        else:
            self.setImage(0)

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def goup(self, event):
        self.vy+=(-.5*(math.cos(self.rotation)))
        self.vx+=(-.5*(math.sin(self.rotation)))

    def goback(self, event):
        self.vy+=(.5*(math.cos(self.rotation)))
        self.vx+=(.5*(math.sin(self.rotation)))

    def turnright(self, event):
        self.vr-=.3

    def turnleft(self, event):
        self.vr+=.3

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        bg = Sprite(bg_asset, (0,0))
        s_asset = ImageAsset("images/sun.png")
        s = Sprite(s_asset, (0,0))
        SpaceShip((100,100))
        SpaceShip((150,150))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()

<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: Jeff
Credit: Space Game tutorial

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, RectangleAsset, ImageAsset, SoundAsset, Sprite, Sound, LineStyle, Color, Frame
import math
SCREEN_WIDTH = 1536
SCREEN_HEIGHT = 1024
class Sun(Sprite):

    asset = ImageAsset("images/sun.png")
    width = 80
    height = 76

    def __init__(self, position):
        super().__init__(Sun.asset, position)
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class Ship1(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(Ship1.asset, position)
        self.vr = 0.00
        self.thrust = 0
        self.thrustframe = 1
        self.VX = 0
        self.VY = 0
        self.vx = 0
        self.vy = 0
        self.turn = 0
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.rotateLeft)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.lrOff)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.rotateRight)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.rrOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.rotation += 1.5*self.vr
        if self.thrust == 1:
            self.VX += self.vx
            self.VY += self.vy
        if 0 <= self.x <= SCREEN_WIDTH:
            self.x -= 0.1*self.VX
        elif self.x < 0:
            self.x += SCREEN_WIDTH
            self.x -= 0.1*self.VX
        else:
            self.x -= (0.1*self.VX + SCREEN_WIDTH)
        if 0 <= self.y <= SCREEN_HEIGHT:
            self.y -= 0.1*self.VY
        elif self.y < 0:
            self.y += SCREEN_HEIGHT
            self.y -= 0.1*self.VY
        else:
            self.y -= (0.1*self.VY + SCREEN_HEIGHT)

        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
            self.move()
        else:
            self.setImage(0)

        collides = self.collidingWithSprites(Ship1)
        if len(collides):
            if collides[0].visible:
                collides[0].explode()
                self.explode()

    def move(self):
        self.X = math.sin(self.rotation)
        self.Y = math.cos(self.rotation)
        self.vx = self.X/math.sqrt(self.X*self.X + self.Y*self.Y)
        self.vy = self.Y/math.sqrt(self.X*self.X + self.Y*self.Y)

    def explode(self):
        self.visible = False
        ExplosionBig(self.position)
        self.waitspawn = 5

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def rotateLeft(self, event):
        self.vr = 0.05

    def lrOff(self,  event):
        self.vr = 0

    def rotateRight(self, event):
        self.vr = -0.05

    def rrOff(self,  event):
        self.vr = 0

class Ship2(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(0,0,86,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(Ship2.asset, position)
        self.vr = 0.00
        self.thrust = 0
        self.thrustframe = 1
        self.VX = 0
        self.VY = 0
        self.vx = 0
        self.vy = 0
        self.turn = 0
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "a", self.rotateLeft)
        SpaceGame.listenKeyEvent("keyup", "a", self.lrOff)
        SpaceGame.listenKeyEvent("keydown", "d", self.rotateRight)
        SpaceGame.listenKeyEvent("keyup", "d", self.rrOff)
        SpaceGame.listenKeyEvent("keydown", "e", self.fire)
        self.fxcenter = self.fycenter = 0.5
        self.bullet = None

    def step(self):
        self.rotation += 1.5*self.vr
        if self.thrust == 1:
            self.VX += self.vx
            self.VY += self.vy
        if 0 <= self.x <= SCREEN_WIDTH:
            self.x -= 0.1*self.VX
        elif self.x < 0:
            self.x += SCREEN_WIDTH
            self.x -= 0.1*self.VX
        else:
            self.x -= (0.1*self.VX + SCREEN_WIDTH)
        if 0 <= self.y <= SCREEN_HEIGHT:
            self.y -= 0.1*self.VY
        elif self.y < 0:
            self.y += SCREEN_HEIGHT
            self.y -= 0.1*self.VY
        else:
            self.y -= (0.1*self.VY + SCREEN_HEIGHT)

        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
            self.move()
        else:
            self.setImage(0)

        collides = self.collidingWithSprites(Ship1)
        if len(collides):
            if collides[0].visible:
                collides[0].explode()
                self.explode()

    def move(self):
        self.X = math.sin(self.rotation)
        self.Y = math.cos(self.rotation)
        self.vx = self.X/math.sqrt(self.X*self.X + self.Y*self.Y)
        self.vy = self.Y/math.sqrt(self.X*self.X + self.Y*self.Y)

    def explode(self):
        self.visible = False
        ExplosionBig(self.position)
        self.waitspawn = 5

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def rotateLeft(self, event):
        self.vr = 0.05

    def lrOff(self,  event):
        self.vr = 0

    def rotateRight(self, event):
        self.vr = -0.05

    def rrOff(self,  event):
        self.vr = 0

    def fire(self, event):
        self.bullet= Bullet(self.position)
        self.bullet.shoot(self.position, 2)

class Bullet(Sprite):

    asset1 = ImageAsset("images/blast.png", Frame(0,0,8,8), 8)
    pewasset = SoundAsset("sounds/pew1.mp3")

    def __init__(self, position):
        super().__init__(Bullet.asset1, position)
        SpaceGame.listenKeyEvent("keydown", "space", self.shoot)
        self.exist = False
        self.circularCollisionModel()
        self.pew = Sound(Bullet.pewasset)
        self.pew.volume = 10

    def step(self):
        if self.exist:
            self.setImage(self.appear)
            self.appear += 1
            if self.appear == 8:
                self.appear = 1
            self.move()
        else:
            self.setImage(0)

    def shoot(self, position, velocity):
        self.exist = True

class HealthBar:

    def __init__(self, indicatorasset, initvalue, position, app):
        self.sprites = [Sprite(indicatorasset, (0,app.height-75)) for i in range(initvalue)]
        for s in self.sprites:
            s.scale = 0.4
        width = self.sprites[0].width
        if position == 'left':
            x = 50
            step = width+5
        else:
            x = app.width - 50 - width
            step = -width-5
        for s in self.sprites:
            s.x = x
            x += step
        self.restart()

    def restart(self):
        for s in self.sprites:
            s.visible = True
        self.count = len(self.sprites)

    def dead(self):
        return self.count == 0

    def killone(self):
        if self.count > 0:
            self.count -= 1
            self.sprites[self.count].visible = False

class ExplosionSmall(Sprite):

    asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10)
    boomasset = SoundAsset("sounds/explosion1.mp3")

    def __init__(self, position):
        super().__init__(ExplosionSmall.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.boom = Sound(ExplosionSmall.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image += 1
        if self.image == 20:
            self.destroy()

class ExplosionBig(Sprite):

    asset = ImageAsset("images/explosion2.png", Frame(0,0,4800/25,195), 25)
    boomasset = SoundAsset("sounds/explosion2.mp3")

    def __init__(self, position):
        super().__init__(ExplosionBig.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.boom = Sound(ExplosionBig.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image += 1
        if self.image == 50:
            self.destroy()

class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        bg = Sprite(bg_asset, (0,0))
        bg1 = Sprite(bg_asset, (512,512))
        bg2 = Sprite(bg_asset, (0,512))
        bg3 = Sprite(bg_asset, (512,0))
        bg4 = Sprite(bg_asset, (1024,512))
        bg5 = Sprite(bg_asset, (1024,0))

        Ship1((250,250))
        Ship2((400,400))
        Sun((50,50))
    def step(self):
        for ship in self.getSpritesbyClass(Ship1):
            ship.step()
        for ship in self.getSpritesbyClass(Ship2):
            ship.step()

        explosions = self.getSpritesbyClass(ExplosionSmall)
        for explosion in explosions:
            explosion.step()
        explosions = self.getSpritesbyClass(ExplosionBig)
        for explosion in explosions:
            explosion.step()

        bullets = self.getSpritebyClass(Bullet)
        for bullet in bullets:
            bullet.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()
<commit_msg>Updated from Brython Server: 10/29/2015 12:09:18 PM<commit_after>"""
spaceshooter.py
Author: Jeff
Credit: Space Game tutorial

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, RectangleAsset, ImageAsset, SoundAsset, Sprite, Sound, LineStyle, Color, Frame
import math
SCREEN_WIDTH = 1536
SCREEN_HEIGHT = 1024
class Sun(Sprite):

    asset = ImageAsset("images/sun.png")
    width = 80
    height = 76

    def __init__(self, position):
        super().__init__(Sun.asset, position)
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class Ship1(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(Ship1.asset, position)
        self.vr = 0.00
        self.thrust = 0
        self.thrustframe = 1
        self.VX = 0
        self.VY = 0
        self.vx = 0
        self.vy = 0
        self.turn = 0
        SpaceGame.listenKeyEvent("keydown", "up arrow", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "up arrow", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "left arrow", self.rotateLeft)
        SpaceGame.listenKeyEvent("keyup", "left arrow", self.lrOff)
        SpaceGame.listenKeyEvent("keydown", "right arrow", self.rotateRight)
        SpaceGame.listenKeyEvent("keyup", "right arrow", self.rrOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.rotation += 1.5*self.vr
        if self.thrust == 1:
            self.VX += self.vx
            self.VY += self.vy
        if 0 <= self.x <= SCREEN_WIDTH:
            self.x -= 0.1*self.VX
        elif self.x < 0:
            self.x += SCREEN_WIDTH
            self.x -= 0.1*self.VX
        else:
            self.x -= (0.1*self.VX + SCREEN_WIDTH)
        if 0 <= self.y <= SCREEN_HEIGHT:
            self.y -= 0.1*self.VY
        elif self.y < 0:
            self.y += SCREEN_HEIGHT
            self.y -= 0.1*self.VY
        else:
            self.y -= (0.1*self.VY + SCREEN_HEIGHT)

        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
            self.move()
        else:
            self.setImage(0)

        collides = self.collidingWithSprites(Ship1)
        if len(collides):
            if collides[0].visible:
                collides[0].explode()
                self.explode()

    def move(self):
        self.X = math.sin(self.rotation)
        self.Y = math.cos(self.rotation)
        self.vx = self.X/math.sqrt(self.X*self.X + self.Y*self.Y)
        self.vy = self.Y/math.sqrt(self.X*self.X + self.Y*self.Y)

    def explode(self):
        self.visible = False
        ExplosionBig(self.position)
        self.waitspawn = 5

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def rotateLeft(self, event):
        self.vr = 0.05

    def lrOff(self,  event):
        self.vr = 0

    def rotateRight(self, event):
        self.vr = -0.05

    def rrOff(self,  event):
        self.vr = 0

class Ship2(Sprite):

    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(0,0,86,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(Ship2.asset, position)
        self.vr = 0.00
        self.thrust = 0
        self.thrustframe = 1
        self.VX = 0
        self.VY = 0
        self.vx = 0
        self.vy = 0
        self.turn = 0
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "a", self.rotateLeft)
        SpaceGame.listenKeyEvent("keyup", "a", self.lrOff)
        SpaceGame.listenKeyEvent("keydown", "d", self.rotateRight)
        SpaceGame.listenKeyEvent("keyup", "d", self.rrOff)
        SpaceGame.listenKeyEvent("keydown", "e", self.fire)
        self.fxcenter = self.fycenter = 0.5
        self.bullet = None

    def step(self):
        self.rotation += 1.5*self.vr
        if self.thrust == 1:
            self.VX += self.vx
            self.VY += self.vy
        if 0 <= self.x <= SCREEN_WIDTH:
            self.x -= 0.1*self.VX
        elif self.x < 0:
            self.x += SCREEN_WIDTH
            self.x -= 0.1*self.VX
        else:
            self.x -= (0.1*self.VX + SCREEN_WIDTH)
        if 0 <= self.y <= SCREEN_HEIGHT:
            self.y -= 0.1*self.VY
        elif self.y < 0:
            self.y += SCREEN_HEIGHT
            self.y -= 0.1*self.VY
        else:
            self.y -= (0.1*self.VY + SCREEN_HEIGHT)

        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if self.thrustframe == 4:
                self.thrustframe = 1
            self.move()
        else:
            self.setImage(0)

        collides = self.collidingWithSprites(Ship1)
        if len(collides):
            if collides[0].visible:
                collides[0].explode()
                self.explode()

    def move(self):
        self.X = math.sin(self.rotation)
        self.Y = math.cos(self.rotation)
        self.vx = self.X/math.sqrt(self.X*self.X + self.Y*self.Y)
        self.vy = self.Y/math.sqrt(self.X*self.X + self.Y*self.Y)

    def explode(self):
        self.visible = False
        ExplosionBig(self.position)
        self.waitspawn = 5

    def thrustOn(self, event):
        self.thrust = 1

    def thrustOff(self, event):
        self.thrust = 0

    def rotateLeft(self, event):
        self.vr = 0.05

    def lrOff(self,  event):
        self.vr = 0

    def rotateRight(self, event):
        self.vr = -0.05

    def rrOff(self,  event):
        self.vr = 0

    def fire(self, event):
        self.bullet= Bullet(self.position)
        self.bullet.shoot(self.position, 2)

class Bullet(Sprite):

    asset1 = ImageAsset("images/blast.png", Frame(0,0,8,8), 8)
    pewasset = SoundAsset("sounds/pew1.mp3")

    def __init__(self, position):
        super().__init__(Bullet.asset1, position)
        SpaceGame.listenKeyEvent("keydown", "space", self.shoot)
        self.exist = False
        self.circularCollisionModel()
        self.pew = Sound(Bullet.pewasset)
        self.pew.volume = 10

    def step(self):
        if self.exist:
            self.setImage(self.appear)
            self.appear += 1
            if self.appear == 8:
                self.appear = 1
            self.move()
        else:
            self.setImage(0)

    def shoot(self, position, velocity):
        self.exist = True

class HealthBar:

    def __init__(self, indicatorasset, initvalue, position, app):
        self.sprites = [Sprite(indicatorasset, (0,app.height-75)) for i in range(initvalue)]
        for s in self.sprites:
            s.scale = 0.4
        width = self.sprites[0].width
        if position == 'left':
            x = 50
            step = width+5
        else:
            x = app.width - 50 - width
            step = -width-5
        for s in self.sprites:
            s.x = x
            x += step
        self.restart()

    def restart(self):
        for s in self.sprites:
            s.visible = True
        self.count = len(self.sprites)

    def dead(self):
        return self.count == 0

    def killone(self):
        if self.count > 0:
            self.count -= 1
            self.sprites[self.count].visible = False

class ExplosionSmall(Sprite):

    asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10)
    boomasset = SoundAsset("sounds/explosion1.mp3")

    def __init__(self, position):
        super().__init__(ExplosionSmall.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.boom = Sound(ExplosionSmall.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image += 1
        if self.image == 20:
            self.destroy()

class ExplosionBig(Sprite):

    asset = ImageAsset("images/explosion2.png", Frame(0,0,4800/25,195), 25)
    boomasset = SoundAsset("sounds/explosion2.mp3")

    def __init__(self, position):
        super().__init__(ExplosionBig.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.boom = Sound(ExplosionBig.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image += 1
        if self.image == 50:
            self.destroy()

class SpaceGame(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        bg = Sprite(bg_asset, (0,0))
        bg1 = Sprite(bg_asset, (512,512))
        bg2 = Sprite(bg_asset, (0,512))
        bg3 = Sprite(bg_asset, (512,0))
        bg4 = Sprite(bg_asset, (1024,512))
        bg5 = Sprite(bg_asset, (1024,0))

        Ship1((250,250))
        Ship2((400,400))
        Sun((50,50))
    def step(self):
        for ship in self.getSpritesbyClass(Ship1):
            ship.step()
        for ship in self.getSpritesbyClass(Ship2):
            ship.step()

        explosions = self.getSpritesbyClass(ExplosionSmall)
        for explosion in explosions:
            explosion.step()
        explosions = self.getSpritesbyClass(ExplosionBig)
        for explosion in explosions:
            explosion.step()

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()
<|endoftext|>