<commit_before># -*- coding: utf-8 -*-

"""
Wordpress Requests Class
"""

__title__ = "wordpress-requests"

from requests import Request, Session
from json import dumps as jsonencode

try:
    from urllib.parse import urlencode, quote, unquote, parse_qsl, urlparse, urlunparse
    from urllib.parse import ParseResult as URLParseResult
except ImportError:
    from urllib import urlencode, quote, unquote
    from urlparse import parse_qsl, urlparse, urlunparse
    from urlparse import ParseResult as URLParseResult

from wordpress import __version__
from wordpress import __default_api_version__
from wordpress import __default_api__
from wordpress.helpers import SeqUtils, UrlUtils, StrUtils

class API_Requests_Wrapper(object):
    """ provides a wrapper for making requests that handles session info """
    def __init__(self, url, **kwargs):
        self.url = url
        self.api = kwargs.get("api", __default_api__)
        self.api_version = kwargs.get("version", __default_api_version__)
        self.timeout = kwargs.get("timeout", 5)
        self.verify_ssl = kwargs.get("verify_ssl", True)
        self.query_string_auth = kwargs.get("query_string_auth", False)
        self.session = Session()

    @property
    def is_ssl(self):
        return UrlUtils.is_ssl(self.url)

    @property
    def api_url(self):
        return UrlUtils.join_components([
            self.url,
            self.api
        ])

    def endpoint_url(self, endpoint):
        endpoint = StrUtils.decapitate(endpoint, '/')
        return UrlUtils.join_components([
            self.url,
            self.api,
            self.api_version,
            endpoint
        ])

    def request(self, method, url, auth=None, params=None, data=None, **kwargs):
        headers = {
            "user-agent": "BCBS Wordpress API Client-Python/%s" % __version__,
            "accept": "application/json",
            "referrer": "https://bcbud.store/"
        }
        if data is not None:
            headers["content-type"] = "application/json;charset=utf-8"

        #args_headers = kwargs.get("headers", False)

       # if args_headers:
            #for k, v in args_headers.iteritems():

            #    headers[k] = v
           # kwargs["headers"] = headers

        print headers

        print kwargs

        request_kwargs = dict(
            method=method,
            url=url,
           # headers=headers,
            verify=self.verify_ssl,
            timeout=self.timeout,
        )
        request_kwargs.update(kwargs)

        print headers
        print request_kwargs

        if auth is not None: request_kwargs['auth'] = auth
        if params is not None: request_kwargs['params'] = params
        if data is not None: request_kwargs['data'] = data
        return self.session.request(
            **request_kwargs
        )

    def get(self, *args, **kwargs):
        return self.request("GET", *args, **kwargs)

    def post(self, *args, **kwargs):
        return self.request("POST", *args, **kwargs)
<commit_msg>just a test<commit_after># -*- coding: utf-8 -*-

"""
Wordpress Requests Class
"""

__title__ = "wordpress-requests"

from requests import Request, Session
from json import dumps as jsonencode

try:
    from urllib.parse import urlencode, quote, unquote, parse_qsl, urlparse, urlunparse
    from urllib.parse import ParseResult as URLParseResult
except ImportError:
    from urllib import urlencode, quote, unquote
    from urlparse import parse_qsl, urlparse, urlunparse
    from urlparse import ParseResult as URLParseResult

from wordpress import __version__
from wordpress import __default_api_version__
from wordpress import __default_api__
from wordpress.helpers import SeqUtils, UrlUtils, StrUtils

class API_Requests_Wrapper(object):
    """ provides a wrapper for making requests that handles session info """
    def __init__(self, url, **kwargs):
        self.url = url
        self.api = kwargs.get("api", __default_api__)
        self.api_version = kwargs.get("version", __default_api_version__)
        self.timeout = kwargs.get("timeout", 5)
        self.verify_ssl = kwargs.get("verify_ssl", True)
        self.query_string_auth = kwargs.get("query_string_auth", False)
        self.session = Session()

    @property
    def is_ssl(self):
        return UrlUtils.is_ssl(self.url)

    @property
    def api_url(self):
        return UrlUtils.join_components([
            self.url,
            self.api
        ])

    def endpoint_url(self, endpoint):
        endpoint = StrUtils.decapitate(endpoint, '/')
        return UrlUtils.join_components([
            self.url,
            self.api,
            self.api_version,
            endpoint
        ])

    def request(self, method, url, auth=None, params=None, data=None, **kwargs):
        headers = {
            "user-agent": "BCBS Wordpress API Client-Python/%s" % __version__,
            "accept": "application/json",
            "referrer": "https://bcbud.store/"
        }
        if data is not None:
            headers["content-type"] = "application/json;charset=utf-8"

        #args_headers = kwargs.get("headers", False)

       # if args_headers:
            #for k, v in args_headers.iteritems():

            #    headers[k] = v
           # kwargs["headers"] = headers

        print headers

        print kwargs

        request_kwargs = dict(
            method=method,
            url=url,
            headers=headers,
            verify=self.verify_ssl,
            timeout=self.timeout,
        )
        request_kwargs.update(kwargs)

        print headers
        print request_kwargs

        if auth is not None: request_kwargs['auth'] = auth
        if params is not None: request_kwargs['params'] = params
        if data is not None: request_kwargs['data'] = data
        return self.session.request(
            **request_kwargs
        )

    def get(self, *args, **kwargs):
        return self.request("GET", *args, **kwargs)

    def post(self, *args, **kwargs):
        return self.request("POST", *args, **kwargs)
<|endoftext|>


<commit_before>import iso8601
from django.core.cache import cache
from django.shortcuts import render
from django.views.generic import View
from django.contrib import messages
from django.http import Http404
from django.utils.translation import get_language
from django.conf import settings
from .utils import WPApiConnector

# Create your views here.
try:
    cache_time = settings.WP_API_BLOG_CACHE_TIMEOUT
except AttributeError:
    cache_time = 0

class ParentBlogView(View):
    """
    Class that defines a method to calculate args for the wp_api
    on the fly. Most of the code of the other views is the same.
    """

    def __init__(self, *args, **kwargs):
        super(ParentBlogView, self).__init__(*args, **kwargs)
        try:  # pragma: no cover
            allow_language = settings.WP_API_ALLOW_LANGUAGE
            if allow_language:
                self.blog_language = str(get_language())
            else:
                self.blog_language = 'en'
        except AttributeError:
            self.blog_language = 'en'
        self.connector = WPApiConnector(lang=self.blog_language)

    def dispatch(self, *args, **kwargs):
        authors = self.connector.authors
        tags = self.connector.tags
        categories = self.connector.categories
        if 'server_error' in tags or\
           'server_error' in categories or\
           'server_error' in authors:
            messages.add_message(
                self.request, messages.ERROR,
                'The server is not reachable this moment. \
                Please try again later')
            raise Http404
        return super(ParentBlogView, self).dispatch(*args, **kwargs)

    def get_wp_api_kwargs(self, **kwargs):
        try:
            page = int(self.request.GET.get('page', 1))
        except ValueError:  # pragma: no cover
            page = 1
        wp_api = {
            'page_number': page
        }
        return wp_api

    def get_context_data(self, **kwargs):
        api_kwargs = self.get_wp_api_kwargs(**kwargs)
        page = api_kwargs.get('page_number', 1)
        search = api_kwargs.get('search', '')
        blogs = self.connector.get_posts(**api_kwargs)
        tags = self.connector.tags
        categories = self.connector.categories
        if 'server_error' in blogs:
            messages.add_message(self.request, messages.ERROR,
                                 blogs['server_error'])
            raise Http404
        if not blogs['body']:
            raise Http404
        for blog in blogs['body']:
            blog['slug'] = str(blog['slug'])
            blog['bdate'] = iso8601.parse_date(blog['date']).date()
            featured_media = blog.get(
                '_embedded', {}).get('wp:featuredmedia', [])
            authors = blog.get(
                '_embedded', {}).get('author', [])
            if featured_media:
                blog['featured_image'] = featured_media[0]
            if authors:
                blog['authors'] = authors
        context = {
            'blogs': blogs['body'],
            'tags': tags,
            'categories': categories,
            'search': search,
            'total_posts': int(blogs['headers']['X-WP-Total']),
            'total_pages': int(blogs['headers']['X-WP-TotalPages']),
            'current_page': page,
            'previous_page': page - 1,
            'next_page': page + 1,
        }
        return context

    def get(self, request, **kwargs):
        context = self.get_context_data(**kwargs)
        return render(request, self.template_name, context)

