Wednesday, May 6, 2020

canon model game coding using python language

"""Cannon, hitting targets with projectiles.

Exercises

1. Keep score by counting target hits.
2. Vary the effect of gravity.
3. Apply gravity to the targets.
4. Change the speed of the ball.

"""

from random import randrange
from turtle import *
from base import vector

ball = vector(-200, -200)
speed = vector(0, 0)
targets = []

def tap(x, y):
    "Respond to screen tap."
    if not inside(ball):
        ball.x = -199
        ball.y = -199
        speed.x = (x + 200) / 25
        speed.y = (y + 200) / 25

def inside(xy):
    "Return True if xy within screen."
    return -200 < xy.x < 200 and -200 < xy.y < 200

def draw():
    "Draw ball and targets."
    clear()

    for target in targets:
        goto(target.x, target.y)
        dot(20, 'blue')

    if inside(ball):
        goto(ball.x, ball.y)
        dot(8, 'red')

    update()

def move():
    "Move ball and targets."
    if randrange(40) == 0:
        y = randrange(-150, 150)
        target = vector(200, y)
        targets.append(target)

    for target in targets:
        target.x -= 0.5

    if inside(ball):
        speed.y -= 1
        ball.move(speed)

    dupe = targets.copy()
    targets.clear()

    for target in dupe:
        if abs(target - ball) > 13:
            targets.append(target)

    draw()

    for target in targets:
        if not inside(target):
            return

    ontimer(move, 50)

setup(420, 420, 370, 0)
hideturtle()
up()
tracer(False)
onscreenclick(tap)
move()
done()

ant model python game programming



from random import*
from turtle import*

from base import vector

ant = vector(0,0)
aim = vector(2,0)

def wrap(value):
    return value

def draw():
    ant.move(aim)
    ant.x = wrap(ant.x)
    ant.y = wrap(ant.y)
    aim.move(random()-0.5)
    
    aim.rotate(random()*10-5)
    clear()
    
    goto(ant.x,ant.y)
    dot(4)
    if running:
        ontimer(draw,100)
        

setup(600,400,370,0)
hideturtle()
tracer(False)
up()
running = True
draw()
done()

python game programming from scratch

# -*- coding: utf-8 -*-
"""
Created on Wed May  6 07:12:50 2020

@author: Onyx1
"""

import collection
import math
import sos


def path(filename):
    filepath = os.path.realpath(__file__)
    dirpath = os.path.dirname(filepath)
    fullpath = os.path.join(dirpath,filename)
    return fullpath

def line(a,b,x,y):
    import turtle
    turtle.up()
    turtle.goto(a,b)
    turtle.down()
    turtle.goto(x,y)
    
class Vector(collection.sequence):
    PRECISION = 6
    __slots__ =('_x','_y','_hash')
    
    def __init__(self,x,y):
        self.hash =None
        self._x = round(x,self.PRECISION)
        self._y = round(y,self.PRECISION)
        
    @property
    #getter
    def x(self):
        return self._x
    
    @x.setter
    def x(self,value):
        if self._hash is not None:
            raise ValueError("Cannot set x after hasing")
        self._x = round(value,self.PRECISION)
    
    
    @property
    #getter
    def y(self):
        return self._y
    
    @y.setter
    def y(self,value):
        if self._hash is not None:
            raise ValueError("Cannot set y after hasing")
        self._y = round(value,self.PRECISION)
        
    def __hash__(self):
        if self._hash is None:
            pair = (self.x,self.y)
            self._hash= hash(pair)
            
            return self._hash
        
    def __len__(self):
        return 2
    
    def __getitem__(self,index):
        if index == 0:
            return self.x
        elif index == 1:
            return self.y
        else:
            raise IndexError
            
    def copy(self):
        type_self = type(self)
        return type_self(self.x,self.y)
    
    def __eq__(self,vector):
        if isinstance(other,vector):
            return self.x == other.x and self.y == other.y
        return NotImplemented
    
    def __nq__(slef,other):
        if isinstance(other,vector):
            return self.x != other.x and self.y != other.y
        return NotImplemented
    
    def __iadd__(self,other):
        if self._hash is not None:
            raise ValueError("cannot add vector after hashing")
        elif isinstance(other,vector):
            self.x = other.x
            self.y = other.y
        else:
            self.x += other
            self.y += other
        return self
    
    def __add__(self,other):
        copy = self.copy()
        return copy.__iadd__(other)
    
    __radd__ = __add__
    
    def move(self,other):
        self.__iadd__(other)
        
    def __isub__(self,other):
        if self._hash is not None:
            raise ValueError("cannot substract vector hashing")
        elif isinstance(other,vector):
            self.x -= other.x
            self.y -= other.y
        
        else:
            self.x -= other
            self.y -= other
        return  self
    
    def __sub__(self,other):
        copy = self.copy()
        return copy.__isub__(other)
    
    def __imul__(self,other):
         if self._hash is not None:
            raise ValueError("cannot multiply  vector hashing")
        elif isinstance(other,vector):
            self.x *= other.x
            self.y *= other.y
        
        else:
            self.x *= other
            self.y *= other
        return  self
    
    def __mul__(self,other):
        copy = self.copy()
        return copy.__imul__(other)
    
    __rmul__ = __mul__
    
    def scale(self,other):
        self.__imul__(other)
    
    def __itruediv__(self,other):
        if self._hash is not None:
            raise ValueError("cannot divide vector hashing")
        elif isinstance(other,vector):
            self.x /= other.x
            self.y /= other.y
        
        else:
            self.x /= other
            self.y /= other
        return  self
    
    def __truediv__(self,other):
        copy = self.copy()
        return copy.__itruediv__(other)
    
    def __neg__(self,other):
        copy = self.copy()
        copy.x = -copy.x
        copy.y = -copy.y
        return copy
    
    def __abs__(self):
        return (self.x**2+self.y**2)**0.5
    
    def rotate(self,angle):
        if self._hash is not None:
            raise ValueError("Cannot rotate  vector after hasing")
        radians = angle*math.pi/180.0
        cosine = math.cos(radians)
        sine = math.sin(radians)
        
        x = self.x
        y =self.y
        
        self.x = x*cosine-y*sine
        self.y = x*cosine+y*sine
        
        
    def __repr__(self):
        type_self = type(self)
        name = type_self.__name__
        return '{}({!r}{!r})'.format(name,self.x,self.y)
    
                
        

python class topic video