class BlogListView(ParentBlogView):
    """
    View to display all blogs in wp blog
    """
    template_name = 'wordpress_api/blog_list.html'

    def get_wp_api_kwargs(self, **kwargs):
        wp_api = super(BlogListView, self).get_wp_api_kwargs(**kwargs)
        search_term = self.request.GET.get('q', None)
        if search_term is not None:
            wp_api['search'] = search_term
        return wp_api

    def get_context_data(self, **kwargs):
        api_kwargs = self.get_wp_api_kwargs(**kwargs)
        page = api_kwargs.get('page_number', 1)
        context = cache.get(
            "blog_list_cache" + self.blog_language + "_page_" + str(page))
        context = super(BlogListView, self).get_context_data(**kwargs) if\
            context is None else context
        cache.add(
            "blog_list_cache" + self.blog_language + "_page_" + str(page),
            context, cache_time)
        return context

class BlogView(ParentBlogView):
    """
    View to display blog detail in wp blog
    """
    template_name = 'wordpress_api/blog_detail.html'

    def get_wp_api_kwargs(self, **kwargs):
        wp_api = super(BlogView, self).get_wp_api_kwargs(**kwargs)
        wp_api['wp_filter'] = {'name': str(kwargs.get('slug'))}
        return wp_api

    def get_context_data(self, **kwargs):
        blog = cache.get("blog_cache_detail_{}_{}".format(
            kwargs.get('slug'), self.blog_language))
        api_kwargs = self.get_wp_api_kwargs(**kwargs)
        blog = self.connector.get_posts(
            **api_kwargs) if blog is None else blog
        tags = self.connector.tags
        categories = self.connector.categories
        cache.add(
            "blog_cache_detail_{}_{}".format(
                kwargs.get('slug'), self.blog_language),
            blog, cache_time)
        if 'server_error' in blog or\
           'server_error' in tags:
            messages.add_message(self.request, messages.ERROR,
                                 blog['server_error'])
            raise Http404

        if not blog['body']:
            raise Http404
        bdate = iso8601.parse_date(blog['body'][0]['date'])

        blog = blog['body'][0]
        blog_categories = []
        blog['slug'] = str(blog['slug'])
        blog['bdate'] = iso8601.parse_date(blog['date']).date()
        featured_media = blog.get(
            '_embedded', {}).get('wp:featuredmedia', [])
        authors = blog.get(
            '_embedded', {}).get('author', [])
        if featured_media:
            blog['featured_image'] = featured_media[0]
        if authors:
            blog['authors'] = authors
        if 'categories' in blog:
            for category in categories:
                if category['id'] in blog['categories']:
                    blog_categories.append(category)
        blog_tags = []
        if 'tags' in blog:
            for tag in tags:
                if tag['id'] in blog['tags']:
                    blog_tags.append(tag)
            if blog_tags:
                related_blogs = cache.get(
                    "blog_cache_detail_related_{}_{}".format(
                        kwargs.get('slug'), self.blog_language))
                tag_query = ",".join([str(tag['id']) for tag in blog_tags])
                related_blogs = self.connector.get_posts(
                    wp_filter={'tag': tag_query},
                    page_number=1,
                    orderby='date')['body'] if related_blogs is None else\
                    related_blogs
                for related_blog in related_blogs:
                    related_blog['slug'] = str(related_blog['slug'])
                    related_blog['bdate'] = iso8601.parse_date(
                        related_blog['date']).date()
                    featured_media = related_blog.get(
                        '_embedded', {}).get('wp:featuredmedia', [])
                    authors = related_blog.get(
                        '_embedded', {}).get('author', [])
                    if featured_media:
                        related_blog['featured_image'] = featured_media[0]
                    if authors:
                        related_blog['authors'] = authors
                cache.add(
                    "blog_cache_detail_related_{}_{}".format(
                        kwargs.get('slug'), self.blog_language),
                    related_blogs, cache_time)

                for related in related_blogs:
                    related_bdate = iso8601.parse_date(related['date_gmt'])
                    related['bdate'] = related_bdate.date()
            else:
                related_blogs = []
        else:
            related_blogs = []
        if blog in related_blogs:
            related_blogs.remove(blog)
        context = {
            'tags': tags,
            'categories': categories,
            'related_blogs': related_blogs[:3],
            'blog': blog,
            'blog_tags': blog_tags,
            'blog_categories': blog_categories,
            'bdate': bdate.date(),
        }
        return context

class CategoryBlogListView(ParentBlogView):
    """
    View to display all blogs in wp blog by category
    """
    template_name = 'wordpress_api/blog_list.html'

    def get_wp_api_kwargs(self, **kwargs):
        slug = kwargs.get('slug')
        self.category = None
        for category in self.connector.categories:
            if category['slug'] == slug:
                self.category = category
                break
        if self.category is None:
            raise Http404
        wp_api = super(CategoryBlogListView, self).get_wp_api_kwargs(**kwargs)
        wp_api['wp_filter'] = {'categories': self.category['id']}
        return wp_api

    def get(self, request, **kwargs):
        api_kwargs = self.get_wp_api_kwargs(**kwargs)
        page = api_kwargs.get('page_number', 1)
        context = cache.get(
            "blog_category_context_" +
            kwargs.get('slug') + self.blog_language + '_page_' + str(page))
        context = self.get_context_data(**kwargs) if\
            context is None else context
        cache.add(
            "blog_category_context_" +
            kwargs.get('slug') + self.blog_language + '_page_' + str(page),
            context, cache_time)
        category_name = None
        context['category'] = self.category
        category_name = self.category['name']
        context['category_name'] = category_name
        return render(request, self.template_name, context)

class TagBlogListView(ParentBlogView):
    """
    View to display all blogs in wp blog by tag
    """
    template_name = 'wordpress_api/blog_list.html'

    def get_wp_api_kwargs(self, **kwargs):
        slug = kwargs.get('slug')
        self.tag = None
        for tag in self.connector.tags:
            if tag['slug'] == slug:
                self.tag = tag
                break
        if self.tag is None:
            raise Http404
        wp_api = super(TagBlogListView, self).get_wp_api_kwargs(**kwargs)
        wp_api['wp_filter'] = {'tags': self.tag['id']}
        return wp_api

    def get(self, request, **kwargs):
        api_kwargs = self.get_wp_api_kwargs(**kwargs)
        page = api_kwargs.get('page_number', 1)
        context = cache.get("blog_tag_context_" + kwargs.get('slug') +
                            self.blog_language + '_page_' + str(page))
        context = self.get_context_data(**kwargs) if\
            context is None else context
        cache.add("blog_tag_context_" + kwargs.get('slug') +
                  self.blog_language + '_page_' + str(page),
                  context, cache_time)
        category_name = None
        context['tag'] = self.tag
        category_name = self.tag['name']
        context['tag_name'] = category_name
        return render(request, self.template_name, context)

class BlogByAuthorListView(ParentBlogView):
    """
    View to display all blogs written by given author
    """
    template_name = 'wordpress_api/blog_list.html'

    def get_wp_api_kwargs(self, **kwargs):
        wp_api = super(BlogByAuthorListView, self).get_wp_api_kwargs(**kwargs)
        slug = kwargs.get('slug')
        authors = self.connector.authors
        if slug in authors:
            wp_api['wp_filter'] = {'author': authors[slug]['id']}
        else:
            wp_api['wp_filter'] = {'author': -1}
        return wp_api

    def get(self, request, **kwargs):
        api_kwargs = self.get_wp_api_kwargs(**kwargs)
        page = api_kwargs.get('page_number', 1)
        context = cache.get("blog_author_context_" + kwargs.get('slug') +
                            self.blog_language + '_page_' + str(page))
        context = self.get_context_data(**kwargs) if\
            context is None else context
        cache.add("blog_author_context_" + kwargs.get('slug') +
                  self.blog_language + '_page_' + str(page),
                  context, cache_time)
        author_name = None
        if context['blogs']:
            for blog in context['blogs']:
                authors = blog.get(
                    '_embedded', {}).get('author', [])
                for author in authors:
                    if str(author['slug']) == kwargs.get('slug'):
                        author_name = kwargs.get('slug')
                        context['author_name'] = author_name
                        return render(
                            request, self.template_name, context)

        context['author_name'] = author_name
        return render(request, self.template_name, context)
<commit_msg>fixed minor issue<commit_after>import iso8601
from django.core.cache import cache
from django.shortcuts import render
from django.views.generic import View
from django.contrib import messages
from django.http import Http404
from django.utils.translation import get_language
from django.conf import settings
from .utils import WPApiConnector

# Create your views here.
try:
    cache_time = settings.WP_API_BLOG_CACHE_TIMEOUT
except AttributeError:
    cache_time = 0

class ParentBlogView(View):
    """
    Class that defines a method to calculate args for the wp_api
    on the fly. Most of the code of the other views is the same.
    """

    def __init__(self, *args, **kwargs):
        super(ParentBlogView, self).__init__(*args, **kwargs)
        try:  # pragma: no cover
            allow_language = settings.WP_API_ALLOW_LANGUAGE
            if allow_language:
                self.blog_language = str(get_language())
            else:
                self.blog_language = 'en'
        except AttributeError:
            self.blog_language = 'en'
        self.connector = WPApiConnector(lang=self.blog_language)

    def dispatch(self, *args, **kwargs):
        authors = self.connector.authors
        tags = self.connector.tags
        categories = self.connector.categories
        if 'server_error' in tags or\
           'server_error' in categories or\
           'server_error' in authors:
            messages.add_message(
                self.request, messages.ERROR,
                'The server is not reachable this moment. \
                Please try again later')
            raise Http404
        return super(ParentBlogView, self).dispatch(*args, **kwargs)

    def get_wp_api_kwargs(self, **kwargs):
        try:
            page = int(self.request.GET.get('page', 1))
        except ValueError:  # pragma: no cover
            page = 1
        wp_api = {
            'page_number': page
        }
        return wp_api

    def get_context_data(self, **kwargs):
        api_kwargs = self.get_wp_api_kwargs(**kwargs)
        page = api_kwargs.get('page_number', 1)
        search = api_kwargs.get('search', '')
        blogs = self.connector.get_posts(**api_kwargs)
        tags = self.connector.tags
        categories = self.connector.categories
        if 'server_error' in blogs:
            messages.add_message(self.request, messages.ERROR,
                                 blogs['server_error'])
            raise Http404
        if not blogs['body']:
            raise Http404
        for blog in blogs['body']:
            blog['slug'] = str(blog['slug'])
            blog['bdate'] = iso8601.parse_date(blog['date']).date()
            featured_media = blog.get(
                '_embedded', {}).get('wp:featuredmedia', [])
            authors = blog.get(
                '_embedded', {}).get('author', [])
            if featured_media:
                blog['featured_image'] = featured_media[0]
            if authors:
                blog['authors'] = authors
        context = {
            'blogs': blogs['body'],
            'tags': tags,
            'categories': categories,
            'search': search,
            'total_posts': int(blogs['headers']['X-WP-Total']),
            'total_pages': int(blogs['headers']['X-WP-TotalPages']),
            'current_page': page,
            'previous_page': page - 1,
            'next_page': page + 1,
        }
        return context

    def get(self, request, **kwargs):
        context = self.get_context_data(**kwargs)
        return render(request, self.template_name, context)

class BlogListView(ParentBlogView):
    """
    View to display all blogs in wp blog
    """
    template_name = 'wordpress_api/blog_list.html'

    def get_wp_api_kwargs(self, **kwargs):
        wp_api = super(BlogListView, self).get_wp_api_kwargs(**kwargs)
        search_term = self.request.GET.get('q', None)
        if search_term is not None:
            wp_api['search'] = search_term
        return wp_api

    def get_context_data(self, **kwargs):
        api_kwargs = self.get_wp_api_kwargs(**kwargs)
        page = api_kwargs.get('page_number', 1)
        context = cache.get(
            "blog_list_cache" + self.blog_language + "_page_" + str(page))
        context = super(BlogListView, self).get_context_data(**kwargs) if\
            context is None else context
        cache.add(
            "blog_list_cache" + self.blog_language + "_page_" + str(page),
            context, cache_time)
        return context

class BlogView(ParentBlogView):
    """
    View to display blog detail in wp blog
    """
    template_name = 'wordpress_api/blog_detail.html'

    def get_wp_api_kwargs(self, **kwargs):
        wp_api = super(BlogView, self).get_wp_api_kwargs(**kwargs)
        wp_api['wp_filter'] = {'name': str(kwargs.get('slug'))}
        return wp_api

    def get_context_data(self, **kwargs):
        blog = cache.get("blog_cache_detail_{}_{}".format(
            kwargs.get('slug'), self.blog_language))
        api_kwargs = self.get_wp_api_kwargs(**kwargs)
        blog = self.connector.get_posts(
            **api_kwargs) if blog is None else blog
        tags = self.connector.tags
        categories = self.connector.categories
        cache.add(
            "blog_cache_detail_{}_{}".format(
                kwargs.get('slug'), self.blog_language),
            blog, cache_time)
        if 'server_error' in blog or\
           'server_error' in tags:
            messages.add_message(self.request, messages.ERROR,
                                 blog['server_error'])
            raise Http404

        if not blog['body']:
            raise Http404
        bdate = iso8601.parse_date(blog['body'][0]['date'])

        blog = blog['body'][0]
        blog_categories = []
        blog['slug'] = str(blog['slug'])
        blog['bdate'] = iso8601.parse_date(blog['date']).date()
        featured_media = blog.get(
            '_embedded', {}).get('wp:featuredmedia', [])
        authors = blog.get(
            '_embedded', {}).get('author', [])
        if featured_media:
            blog['featured_image'] = featured_media[0]
        if authors:
            blog['authors'] = authors
        if 'categories' in blog:
            for category in categories:
                if category['id'] in blog['categories']:
                    blog_categories.append(category)
        blog_tags = []
        if 'tags' in blog:
            for tag in tags:
                if tag['id'] in blog['tags']:
                    blog_tags.append(tag)
            if blog_tags:
                related_blogs = cache.get(
                    "blog_cache_detail_related_{}_{}".format(
                        kwargs.get('slug'), self.blog_language))
                tag_query = ",".join([str(tag['id']) for tag in blog_tags])
                related_blogs = self.connector.get_posts(
                    wp_filter={'tag': tag_query},
                    page_number=1,
                    orderby='date')['body'] if related_blogs is None else\
                    related_blogs
                for related_blog in related_blogs:
                    related_blog['slug'] = str(related_blog['slug'])
                    related_blog['bdate'] = iso8601.parse_date(
                        related_blog['date']).date()
                    featured_media = related_blog.get(
                        '_embedded', {}).get('wp:featuredmedia', [])
                    authors = related_blog.get(
                        '_embedded', {}).get('author', [])
                    if featured_media:
                        related_blog['featured_image'] = featured_media[0]
                    if authors:
                        related_blog['authors'] = authors
                cache.add(
                    "blog_cache_detail_related_{}_{}".format(
                        kwargs.get('slug'), self.blog_language),
                    related_blogs, cache_time)

                for related in related_blogs:
                    related_bdate = iso8601.parse_date(related['date_gmt'])
                    related['bdate'] = related_bdate.date()
            else:
                related_blogs = []
        else:
            related_blogs = []
        if blog in related_blogs:
            related_blogs.remove(blog)
        context = {
            'tags': tags,
            'categories': categories,
            'related_blogs': related_blogs[:3],
            'blog': blog,
            'blog_tags': blog_tags,
            'blog_categories': blog_categories,
            'bdate': bdate.date(),
        }
        return context

class CategoryBlogListView(ParentBlogView):
    """
    View to display all blogs in wp blog by category
    """
    template_name = 'wordpress_api/blog_list.html'

    def get_wp_api_kwargs(self, **kwargs):
        slug = kwargs.get('slug')
        self.category = None
        for category in self.connector.categories:
            if category['slug'] == slug:
                self.category = category
                break
        if self.category is None:
            raise Http404
        wp_api = super(CategoryBlogListView, self).get_wp_api_kwargs(**kwargs)
        wp_api['wp_filter'] = {'categories': self.category['id']}
        return wp_api

    def get(self, request, **kwargs):
        api_kwargs = self.get_wp_api_kwargs(**kwargs)
        page = api_kwargs.get('page_number', 1)
        context = cache.get(
            "blog_category_context_" +
            kwargs.get('slug') + self.blog_language + '_page_' + str(page))
        context = self.get_context_data(**kwargs) if\
            context is None else context
        cache.add(
            "blog_category_context_" +
            kwargs.get('slug') + self.blog_language + '_page_' + str(page),
            context, cache_time)
        category_name = None
        context['category'] = self.category
        category_name = self.category['name']
        context['category_name'] = category_name
        return render(request, self.template_name, context)

class TagBlogListView(ParentBlogView):
    """
    View to display all blogs in wp blog by tag
    """
    template_name = 'wordpress_api/blog_list.html'

    def get_wp_api_kwargs(self, **kwargs):
        slug = kwargs.get('slug')
        self.tag = None
        for tag in self.connector.tags:
            if tag['slug'] == slug:
                self.tag = tag
                break
        if self.tag is None:
            raise Http404
        wp_api = super(TagBlogListView, self).get_wp_api_kwargs(**kwargs)
        wp_api['wp_filter'] = {'tags': self.tag['id']}
        return wp_api

    def get(self, request, **kwargs):
        api_kwargs = self.get_wp_api_kwargs(**kwargs)
        page = api_kwargs.get('page_number', 1)
        context = cache.get("blog_tag_context_" + kwargs.get('slug') +
                            self.blog_language + '_page_' + str(page))
        context = self.get_context_data(**kwargs) if\
            context is None else context
        cache.add("blog_tag_context_" + kwargs.get('slug') +
                  self.blog_language + '_page_' + str(page),
                  context, cache_time)
        category_name = None
        context['tag'] = self.tag
        category_name = self.tag['name']
        context['tag_name'] = category_name
        return render(request, self.template_name, context)

class BlogByAuthorListView(ParentBlogView):
    """
    View to display all blogs written by given author
    """
    template_name = 'wordpress_api/blog_list.html'

    def get_wp_api_kwargs(self, **kwargs):
        wp_api = super(BlogByAuthorListView, self).get_wp_api_kwargs(**kwargs)
        slug = kwargs.get('slug')
        authors = self.connector.authors
        if slug in authors:
            wp_api['wp_filter'] = {'author': authors[slug]['id']}
        else:
            raise Http404
        return wp_api

    def get(self, request, **kwargs):
        api_kwargs = self.get_wp_api_kwargs(**kwargs)
        page = api_kwargs.get('page_number', 1)
        context = cache.get("blog_author_context_" + kwargs.get('slug') +
                            self.blog_language + '_page_' + str(page))
        context = self.get_context_data(**kwargs) if\
            context is None else context
        cache.add("blog_author_context_" + kwargs.get('slug') +
                  self.blog_language + '_page_' + str(page),
                  context, cache_time)
        author_name = None
        if context['blogs']:
            for blog in context['blogs']:
                authors = blog.get(
                    '_embedded', {}).get('author', [])
                for author in authors:
                    if str(author['slug']) == kwargs.get('slug'):
                        author_name = kwargs.get('slug')
                        context['author_name'] = author_name
                        return render(
                            request, self.template_name, context)

        context['author_name'] = author_name
        return render(request, self.template_name, context)
<|endoftext|>


<commit_before>import boto3
import json

# Taken from free tear list when creating an instance
instances = [
    'ami-760aaa0f', 'ami-bb9a6bc2', 'ami-35e92e4c', 'ami-785db401', 'ami-b7e93bce', 'ami-dca37ea5', 'ami-999844e0',
    'ami-9b32e8e2', 'ami-f8e54081', 'ami-bceb39c5', 'ami-03cf127a', 'ami-1ecc1e67', 'ami-c2ff2dbb', 'ami-12c6146b',
    'ami-d1cb19a8', 'ami-61db0918', 'ami-56ec3e2f', 'ami-84ee3cfd', 'ami-86ee3cff', 'ami-f0e83a89', 'ami-1f12c066',
    'ami-afee3cd6', 'ami-1812c061', 'ami-77ed3f0e', 'ami-3bf32142', 'ami-6ef02217', 'ami-f4cf1d8d', 'ami-3df32144',
    'ami-c6f321bf', 'ami-24f3215d', 'ami-fa7cdd89', 'ami-1e749f67', 'ami-a9cc1ed0', 'ami-8104a4f8'
]

client = boto3.client('ec2', region_name='eu-west-1')

test = client.describe_images(ImageIds=instances)

result = []
for image in test['Images']:
    try:
        tmp = {
            'ami_id': image['ImageId'],
            'name': image['Name'],
            'description': image['Description'],
            'owner_id': image['OwnerId'],
            'public': image['Public'],
            'virtualization_type': image['VirtualizationType'],
            'architecture': image['Architecture'],
            'state': image['State'],
            'platform': image.get('Platform'),
            'image_type': image['ImageType'],
            'hypervisor': image['Hypervisor'],
            'root_device_name': image['RootDeviceName'],
            'root_device_type': image['RootDeviceType'],
            'sriov': image.get('SriovNetSupport', 'simple')
        }
        result.append(tmp)
    except Exception as err:
        pass

print(json.dumps(result, indent=2))
<commit_msg>Fix tier typo in get_amis.py (#1714)<commit_after>import boto3
import json

# Taken from free tier list when creating an instance
instances = [
    'ami-760aaa0f', 'ami-bb9a6bc2', 'ami-35e92e4c', 'ami-785db401', 'ami-b7e93bce', 'ami-dca37ea5', 'ami-999844e0',
    'ami-9b32e8e2', 'ami-f8e54081', 'ami-bceb39c5', 'ami-03cf127a', 'ami-1ecc1e67', 'ami-c2ff2dbb', 'ami-12c6146b',
    'ami-d1cb19a8', 'ami-61db0918', 'ami-56ec3e2f', 'ami-84ee3cfd', 'ami-86ee3cff', 'ami-f0e83a89', 'ami-1f12c066',
    'ami-afee3cd6', 'ami-1812c061', 'ami-77ed3f0e', 'ami-3bf32142', 'ami-6ef02217', 'ami-f4cf1d8d', 'ami-3df32144',
    'ami-c6f321bf', 'ami-24f3215d', 'ami-fa7cdd89', 'ami-1e749f67', 'ami-a9cc1ed0', 'ami-8104a4f8'
]

client = boto3.client('ec2', region_name='eu-west-1')

test = client.describe_images(ImageIds=instances)

result = []
for image in test['Images']:
    try:
        tmp = {
            'ami_id': image['ImageId'],
            'name': image['Name'],
            'description': image['Description'],
            'owner_id': image['OwnerId'],
            'public': image['Public'],
            'virtualization_type': image['VirtualizationType'],
            'architecture': image['Architecture'],
            'state': image['State'],
            'platform': image.get('Platform'),
            'image_type': image['ImageType'],
            'hypervisor': image['Hypervisor'],
            'root_device_name': image['RootDeviceName'],
            'root_device_type': image['RootDeviceType'],
            'sriov': image.get('SriovNetSupport', 'simple')
        }
        result.append(tmp)
    except Exception as err:
        pass

print(json.dumps(result, indent=2))
<|endoftext|>


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

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
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.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "s", self.thrustDecel)
        SpaceGame.listenKeyEvent("keyup", "s", 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)
        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 = math.cos((self.rotation)+(math.pi/2))
            self.vy = math.sin((self.rotation)+(math.pi/2))
            """
            if 0 <= self.rotation and self.rotation <= math.pi/4:
                self.vx = -.5
                self.vy = -1.5
            elif math.pi/4 <= self.rotation and self.rotation <= math.pi/2:
                self.vx = -1.5
                self.vy = -.5
            elif math.pi/2 <= self.rotation and self.rotation <= 3*math.pi/4:
                self.vx = -1.5
                self.vy =.5
            elif 3*math.pi/4 <= self.rotation and self.rotation <= math.pi:
                self.vx=-.5
                self.vy=1.5
            elif math.pi <= self.rotation and self.rotation <= 5*math.pi/4:
                self.vx=.5
                self.vy=1.5
            elif 5*math.pi/4 <= self.rotation and self.rotation <= 3*math.pi/2:
                self.vx =1.5
                self.vy=.5
            """
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.thrust == -1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.vx=self.vx+.01
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.vr==.1:
            self.rotation =self.rotation+.0001
        if self.vr==-.1:
            self.rotation =self.rotation-.0001
        if self.vr==0:
            self.rotation=self.rotation

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

    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 explode(self):
        self.visible =False
        self.ExplosionSmall

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 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")
        star0 = Sprite(bg_asset, (0,0))
        star1= Sprite(bg_asset, (512,0))
        star2= Sprite(bg_asset, (0,512))
        star3= Sprite(bg_asset, (512, 512))
        Sunthing((500,360))
        SpaceShip((300,300))

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

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

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
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.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "s", self.thrustDecel)
        SpaceGame.listenKeyEvent("keyup", "s", 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)
        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 = math.sin((self.rotation)+(math.pi/2))
            self.vy = math.cos((self.rotation)+(math.pi/2))
            """
            if 0 <= self.rotation and self.rotation <= math.pi/4:
                self.vx = -.5
                self.vy = -1.5
            elif math.pi/4 <= self.rotation and self.rotation <= math.pi/2:
                self.vx = -1.5
                self.vy = -.5
            elif math.pi/2 <= self.rotation and self.rotation <= 3*math.pi/4:
                self.vx = -1.5
                self.vy =.5
            elif 3*math.pi/4 <= self.rotation and self.rotation <= math.pi:
                self.vx=-.5
                self.vy=1.5
            elif math.pi <= self.rotation and self.rotation <= 5*math.pi/4:
                self.vx=.5
                self.vy=1.5
            elif 5*math.pi/4 <= self.rotation and self.rotation <= 3*math.pi/2:
                self.vx =1.5
                self.vy=.5
            """
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.thrust == -1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.vx=self.vx+.01
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.vr==.1:
            self.rotation =self.rotation+.0001
        if self.vr==-.1:
            self.rotation =self.rotation-.0001
        if self.vr==0:
            self.rotation=self.rotation

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

    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 explode(self):
        self.visible =False
        self.ExplosionSmall

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 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")
        star0 = Sprite(bg_asset, (0,0))
        star1= Sprite(bg_asset, (512,0))
        star2= Sprite(bg_asset, (0,512))
        star3= Sprite(bg_asset, (512, 512))
        Sunthing((500,360))
        SpaceShip((300,300))

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

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


<commit_before>"""
spaceshooter.py
Author: Ethan Adner
Credit:
ta presence, n'importe ou, me console. Au cas que ton ceour bat, je suis content
mon amour pour toi est eternel et vivante
sans vous, mes
Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar

tutorial4.py
by E. Dennison
"""

from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import sin, cos, pi

SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 700
"""
xli=[]
for x in range(-25,25):
    xli.append(x+500)
yli=[]
for x in range(-25, 25):
    yli.append(x+300)
"""

class sun(Sprite):

    asset1 = ImageAsset("images/sun.png")
    height = 50
    width = 50

    def __init__(self, position):
        super().__init__(sun.asset1, position)

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", "q", self.clockwise)
        SpaceGame.listenKeyEvent("keyup", "q", self.stopr)
        SpaceGame.listenKeyEvent("keydown", "e", self.cntrclockwise)
        SpaceGame.listenKeyEvent("keyup", "e", self.stopr)
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)

        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        self.explode(self.x, self.y)
        if self.explode(self.x, self.y) == True:
            return()
        if self.thrust==1:
            self.vx=.1*cos(self.rotation+1/2*pi)+self.vx
            self.vy=.1*sin(self.rotation-1/2*pi)+self.vy
        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 stopr(self, event):
        self.vr=0

    def clockwise(self, event):
        self.vr=.05

    def cntrclockwise(self, event):
        self.vr=-.05

    def explode(self, x, y):

        if (x<550 and x>450):
            if (y<350 and y>250):
                print("1")
                SpaceGame.explode(x, y)
                self.vr=.5
                self.vx=3
                self.vy=0

                return(True)

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")

        bg1 = Sprite(bg_asset, (0,0))
        bg2 = Sprite(bg_asset, (512,0))
        bg3 = Sprite(bg_asset, (0,512))
        bg4 = Sprite(bg_asset, (512,512))
        bg5 = Sprite(bg_asset, (1024,0))
        bg6 = Sprite(bg_asset, (1024,1024))
        bg7 = Sprite(bg_asset, (1536,1024))
        bg8 = Sprite(bg_asset, (512,512))
        sun((500,300))
        SpaceShip((100,100))

    def explode(xx, yy):
        expl =  ImageAsset("images/explosion1.png")
        ex = Sprite(expl, (xx, yy))

        return()

    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: 3/30/2016 9:16:42 AM<commit_after>"""
spaceshooter.py
Author: Ethan Adner
Credit:
ta presence, n'importe ou, me console. Au cas que ton ceour bat, je suis content
mon amour pour toi est eternel et vivante
sans vous, mes
Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar

tutorial4.py
by E. Dennison
"""

from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import sin, cos, pi

SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 700
"""
xli=[]
for x in range(-25,25):
    xli.append(x+500)
yli=[]
for x in range(-25, 25):
    yli.append(x+300)
"""

class sun(Sprite):

    asset1 = ImageAsset("images/sun.png")
    height = 50
    width = 50

    def __init__(self, position):
        super().__init__(sun.asset1, position)

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", "q", self.clockwise)
        SpaceGame.listenKeyEvent("keyup", "q", self.stopr)
        SpaceGame.listenKeyEvent("keydown", "e", self.cntrclockwise)
        SpaceGame.listenKeyEvent("keyup", "e", self.stopr)
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)

        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        self.explode(self.x, self.y)
        if self.explode(self.x, self.y) == True:
            return()
        if self.thrust==1:
            self.vx=.1*cos(self.rotation+1/2*pi)+self.vx
            self.vy=.1*sin(self.rotation-1/2*pi)+self.vy
        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 stopr(self, event):
        self.vr=0

    def clockwise(self, event):
        self.vr=.05

    def cntrclockwise(self, event):
        self.vr=-.05

    def explode(self, x, y):

        if (x<550 and x>450):
            if (y<350 and y>250):
                print("1")
                SpaceGame.explode(x, y)
                self.vr=.5
                self.vx=10
                self.vy=0

                return(True)

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")

        bg1 = Sprite(bg_asset, (0,0))
        bg2 = Sprite(bg_asset, (512,0))
        bg3 = Sprite(bg_asset, (0,512))
        bg4 = Sprite(bg_asset, (512,512))
        bg5 = Sprite(bg_asset, (1024,0))
        bg6 = Sprite(bg_asset, (1024,1024))
        bg7 = Sprite(bg_asset, (1536,1024))
        bg8 = Sprite(bg_asset, (512,512))
        sun((500,300))
        SpaceShip((100,100))

    def explode(xx, yy):
        expl =  ImageAsset("images/explosion1.png")
        ex = Sprite(expl, (xx, yy))

        return()

    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: 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)
        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(Sunthing)
        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:36:24 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)
        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(Sunthing)
        col1 = self.collidingWithSprites(Spaceship)
        if col or col1:
            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: Nils Kingston
Credit: <list sources used, if any>

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, SoundAsset
import math

SCREEN_WIDTH = 1250
SCREEN_HEIGHT = 600

class Sun(Sprite):

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

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

class SpaceShip(Sprite):

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

    def __init__(self, position, app):
        # vr is change of rotation
        super().__init__(SpaceShip.asset, position)
        self.velocity = 0
        self.rotation = 0
        self.vr = 0
        self.app = app
        self.registerKeys(["a", "d", "w"])

    def step(self):
        self.y -= math.cos(self.rotation) * self.velocity
        self.x -= math.sin(self.rotation) * self.velocity
        self.rotation += self.vr

    def registerKeys(self, keys):
        commands = ["left", "right", "forward"]
        self.keymap = dict(zip(keys, commands))
        [self.app.listenKeyEvent("keydown", k, self.controldown) for k in keys]
        [self.app.listenKeyEvent("keyup", k, self.controlup) for k in keys]

    def controldown(self, event):
        command = self.keymap[event.key]
        if command == "left":
            self.vr = 0.1
        elif command == "right":
            self.vr = -0.1
        elif command == "forward":
            self.velocity = 7

    def controlup(self, event):
        command = self.keymap[event.key]
        if command in ["left", "right"]:
            self.vr = 0
        elif command == "forward":
            self.velocity = 0

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 = 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))
        bg.scale = 2.75
        SpaceShip((100,100), self)
        Sun((600,260))

    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: 4/28/2016 11:30:43 AM<commit_after>"""
spaceshooter.py
Author: Nils Kingston
Credit: <list sources used, if any>

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, SoundAsset
import math

SCREEN_WIDTH = 1250
SCREEN_HEIGHT = 600

class Sun(Sprite):

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

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

class SpaceShip(Sprite):

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

    def __init__(self, position, app):
        # vr is change of rotation
        super().__init__(SpaceShip.asset, position)
        self.velocity = 0
        self.rotation = 0
        self.vr = 0
        self.app = app
        self.registerKeys(["a", "d", "w"])

    def step(self):
        self.y -= math.cos(self.rotation) * self.velocity
        self.x -= math.sin(self.rotation) * self.velocity
        self.rotation += self.vr

    def registerKeys(self, keys):
        commands = ["left", "right", "forward"]
        self.keymap = dict(zip(keys, commands))
        [self.app.listenKeyEvent("keydown", k, self.controldown) for k in keys]
        [self.app.listenKeyEvent("keyup", k, self.controlup) for k in keys]

    def controldown(self, event):
        command = self.keymap[event.key]
        if command == "left":
            self.vr = 0.1
        elif command == "right":
            self.vr = -0.1
        elif command == "forward":
            self.setImage(1)
            self.velocity = 7

    def controlup(self, event):
        command = self.keymap[event.key]
        if command in ["left", "right"]:
            self.vr = 0
        elif command == "forward":
            self.setImage(0)
            self.velocity = 0

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 = 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))
        bg.scale = 2.75
        SpaceShip((100,100), self)
        Sun((600,260))

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

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


<commit_before>import scipy as sp
import scipy.stats
import numpy as np
import math

# univariate tauchen code is taken from dpsolve ( https://bitbucket.org/stevejb/dpsolve )

def tauchen(N, mu, rho, sigma, m=2):
    """
    SJB: This is a port of Martin Floden's 1996 Matlab code to implement Tauchen 1986 Economic Letters method The following comments are Floden's. Finds a Markov chain whose sample paths approximate those of the AR(1) process z(t+1) = (1-rho)*mu + rho * z(t) + eps(t+1) where eps are normal with stddev sigma.

    :param N: scalar, number of nodes for Z
    :param mu: scalar, unconditional mean of process
    :param rho: scalar
    :param sigma: scalar, std. dev. of epsilons
    :param m: max +- std. devs.
    :returns: Z, N*1 vector, nodes for Z. Zprob, N*N matrix, transition probabilities

    Original implementation by Martin Floden Fall 1996. This procedure is an implementation of George Tauchen's algorithm described in Ec. Letters 20 (1986) 177-181.
    """
    Z     = np.zeros((N,1))
    Zprob = np.zeros((N,N))
    a     = (1-rho)*mu

    Z[-1]  = m * math.sqrt(sigma**2 / (1 - (rho**2)))
    Z[0]  = -1 * Z[-1]
    zstep = (Z[-1] - Z[0]) / (N - 1)

    for i in range(1,N):
        Z[i] = Z[0] + zstep * (i)

    Z = Z + a / (1-rho)

    for j in range(0,N):
        for k in range(0,N):
            if k == 0:
                Zprob[j,k] = sp.stats.norm.cdf((Z[0] - a - rho * Z[j] + zstep / 2) / sigma)
            elif k == (N-1):
                Zprob[j,k] = 1 - sp.stats.norm.cdf((Z[-1] - a - rho * Z[j] - zstep / 2) / sigma)
            else:
                up = sp.stats.norm.cdf((Z[k] - a - rho * Z[j] + zstep / 2) / sigma)
                down = sp.stats.norm.cdf( (Z[k] - a - rho * Z[j] - zstep / 2) / sigma)
                Zprob[j,k] = up - down

    return( (Z, Zprob) )

def rouwenhorst(rho, sigma, N):
    """Compute rouwenhorst discretization of a univariate AR1 process by finite markov chain
    :param rho: autocorrelation of the AR1 process
    :param sigma: conditional standard deviation of the AR1 process
    :param N: number of states
    :return [nodes, P]: equally spaced nodes and transition matrix
    """

    from numpy import sqrt, linspace, array,zeros

    p = (rho+1)/2
    q = p
    nu = sqrt( (N-1)/(1-rho**2) )*sigma

    nodes = linspace( -nu, nu, N)
    sig_a = sigma
    n = 1
    #    mat0 = array( [[1]] )
    mat0 = array([[p,1-p],[1-q,q]])
    if N == 2:
        return [nodes,mat0]
    for n in range(3,N+1):
        mat = zeros( (n,n) )
        mat_A = mat.copy()
        mat_B = mat.copy()
        mat_C = mat.copy()
        mat_D = mat.copy()
        mat_A[:-1,:-1] = mat0
        mat_B[:-1,1:] = mat0
        mat_C[1:,:-1] = mat0
        mat_D[1:,1:] = mat0

        mat0 = p*mat_A + (1-p)*mat_B + (1-q)*mat_C + q*mat_D
        mat0[1:-1,:] = mat0[1:-1,:]/2
    P = mat0
    return [nodes, P]

def multidimensional_discretization(rho, sigma, N, method='rouwenhorst', m=2):

    # rho is assumed to be a scalar
    # sigma is a positive symmetric matrix
    # N number of points in each non-degenerate dimension
    # m : standard deviations to approximate

    import scipy.linalg
    from itertools import product

    d = sigma.shape[1]

    L = scipy.linalg.cholesky(sigma)

    if method=='tauchen':
        [nodes_1d, probas_1d] = tauchen(N, 0, rho, 1, m=m)
    elif method=='rouwenhorst':
        [nodes_1d, probas_1d] = rouwenhorst(rho, 1, N)

    markov_nodes = np.array( list( product( *([nodes_1d]*d))) ).T
    markov_indices = np.array( list( product( *([range(N)]*d)  )  ) ).T

    markov_nodes = np.dot(L, markov_nodes)

    transition_matrix = 1
    for i in range(d):
        transition_matrix = np.kron(transition_matrix, probas_1d)

    return [markov_nodes, transition_matrix]

if __name__ == '__main__':
    [Z,Zprob] = tauchen( 5,0,0.8,0.1,1.5 )
    print(Z)
    print(Zprob)

    import numpy
    sigma = numpy.diag([0.1, 0.1])**2
    sigma[0,1]  = numpy.sqrt( 0.5*sigma[0,0]*sigma[1,1] )
    sigma[1,0]  = numpy.sqrt( 0.5*sigma[0,0]*sigma[1,1] )
    rho = 0.9

    [nodes, transition] = multidimensional_discretization(rho, sigma, 3, method='rouwenhorst')

    from matplotlib.pylab import *
    plot(nodes[0,:], nodes[1,:],'o')
    show()
<commit_msg>Added product of markov chains.<commit_after>import scipy as sp
import scipy.stats
import numpy as np
import math

# univariate tauchen code is taken from dpsolve ( https://bitbucket.org/stevejb/dpsolve )

def tauchen(N, mu, rho, sigma, m=2):
    """
    Approximate an AR1 process by a finite markov chain using Tauchen's method.

    :param N: scalar, number of nodes for Z
    :param mu: scalar, unconditional mean of process
    :param rho: scalar
    :param sigma: scalar, std. dev. of epsilons
    :param m: max +- std. devs.
    :returns: Z, N*1 vector, nodes for Z. Zprob, N*N matrix, transition probabilities

    SJB: This is a port of Martin Floden's 1996 Matlab code to implement Tauchen 1986 Economic Letters method The following comments are Floden's. Finds a Markov chain whose sample paths approximate those of the AR(1) process z(t+1) = (1-rho)*mu + rho * z(t) + eps(t+1) where eps are normal with stddev sigma.
    """
    Z     = np.zeros((N,1))
    Zprob = np.zeros((N,N))
    a     = (1-rho)*mu

    Z[-1]  = m * math.sqrt(sigma**2 / (1 - (rho**2)))
    Z[0]  = -1 * Z[-1]
    zstep = (Z[-1] - Z[0]) / (N - 1)

    for i in range(1,N):
        Z[i] = Z[0] + zstep * (i)

    Z = Z + a / (1-rho)

    for j in range(0,N):
        for k in range(0,N):
            if k == 0:
                Zprob[j,k] = sp.stats.norm.cdf((Z[0] - a - rho * Z[j] + zstep / 2) / sigma)
            elif k == (N-1):
                Zprob[j,k] = 1 - sp.stats.norm.cdf((Z[-1] - a - rho * Z[j] - zstep / 2) / sigma)
            else:
                up = sp.stats.norm.cdf((Z[k] - a - rho * Z[j] + zstep / 2) / sigma)
                down = sp.stats.norm.cdf( (Z[k] - a - rho * Z[j] - zstep / 2) / sigma)
                Zprob[j,k] = up - down

    return( (Z, Zprob) )

def rouwenhorst(rho, sigma, N):
    """
    Approximate an AR1 process by a finite markov chain using Rouwenhorst's method.

    :param rho: autocorrelation of the AR1 process
    :param sigma: conditional standard deviation of the AR1 process
    :param N: number of states
    :return [nodes, P]: equally spaced nodes and transition matrix
    """

    from numpy import sqrt, linspace, array,zeros

    p = (rho+1)/2
    q = p
    nu = sqrt( (N-1)/(1-rho**2) )*sigma

    nodes = linspace( -nu, nu, N)
    sig_a = sigma
    n = 1
    #    mat0 = array( [[1]] )
    mat0 = array([[p,1-p],[1-q,q]])
    if N == 2:
        return [nodes,mat0]
    for n in range(3,N+1):
        mat = zeros( (n,n) )
        mat_A = mat.copy()
        mat_B = mat.copy()
        mat_C = mat.copy()
        mat_D = mat.copy()
        mat_A[:-1,:-1] = mat0
        mat_B[:-1,1:] = mat0
        mat_C[1:,:-1] = mat0
        mat_D[1:,1:] = mat0

        mat0 = p*mat_A + (1-p)*mat_B + (1-q)*mat_C + q*mat_D
        mat0[1:-1,:] = mat0[1:-1,:]/2
    P = mat0
    return [nodes, P]

def multidimensional_discretization(rho, sigma, N, method='rouwenhorst', m=2):
    """
    Discretize an VAR(1) into a markov chain. The autoregression matrix is supposed to be a scalar.

    :param rho:
    :param sigma:
    :param N:
    :param method:
    :param m:
    :return:
    """

    # rho is assumed to be a scalar
    # sigma is a positive symmetric matrix
    # N number of points in each non-degenerate dimension
    # m : standard deviations to approximate

    import scipy.linalg
    from itertools import product

    d = sigma.shape[1]

    L = scipy.linalg.cholesky(sigma)

    if method=='tauchen':
        [nodes_1d, probas_1d] = tauchen(N, 0, rho, 1, m=m)
    elif method=='rouwenhorst':
        [nodes_1d, probas_1d] = rouwenhorst(rho, 1, N)

    markov_nodes = np.array( list( product( *([nodes_1d]*d))) ).T
    markov_indices = np.array( list( product( *([range(N)]*d)  )  ) ).T

    markov_nodes = np.dot(L, markov_nodes)

    transition_matrix = 1
    for i in range(d):
        transition_matrix = np.kron(transition_matrix, probas_1d)

    return [markov_nodes, transition_matrix]

def tensor_markov( m1, m2 ):
    """Computes the product of two independent markov chains.

    :param m1: a tuple containing the nodes and the transition matrix of the first chain
    :param m2: a tuple containing the nodes and the transition matrix of the second chain
    :return: a tuple containing the nodes and the transition matrix of the product chain
    """

    n1, t1 = m1
    n2, t2 = m2
    t = np.kron(t1, t2)
    p = t1.shape[1]
    q = t2.shape[1]
    n = np.row_stack([
        np.repeat(t1, q, axis=1),
        np.tile( t2, (1,p))
    ])
    return [n,t]

if __name__ == '__main__':
    [Z,Zprob] = tauchen( 5,0,0.8,0.1,1.5 )
    print(Z)
    print(Zprob)

    import numpy
    sigma = numpy.diag([0.1, 0.1])**2
    sigma[0,1]  = numpy.sqrt( 0.5*sigma[0,0]*sigma[1,1] )
    sigma[1,0]  = numpy.sqrt( 0.5*sigma[0,0]*sigma[1,1] )
    rho = 0.9

    [nodes, transition] = multidimensional_discretization(rho, sigma, 2, method='rouwenhorst')

    # from matplotlib.pylab import *
    # plot(nodes[0,:], nodes[1,:],'o')
    # show()

    transition0 = transition.copy()*0
    transition0[1,1] = 1.0

    print(nodes)

    [nodes, transition] = tensor_markov( (nodes, transition0), (nodes, transition) )
    print(nodes)<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: Nils Kingston
Credit: <list sources used, if any>

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 = 1250
SCREEN_HEIGHT = 600

class SpaceShip(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__(SpaceShip.asset, position)

class SpaceGame(App):

    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = RectangleAsset(SCREEN_WIDTH, SCREEN_HEIGHT, noline, black)
        bg = Sprite(bg_asset, (0,0))
        SpaceShip((100,100))

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()<commit_msg>Updated from Brython Server: 4/18/2016 2:54:23 PM<commit_after>"""
spaceshooter.py
Author: Nils Kingston
Credit: <list sources used, if any>

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 = 1250
SCREEN_HEIGHT = 600

class SpaceShip(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__(SpaceShip.asset, position)
        self.vx = 1
        self.vy = 1
        self.vr = 0.01

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr

class SpaceGame(App):

    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = RectangleAsset(SCREEN_WIDTH, SCREEN_HEIGHT, noline, black)
        bg = Sprite(bg_asset, (0,0))
        SpaceShip((100,100))
        SpaceShip((150,150))
        SpaceShip((200,50))

     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: Daniel Wilson
Credit:

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
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.vx = 0
        self.vy = 0
        self.vr = 0.0
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "s", self.UPON)
        SpaceGame.listenKeyEvent("keyup", "s", self.stop)
        SpaceGame.listenKeyEvent("keydown", "w", self.DOWNON)
        SpaceGame.listenKeyEvent("keyup", "w", self.stop)
        SpaceGame.listenKeyEvent("keydown", "a", self.Left)
        SpaceGame.listenKeyEvent("keyup", "a", self.stop)
        SpaceGame.listenKeyEvent("keydown", "d", self.Right)
        SpaceGame.listenKeyEvent("keyup", "d", self.stop)
        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 UPON(self, event):
        self.vy=1
    def DOWNON(self, event):
        self.vy=-1
    def Right(self, event):
        self.vx = 1
    def Left(self, event):
        self.vx = -1
    def stop(self, event):
        self.vy=0
        self.vx=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 = ImageAsset("images/starfield.jpg")
        bg1 = Sprite(bg_asset, (0,0))
        bg2 = Sprite(bg_asset, (512,0))
        SpaceShip((100,100))
        SpaceShip((500,100))

    def step(self):
        step.x += self.vx
        step.y += self.vy
        step.rotation += self.vr

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

def registerKeys(self, keys):
        commands = ["left", "right", "forward", "fire"]
        self.keymap = dict(zip(keys, commands))
        [self.app.listenKeyEvent("keydown", k, self.controldown) for k in keys]
        [self.app.listenKeyEvent("keyup", k, self.controlup) for k in keys]

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()<commit_msg>Updated from Brython Server: 3/22/2016 2:22:26 PM<commit_after>"""
spaceshooter.py
Author: Daniel Wilson
Credit:

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
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.vx = 0
        self.vy = 0
        self.vr = 0.0
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "s", self.UPON)
        SpaceGame.listenKeyEvent("keyup", "s", self.stop)
        SpaceGame.listenKeyEvent("keydown", "w", self.DOWNON)
        SpaceGame.listenKeyEvent("keyup", "w", self.stop)
        SpaceGame.listenKeyEvent("keydown", "a", self.Left)
        SpaceGame.listenKeyEvent("keyup", "a", self.stop)
        SpaceGame.listenKeyEvent("keydown", "d", self.Right)
        SpaceGame.listenKeyEvent("keyup", "d", self.stop)
        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 UPON(self, event):
        self.vy=1
    def DOWNON(self, event):
        self.vy=-1
    def Right(self, event):
        self.vx = 1
    def Left(self, event):
        self.vx = -1
    def stop(self, event):
        self.vy=0
        self.vx=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 = ImageAsset("images/starfield.jpg")
        bg1 = Sprite(bg_asset, (0,0))
        bg2 = Sprite(bg_asset, (700,0))
        SpaceShip((100,100))
        SpaceShip((500,100))

    def step(self):
        step.x += self.vx
        step.y += self.vy
        step.rotation += self.vr

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

def registerKeys(self, keys):
        commands = ["left", "right", "forward", "fire"]
        self.keymap = dict(zip(keys, commands))
        [self.app.listenKeyEvent("keydown", k, self.controldown) for k in keys]
        [self.app.listenKeyEvent("keyup", k, self.controlup) for k in keys]

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


<commit_before>"""
spaceshooter.py
Author: Ethan Adner
Credit:
ta presence, n'importe ou, me console. Au cas que ton ceour bat, je suis content
mon amour pour toi est eternel et vivante
sans vous, mes
Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar

tutorial4.py
by E. Dennison
"""

from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import sin, cos, pi

SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 700
"""
xli=[]
for x in range(-25,25):
    xli.append(x+500)
yli=[]
for x in range(-25, 25):
    yli.append(x+300)
"""

class sun(Sprite):

    asset1 = ImageAsset("images/sun.png")
    height = 50
    width = 50

    def __init__(self, position):
        super().__init__(sun.asset1, position)

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", "q", self.clockwise)
        SpaceGame.listenKeyEvent("keyup", "q", self.stopr)
        SpaceGame.listenKeyEvent("keydown", "e", self.cntrclockwise)
        SpaceGame.listenKeyEvent("keyup", "e", self.stopr)
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)

        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        self.explode(self.x, self.y)
        if self.explode(self.x, self.y) == True:
            return()
        if self.thrust==1:
            self.vx=.1*cos(self.rotation+1/2*pi)+self.vx
            self.vy=.1*sin(self.rotation-1/2*pi)+self.vy
        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 stopr(self, event):
        self.vr=0

    def clockwise(self, event):
        self.vr=.05

    def cntrclockwise(self, event):
        self.vr=-.05

    def explode(self, x, y):

        if (x<550 and x>450):
            if (y<350 and y>250):
                print("1")
                SpaceGame.explode(x, y)
                self.vr=.5
                self.vx=10
                self.vy=0

                return(True)

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")

        bg1 = Sprite(bg_asset, (0,0))
        bg2 = Sprite(bg_asset, (512,0))
        bg3 = Sprite(bg_asset, (0,512))
        bg4 = Sprite(bg_asset, (512,512))
        bg5 = Sprite(bg_asset, (1024,0))
        bg6 = Sprite(bg_asset, (1024,1024))
        bg7 = Sprite(bg_asset, (1536,1024))
        bg8 = Sprite(bg_asset, (512,512))
        sun((500,300))
        SpaceShip((100,100))

    def explode(xx, yy):
        expl =  ImageAsset("images/explosion1.png")
        ex = Sprite(expl, (xx-100, yy))

        return()

    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: 3/30/2016 9:17:24 AM<commit_after>"""
spaceshooter.py
Author: Ethan Adner
Credit:
ta presence, n'importe ou, me console. Au cas que ton ceour bat, je suis content
mon amour pour toi est eternel et vivante
sans vous, mes
Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar

tutorial4.py
by E. Dennison
"""

from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import sin, cos, pi

SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 700
"""
xli=[]
for x in range(-25,25):
    xli.append(x+500)
yli=[]
for x in range(-25, 25):
    yli.append(x+300)
"""

class sun(Sprite):

    asset1 = ImageAsset("images/sun.png")
    height = 50
    width = 50

    def __init__(self, position):
        super().__init__(sun.asset1, position)

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", "q", self.clockwise)
        SpaceGame.listenKeyEvent("keyup", "q", self.stopr)
        SpaceGame.listenKeyEvent("keydown", "e", self.cntrclockwise)
        SpaceGame.listenKeyEvent("keyup", "e", self.stopr)
        SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff)

        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        self.explode(self.x, self.y)
        if self.explode(self.x, self.y) == True:
            return()
        if self.thrust==1:
            self.vx=.1*cos(self.rotation+1/2*pi)+self.vx
            self.vy=.1*sin(self.rotation-1/2*pi)+self.vy
        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 stopr(self, event):
        self.vr=0

    def clockwise(self, event):
        self.vr=.05

    def cntrclockwise(self, event):
        self.vr=-.05

    def explode(self, x, y):

        if (x<550 and x>450):
            if (y<350 and y>250):
                print("1")
                SpaceGame.explode(x, y)
                self.vr=.5
                self.vx=10
                self.vy=0

                return(True)

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")

        bg1 = Sprite(bg_asset, (0,0))
        bg2 = Sprite(bg_asset, (512,0))
        bg3 = Sprite(bg_asset, (0,512))
        bg4 = Sprite(bg_asset, (512,512))
        bg5 = Sprite(bg_asset, (1024,0))
        bg6 = Sprite(bg_asset, (1024,1024))
        bg7 = Sprite(bg_asset, (1536,1024))
        bg8 = Sprite(bg_asset, (512,512))
        sun((500,300))
        SpaceShip((100,100))

    def explode(xx, yy):
        expl =  ImageAsset("images/explosion1.png")
        ex = Sprite(expl, (xx-100, yy-50))

        return()

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

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