<file_sep>pygame.mixer.set_reserved(2) 
reserved_channel_0 = pygame.mixer.Channel(0) 
reserved_channel_1 = pygame.mixer.Channel(1)
<file_sep>    def read_mtllib(self, mtl_fname):

        file_mtllib = open(mtl_fname)
        for line in file_mtllib:

            words = line.split()
            command = words[0]
            data = words[1:]

            if command == 'newmtl':
                material = Material()
                material.name = data[0]
                self.materials[data[0]] = material

            elif command == 'map_Kd':
                material.texture_fname = data[0]
<file_sep>from enum import Enum, auto
import time

class States(Enum):
    IDLE = auto()
    STARTING = auto()
    RUNNING = auto()
    STOPING = auto()
    ERROR = auto()

class StateObject:
    def __init__(self):
        self.__state = States.IDLE

    def set_state(self, state):
        self.__state = state

    def get_state(self):
        return self.__state

class Entity(StateObject):
    def __init__(self):
        super().__init__()
        self.__counter = 0

    def inc_counter(self):
        self.__counter += 1

    def sub_counter(self):
        self.__counter -= 1

    def get_counter(self):
        return self.__counter

    def set_counter(self, counter):
        self.__counter = counter

SM1 = Entity()
SM1.set_state(States.IDLE)

SM2 = Entity()
SM2.set_state(States.IDLE)

while True:

    #if we are in IDLE state, ask user for statemachine run
    if SM1.get_state() == States.IDLE:
        user_input = input("goto RUNNING=ok, goto ERRROR=nok, quit=q")
        print("-----------------------------------------")

        if user_input == "ok":
            SM1.set_state(States.RUNNING)
            SM1.set_counter(5)
        elif user_input == "nok":
            SM1.set_state(States.ERROR)
            SM1.set_counter(10)
        elif user_input == "q":
            break

    if SM1.get_state() == States.RUNNING:
        SM1.sub_counter()
        print(SM1.get_counter())
        time.sleep(1) #slow running state
        if SM1.get_counter() <= 0:
            SM1.set_state(States.IDLE)

    if SM1.get_state() == States.ERROR:
        SM1.sub_counter()
        print(SM1.get_counter())
        time.sleep(0.1) #slow running state
        if SM1.get_counter() <= 0:
            SM1.set_state(States.IDLE)

print("Statemachine stopped")<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 20:29:39 2020

@author: crtom

https://www.youtube.com/watch?v=3UxnelT9aCo
"""

# Pathfinding - Part 1
# Graphs
# KidsCanCode 2017
import pygame as pg
from sys import exit

vec = pg.math.Vector2

TILESIZE = 48
GRIDWIDTH = 28
GRIDHEIGHT = 15
WIDTH = TILESIZE * GRIDWIDTH
HEIGHT = TILESIZE * GRIDHEIGHT
FPS = 30
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
YELLOW = (255, 255, 0)
DARKGRAY = (40, 40, 40)
LIGHTGRAY = (140, 140, 140)

pg.init()
screen = pg.display.set_mode((WIDTH, HEIGHT))
clock = pg.time.Clock()

class SquareGrid:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.walls = []
        self.connections = [vec(1, 0), vec(-1, 0), vec(0, 1), vec(0, -1)]

    def in_bounds(self, node):
        return 0 <= node.x < self.width and 0 <= node.y < self.height

    def passable(self, node):
        return node not in self.walls

    def find_neighbors(self, node):
        neighbors = [node + connection for connection in self.connections]
        neighbors = filter(self.in_bounds, neighbors)
        neighbors = filter(self.passable, neighbors)
        return neighbors

    def draw(self):
        for wall in self.walls:
            rect = pg.Rect(wall * TILESIZE, (TILESIZE, TILESIZE))
            pg.draw.rect(screen, LIGHTGRAY, rect)

def draw_grid():
    for x in range(0, WIDTH, TILESIZE):
        pg.draw.line(screen, LIGHTGRAY, (x, 0), (x, HEIGHT))
    for y in range(0, HEIGHT, TILESIZE):
        pg.draw.line(screen, LIGHTGRAY, (0, y), (WIDTH, y))

g = SquareGrid(GRIDWIDTH, GRIDHEIGHT)
walls = [(10, 7), (11, 7), (12, 7), (13, 7), (14, 7), (15, 7), (16, 7), (7, 7), (6, 7), (5, 7), (5, 5), (5, 6), (1, 6), (2, 6), (3, 6), (5, 10), (5, 11), (5, 12), (5, 9), (5, 8), (12, 8), (12, 9), (12, 10), (12, 11), (15, 14), (15, 13), (15, 12), (15, 11), (15, 10), (17, 7), (18, 7), (21, 7), (21, 6), (21, 5), (21, 4), (21, 3), (22, 5), (23, 5), (24, 5), (25, 5), (18, 10), (20, 10), (19, 10), (21, 10), (22, 10), (23, 10), (14, 4), (14, 5), (14, 6), (14, 0), (14, 1), (9, 2), (9, 1), (7, 3), (8, 3), (10, 3), (9, 3), (11, 3), (2, 5), (2, 4), (2, 3), (2, 2), (2, 0), (2, 1), (0, 11), (1, 11), (2, 11), (21, 2), (20, 11), (20, 12), (23, 13), (23, 14), (24, 10), (25, 10), (6, 12), (7, 12), (10, 12), (11, 12), (12, 12), (5, 3), (6, 3), (5, 4)]
for wall in walls:
    g.walls.append(vec(wall))
running = True
while running:
    clock.tick(FPS)
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                running = False
            if event.key == pg.K_m:
                # dump the wall list for saving
                print([(int(loc.x), int(loc.y)) for loc in g.walls])
        if event.type == pg.MOUSEBUTTONDOWN:
            mpos = vec(pg.mouse.get_pos()) // TILESIZE
            if event.button == 1:
                if mpos in g.walls:
                    g.walls.remove(mpos)
                else:
                    g.walls.append(mpos)

    pg.display.set_caption("{:.2f}".format(clock.get_fps()))
    screen.fill(DARKGRAY)
    draw_grid()
    g.draw()
    pg.display.flip()

pg.quit()
exit()<file_sep>import pygame
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2

picture_file = 'map.png'

pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)

picture = pygame.image.load(picture_file).convert()
picture_pos = Vector2(0, 0)
scroll_speed = 1000.

clock = pygame.time.Clock()

joystick = None
if pygame.joystick.get_count() > 0:
    joystick = pygame.joystick.Joystick(0)
    joystick.init()

if joystick is None:
    print("Sorry, you need a joystick for this!")
    pygame.quit()
    exit()


while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()

    scroll_direction = Vector2(*joystick.get_hat(0))
    scroll_direction.normalize()

    screen.fill((255, 255, 255))
    screen.blit(picture, (-picture_pos.x, picture_pos.y))

    time_passed = clock.tick()
    time_passed_seconds = time_passed / 1000.0

    picture_pos += scroll_direction * scroll_speed * time_passed_seconds 

    pygame.display.update()
<file_sep>"""
Game Template

Attributes:
    g (TYPE): Description
"""

import pygame as pg # rename for fast typing
import random
from settings import *

class Game:

	"""Summary
	
	Attributes:
	    all_sprites (TYPE): Description
	    clock (TYPE): Description
	    playing (bool): Description
	    running (bool): Description
	    screen (TYPE): Description
	"""

	def __init__(self):
		"""initialize game window, etc
		"""
		pg.init()
		pg.mixer.init()
		self.screen = pg.display.set_mode((WIDTH, HEIGHT))
		pg.display.set_caption("My Game")
		self.clock = pg.time.Clock()
		self.running = True

	def new(self):
		"""Start a New Game
		"""
		self.all_sprites = pg.sprite.Group()

	def run(self):
		"""Game Loop
		"""
		self.playing = True
		while  self.playing:
			self.clock.tick(FPS) # keep looping at the right speed
			self.events()
			self.update()
			self.draw()

	def update(self):
		"""Game Loop - Update
		"""
		self.all_sprites.update()


	def events(self):
		"""Game Loop - events
		"""
		for event in pg.event.get():
			#check for closing window
			if (event.type == pg.QUIT) or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):
				if self.playing:
					self.playing = False
				self.running = False

	def draw(self):
		"""Game Loop - draw
		"""
		self.screen.fill(BLACK)
		self.all_sprites.draw(self.screen)
		pg.display.flip() # after drawing everything, flip the display

	def show_start_screen(self):
		"""game splash/start screen
		"""
		print("game start")
		pass

	def show_go_screen(self):
		"""game over/continue screen
		"""
		print("game end")
		pass

g = Game() # instance of game object
g.show_start_screen()
while g.running:
	g.new()
	g.run()
	g.show_go_screen()

pg.quit()

<file_sep>class StateMachine(object):

  def __init__(self):

      self.states = {} 	# Stores the states
      self.active_state = None  # The currently active state

  def add_state(self, state):

      # Add a state to the internal dictionary
      self.states[state.name] = state

  def think(self):

     # Only continue if there is an active state
     if self.active_state is None:
         return

     # Perform the actions of the active state, and check conditions
     self.active_state.do_actions()

     new_state_name = self.active_state.check_conditions()
     if new_state_name is not None:
         self.set_state(new_state_name)
 
  def set_state(self, new_state_name):

      # Change states and perform any exit / entry actions
      if self.active_state is not None:
          self.active_state.exit_actions()

      self.active_state = self.states[new_state_name]
      self.active_state.entry_actions()
<file_sep>from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
from pygame.locals import *

screen = pygame.display.set_mode((640, 480), HWSURFACE|DOUBLEBUF|OPENGL)

def resize(width, height):
    glViewport(0, 0, width, height) 
    glMatrixMode(GL_PROJECTION) 
    glLoadIdentity()
    gluPerspective(60, float(width)/height, 1, 10000)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()


def init():

    glEnable(GL_DEPTH_TEST)
    glClearColor(1.0, 1.0, 1.0, 0.0)

    glShadeModel(GL_FLAT)
    glEnable(GL_COLOR_MATERIAL)

    glEnable(GL_LIGHTING)
    glEnable(GL_LIGHT0)
    glLight(GL_LIGHT0, GL_POSITION, (0, 1, 1, 0))
<file_sep>import pygame

pygame.init()


#---------display-------------
display_width = 800
display_height = 600
#color var
black = (0,0,0)
white = (255,255,255)
red   = (255,0,0)
green = (0,255,0)
blue  = (0,0,255)

gameDisplay = pygame.display.set_mode((display_width,display_height))
#set title
pygame.display.set_caption('Race Game')

clock = pygame.time.Clock()

carImg = pygame.image.load('race_car_transp_v2.png')

#function to display a car
def car(x,y):
	gameDisplay.blit(carImg,(x,y)) #we blit car image to a surface

x = display_width*0.45
y = display_height*0.8
#for computers (x=0,y=0) is top left corner

#------------main game loop---------
x_change = 0
chrashed = False
while not chrashed:

	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			chrashed = True

			#if key pressed start moving
		if event.type == pygame.KEYDOWN:
		    if event.key == pygame.K_LEFT:
		    	x_change = -5
		    elif event.key == pygame.K_RIGHT:
		    	x_change = 5

			#if key released stop moving
		if event.type == pygame.KEYUP:
		    if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
		    	x_change = 0

	x += x_change

	#------------------------------------
	#first draw background, dont paint over car
	gameDisplay.fill(white)	
	car(x,y)
	pygame.display.update()

	clock.tick(60)	
#------------------------------------
pygame.quit()
quit()<file_sep>"""
Animation Spritesheet
- picture size 32*640
- 10 pictures
- 2 rows by 5 pictures

Main goal:
- cutting subpictures out of a single spritesheet image
#-------------------------------------------------
picture idexes
0, 1, 2, 3, 4,
5, 6, 7, 8, 9,

picture column, row position
(0,0) (1,0) (2,0) (3,0) (4,0)
(0,1) (1,1) (2,1) (3,1) (4,1)

picture column, row pixel position
(0,0) (32,0) (64,0) (96,0) (128,0)
(0,32) (32,32) (64,32) (96,32) (128,32)
#--------------------------------------------------
HANDLES = are used for easy picture offsets
     	-
    8 	7   6
     	-
  --5---4---3---
	 	-
	2 	1   0
	 	-

index offset
  0	  (0,0)
  1	  (-hw,0)
  2   (-w,0)
  3   (0,-hh)
  4   (-hw,-hh)	#image is centralized
  5   (-w,-hh)
  6   (0,-h)
  7   (-hw,-h)
  8   (w,-h)
"""

import math,random,sys
import pygame
from pygame.locals import *

#esit the program
def events():
	for event in pygame.event.get():
		if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
			pygame.quit()
			sys.exit()

#define display surface
W,H = 320,320
HW, HH = W//2, H//2
AREA = W*H

#initialize display
pygame.init()
CLOCK = pygame.time.Clock()
DS = pygame.display.set_mode((W,H))
pygame.display.set_caption("sprite sheets")
FPS = 1

#define colours
BLACK = (0,0,0)
WHITE = (255,255,255)
background = pygame.image.load('background.png').convert_alpha()
#--------------------------------------

class spritesheet:
	def __init__(self, filename,cols,rows):
		self.sheet = pygame.image.load(filename).convert_alpha()

		self.cols =cols
		self.rows = rows
		self.totalCellCount = cols*rows
		#print(f'self.totalCellCount {self.totalCellCount}') OK

		self.rect = self.sheet.get_rect()	#calling this function gives use rect width
		#cell width
		w = self.cellWidth = self.rect.width // cols
		h = self.cellHeight = self.rect.height // rows
		hw,hh = self.cellCenter = (w//2,h//2)

		#print(f'self.rect.width{self.rect.width} self.rect.height:{self.rect.height}') OK

		#print(f'w={w}, h={h}')
		#print(f'hw={hw}, hh={hh}')

		#build a list of cells. We need every cell x and y in pixels
		#1.) build list of indexes and than multiply those indexes by pixel size
		self.cells = list([(index%cols*w,index//cols*h,w,h) for index in range(self.totalCellCount)])
		self.handle = list([(0,0),(-hw,0),(-w,0),(0,-hh),(-hw,-hh),(-w,-hh),(0,-h),(-hw,-h),(w,-h)])

	def draw(self, surface, cellIndex, x, y, handle):
		surface.blit(self.sheet,(x+self.handle[handle][0],y+self.handle[handle][1]),self.cells[cellIndex])

	#----------------------------------------
s = spritesheet(filename="moon_phase_64x320_v1.png",cols=10,rows=2)
CENTER_HANDLE = 4
index = 0

#main loop
print (s.handle)
while True:
	events()
	#draw spritesheet
	#DS.fill(BLACK)
	DS.blit(background, (0,0))
	s.draw(DS, index% s.totalCellCount, HW//2,HH//2,CENTER_HANDLE)
	index += 1
	pygame.draw.circle(DS,WHITE,(HW,HH),2,0)
	pygame.display.update()
	CLOCK.tick(FPS)
	DS.fill(WHITE)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 23:13:08 2020

@author: crtom
"""

import pygame as pg
from settings import *

class Player(pg.sprite.Sprite):
    def __init__(self, game, x, y):
       
        # so player can acces all sprites in the game
        self.game = game
        self.groups = game.all_sprites
        
        # 1.) sprite class default override:
        #Call the parent class (Sprite) constructor
        pg.sprite.Sprite.__init__(self, self.groups)

        # 2.) sprite class default override:
        # tile based game - player is only one tile large
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill(YELLOW)
        
        # 3.) sprite class default override:
        # Fetch the rectangle object that has the dimensions of the image
        # Update the position of this object by setting the values of rect.x and rect.y       
        self.rect = self.image.get_rect()
        #self.rect.center = (WIDTH // 2, HEIGHT // 2)
        
        # CUSTOM ATTRIBUTES
        self.x = x * TILESIZE
        self.y = y * TILESIZE
        # delta time, game loop time
        #self.dt = 0
        self.vx, self.vy = 0, 0

        # position vector
        #self.position =  Vector2(100.0, 100.0)
        # direction vector
        #self.direction = Vector2(0, 0)  
        # movement speed
        #self.speed = 300.        
    
    def get_keys(self):
        self.vx, self.vy = 0, 0
        
        keys = pg.key.get_pressed()
        
        if keys[pg.K_LEFT] or keys[pg.K_a]:
            # self.player.move(dx=-1)
            self.vx = -PLAYER_SPEED
        elif keys[pg.K_RIGHT] or keys[pg.K_d]: # IF ENABLES DIAG
            self.vx = PLAYER_SPEED
        if keys[pg.K_UP] or keys[pg.K_w]: # IF ENABLES DIAG
            self.vy = -PLAYER_SPEED
        if keys[pg.K_DOWN] or keys[pg.K_s]: # IF ENABLES DIAG
            self.vy = PLAYER_SPEED
        
        # DIAGONAL PITAGORA
        if self.vx != 0 and self.vy != 0:
            self.vx *= 0.7071
            self.vy *= 0.7071
    
    #def set_time_passed_sec(self, dt):
    #    self.dt_sec = dt / 1000.0
    # def move(self, dx=0, dy=0):
    #     # only move if not colliding with walls
    #     if not self.collide_with_walls(dx, dy):
    #         self.x += dx
    #         self.y += dy
    
    # def collide_with_walls(self, dx = 0, dy = 0):
    #     # OLD collision check
    #     # loop trough the wall group and check
    #     for wall in self.game.walls:
    #         if wall.x == self.x + dx and wall.y == self.y + dy:
    #             # yes we did collide
    #             return True
    #     #no we didnt collide with wall
    #     return False
    def collide_with_walls(self, direction):
        # x collision check
        if direction == 'x':
            hits = pg.sprite.spritecollide(self, self.game.walls, False) # false= dont delete the wall
            
            if hits:
                # sprite was moving to the right
                # we need to put the sprite to the left edge of the wall
                if self.vx > 0: 
                    self.x = hits[0].rect.left - self.rect.width
                # sprite was moving to the left
                # we need to put the sprite to the right edge of the wall
                if self.vx < 0:
                    self.x = hits[0].rect.right #- self.rect.width    
                
                # we run into the wall, x velocity = 0
                self.vx = 0
                # update new position
                self.rect.x = self.x

        if direction == 'y':
            hits = pg.sprite.spritecollide(self, self.game.walls, False) # false= dont delete the wall
            
            if hits:
                # sprite was moving down
                # we need to put the sprite to the top of the wall
                if self.vy > 0: 
                    self.y = hits[0].rect.top - self.rect.height
                # sprite was moving to the top
                # we need to put the sprite to the bottom edge of the wall
                if self.vy < 0:
                    self.y = hits[0].rect.bottom #- self.rect.width    
                
                # we run into the wall, x velocity = 0
                self.vy = 0
                # update new position
                self.rect.y = self.y
                    
    def update(self):
        self.get_keys()
        # # set sprite rectangle position
        # self.rect.x = self.x * TILESIZE
        # self.rect.y = self.y * TILESIZE
        # this will make movement independant of frame rate
        self.x += self.vx * self.game.dt # get dt from game object
        self.y += self.vy * self.game.dt # get dt from game object
        # self.rect.topleft = (self.x, self.y)
        
        self.rect.x = self.x
        self.collide_with_walls('x')
        
        self.rect.y = self.y
        self.collide_with_walls('y')
        # check if sprite and a group collides
        # # if hits a wall dont move
        # # redo movement position
        # if pg.sprite.spritecollideany(self, self.game.walls):
        #     self.x -= self.vx * self.game.dt # get dt from game object
        #     self.y -= self.vy * self.game.dt # get dt from game object
        #     # self.rect.x = self.x * TILESIZE
        #     # self.rect.y = self.y * TILESIZE
        #     self.rect.topleft = (self.x, self.y)

class Wall(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        
        # so player can acces all sprites in the game
        # member of all sprites group
        # member of all walls group
        self.groups = game.all_sprites, game.walls
        
        pg.sprite.Sprite.__init__(self, self.groups)
        
        self.game = game
        # tile based game - player is only one tile large
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y
        
        self.rect.x = x * TILESIZE
        self.rect.y = y * TILESIZE<file_sep>import pygame

pygame.init()

gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('a bit racey')

clock = pygame.time.Clock()

chrashed = False
while not chrashed:

	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			chrashed = True

		print(event)

	pygame.display.update()

	clock.tick(60)¸#frames per second

pygame.quit()
quit()<file_sep># -*- coding: utf-8 -*-
"""
http://inventwithpython.com/pygame/

Created on Tue Dec 15 18:09:41 2020

@author: crtom

- BASIC ARHITECTURE, get mouse coordinates

#------------------------------------------------------------------------------
    #--------------------------------------------------------------------------
        #----------------------------------------------------------------------
            #------------------------------------------------------------------
                #--------------------------------------------------------------
"""

import pygame
import sys

from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT

#--------------------------------------------------------------------------
#-------------------------constants----------------------------------------
#--------------------------------------------------------------------------

FPS = 30
WIN_W = 600
WIN_H = 600 
""" grid calculations
 GRID = 600*600
 GRID 6x6 = 36 pieces
 100x100 per square
 one piece is 80x80 + margin = 100x100
"""
MARGIN_L = 10
BOX_L = 80

#REVEALSPEED = 8

#GAPSIZE = 10
BOARD_W = 6
BOARD_H = 6

# check
#assert(BOARDWIDTH*BOARDHEIGHT) % 2 == 0, 'Board needs to have an even number of boxes for pairs of matches'

#XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE + GAPSIZE))) / 2)
#YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE))) / 2)

# COLORS  ( R ,  G ,  B )
WHITE   = (255, 255, 255)
BLACK   = (  0,   0,   0)
GREY    = (128, 128, 128)
SILVER  = (192, 192, 192)

RED     = (255,   0,   0)
YELLOW  = (255, 255,   0)
ORANGE  = (255, 128,   0)
MAGENTA = (255,   0, 255)
PURPLE  = (128,   0, 128)

LIME    = (  0, 255,   0)
BLUE    = (  0,   0, 255)
NAVYBLUE= ( 60,  60, 100)
CYAN    = (  0, 255, 255)
GRAY	= (128, 128, 128)
MAROON  = (128,   0,   0)
OLIVE   = (128, 128,   0)
GREEN   = (  0, 128,   0)
TEAL    = (  0, 128, 128)
NAVY    = (  0,   0, 128)


BGCOLOR = NAVYBLUE
LIGHTBGCOLOR = GRAY
BOXCOLOR = WHITE
HIGHLIGHTCOLOR = BLUE

LINE = 'line'
DONUT = 'donut'
SQUARE = 'square'
DIAMOND = 'diamond' 
LINES = 'lines'
OVAL = 'oval'


#ALLCOLORS = (RED, GREEN, BLUE, YELLOW, ORANGE, PURPLE, CYAN)
#ALLSHAPES = (LINE, DONUT, SQUARE, DIAMOND, LINES, OVAL)

#assert len(ALLCOLORS) * len(ALLSHAPES) * 2 <= BOARDWIDTH * BOARDHEIGHT,'Board is too big for the number of shapes/colors defined.'

# create a list of touple positions
grid_touple_lst = []
for y in range(0, 6):
    for x in range(0, 6):
        grid_touple_lst.append((x,y))

grid_pixel_pos_list = []
card_position_list = []
for x in range(0, 600, 100):
    for y in range(0, 600, 100):
        grid_pixel_pos_list.append((x, y))
        card_position_list.append((x + 10, y + 10))

print(grid_pixel_pos_list)
print(card_position_list)

#--------------------------BACKGROUND--------------------------------------
def draw_background():
    background = pygame.Surface(DISPLAYSURF.get_size())
    ts, w, h, c1, c2 = 100, *DISPLAYSURF.get_size(), (160, 160, 160), (192, 192, 192)
    tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]

    for rect, color in tiles:
        pygame.draw.rect(background, color, rect)

    DISPLAYSURF.blit(background, (0, 0))    

#----------card-----------
# 36 tiles
cards = []
for i in range(36):
    
    position = card_position_list[i]
    rectangle = [position[1], position[0], 80, 80]
    surface = pygame.Surface((80,80))
    state = 'closed' #opened
    glow = False
    
    dictionary = {'card_n': i,
                  'position': position,
                  'surface': surface,
                  'rectangle': rectangle,
                  'glow': glow,
                  'state': state
                  }
    
    cards.append(dictionary)
    print(dictionary)

def draw_cards():
    
    for card in cards:
        #pygame.draw.rect(DISPLAYSURF, GREY, [0, 1, 20, 30], 0)
        pygame.draw.rect(DISPLAYSURF, BLACK, card['rectangle'], 0)
        
        if card['glow'] == True:
            pass
            

def draw_rect_alpha(surface, color, rect):
    shape_surf = pygame.Surface(pygame.Rect(rect).size, pygame.SRCALPHA)
    pygame.draw.rect(shape_surf, color, shape_surf.get_rect())
    surface.blit(shape_surf, rect)
#------------------------------------------------------------------------------
#----------------------------main loop-----------------------------------------
#------------------------------------------------------------------------------
def main():
    
    # global variables
    global FPSCLOCK, DISPLAYSURF
    
    # for positions
    position_pixel = (None, None)
    position_grid = (None, None)
    position_box = None
    
    # for user events
    mouseMoved = False
    mouseClicked = False
    #--------------------------------------------------------------------------
    # init pygame
    pygame.init()
    
    FPSCLOCK = pygame.time.Clock() # initialize clock
    
    DISPLAYSURF = pygame.display.set_mode((WIN_W, WIN_H)) # initialize surface
    
    pygame.display.set_caption('Memory Game')

    #---------------------------------------------------------
    #DISPLAYSURF.fill(BGCOLOR)
    draw_background()

    draw_cards()
    
    #--------------------------------------------------------------------------
    #-------------------------GAME loop----------------------------------------
    #--------------------------------------------------------------------------
    while True:
        
        #----------------------event handling---------------------------------
        for event in pygame.event.get():
            
            # event objects have type attribute
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            elif event.type == MOUSEMOTION:
                position_pixel = event.pos
                mouseMoved = True
                #print('mouse moved')

            elif event.type == MOUSEBUTTONUP:
                # mouse click position is in pixels
                position_pixel = event.pos
                # set click is true for functions
                mouseCicked = True
                #print('mouse clicked')
        #---------------------------------------------------------------------
        # if mouse moved than highlight box
        if mouseMoved:
            # window pixels to game grid 
            position_grid = pixel_pos_to_game_grid(position_pixel)
            # game grid to box number
            position_box = game_grid_to_touple_pos(position_grid)
            
            print('position_pixel = ', position_pixel)
            print('position_grid = ', position_grid)
            print('position_box = ', position_box)
            
            glow_card(position_box)
            
            # reset event flag
            mouseMoved = False
        #---------------------------------------------------------------------
        if mouseClicked:
            mouseClicked = False
            
            show_card(position_box)
        
        update_cards()
        #------------------------timing----------------------------------------
        # draws surface object stored in DISPLAYSURF
        #pygame.display.update()
        pygame.display.flip()
        FPSCLOCK.tick(FPS)
    
#------------------------------------------------------------------------------
#-------------------------function definitions---------------------------------
#------------------------------------------------------------------------------
def update_cards():
    global cards
    
    for card in cards:
       
        # if card is selected, glow sides
        if card['glow'] == True:
            pygame.draw.rect(DISPLAYSURF, BLUE, card['rectangle'], 0)
        else:
           pygame.draw.rect(DISPLAYSURF, BLACK, card['rectangle'], 0)

def show_card():
    global cards
    pass
 
    
def glow_card(position_box):
    global cards
   
    for i, card in enumerate(cards):
        # set highlight selected card
        if i == position_box: 
            card['glow'] = True
            #print() # = cards[position_box]
            #pygame.draw.rect(DISPLAYSURF, GREY, [0, 1, 20, 30], 0)
            #pygame.draw.rect(DISPLAYSURF, BLUE, card['rectangle'], 5)
            # clear highlight on other cards
            pass
        else:
            card['glow'] = False
            pass
            


def pixel_pos_to_game_grid(touple_pixel):
    """
    Parameters
    ----------
    touple_pixel : touple
        position in pixels coordinates.

    Returns
    -------
    touple_grid : touple
        position in game grid coordinates.
    """

    x_grid = touple_pixel[0] // 100 # integere division
    y_grid = touple_pixel[1] // 100
    touple_grid = (x_grid, y_grid)

    return touple_grid

def game_grid_to_touple_pos(touple_grid):
    """
    Parameters
    ----------
    mytouple : touple
        position in game grid coordinates.

    Returns
    -------
    position_box : number
        list index from grid_touple_lst
    """

    box_n = None
    for i, touple in enumerate(grid_touple_lst):
        if touple_grid == touple:
            position_box = i
    
    return position_box
  

def drawHighlightBox(boxx, boxy):
    left, top = leftTopCoordsOfBox(boxx, boxy)
    pygame.draw.rect(DISPLAYSURF, HIGHLIGHTCOLOR, (left - 5, top - 5, BOXSIZE + 10, BOXSIZE + 10), 4)

def change_box_state(grid_nx, grid_ny):
    global state_lst
    
    
    
    # for state in state_lst:
    #     # if back, turn to front
    #     if state == 'front':
    #         pygame.draw.rect(DISPLAYSURF, WHITE, (x, y, 80, 80))
    #     # if front, turn to back
    #     else:
    #         pygame.draw.rect(DISPLAYSURF, RED, (x, y, 80, 80))



def leftTopCoordsOfBox(boxx, boxy):
    # Convert board coordinates to pixel coordinates
    left = boxx * (BOXSIZE + GAPSIZE) + XMARGIN
    top = boxy * (BOXSIZE + GAPSIZE) + YMARGIN
    return (left, top)    
#------------------------------------------------------------------------------
#-------------------------Start application------------------------------------
#------------------------------------------------------------------------------        
if __name__ == '__main__':
    main()<file_sep>import pygame
from grid import Grid

import os
os.environ['SDL_VIDEO_WINDOW_POS'] = '400,100'


surface = pygame.display.set_mode((600,600))
pygame.display.set_caption('Tic-tac-toe')

grid = Grid()


running = True
player = "X"

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN and not grid.game_over:
            if pygame.mouse.get_pressed()[0]:
                pos = pygame.mouse.get_pos()
                grid.get_mouse(pos[0] // 200, pos[1] // 200, player)
                if grid.switch_player:
                    if player == "X":
                        player = "O"
                    else:
                        player = "X"
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and grid.game_over:
                grid.clear_grid()
                grid.game_over = False
            elif event.key == pygame.K_ESCAPE:
                running = False


    surface.fill((0,0,0))

    grid.draw(surface)

    pygame.display.flip()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 20:46:32 2020

@author: crtom
"""


import pygame
import sys
import random

from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT

import time
pygame.init() 

screen = pygame.display.set_mode((300, 300)) 
s_r = screen.get_rect()
player = pygame.Rect((100, 100, 50, 50))
timer = pygame.time.Clock()
flash = 0
grow = True
color = pygame.color.Color('Black')

E_OUTSIDE = pygame.USEREVENT  + 1
E_MOUSE   = pygame.USEREVENT  + 2

conditions = [ # blink if player is outside screen
              (lambda: not s_r.contains(player), pygame.event.Event(E_OUTSIDE)),
               # if mouse if over player then grow and shrink player  
              (lambda: player.collidepoint(pygame.mouse.get_pos()), pygame.event.Event(E_MOUSE))]

while True:
    # generate events from conditions
    map(pygame.event.post, [e for (c, e) in conditions if c()])

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise
        elif event.type == E_OUTSIDE and not flash:
            flash = 5
        elif event.type == E_MOUSE:
            if grow: 
                player.inflate_ip(4, 4)
                grow = player.width < 75
            else: 
                player.inflate_ip(-4, -4)
                grow = player.width < 50

    flash = max(flash - 1, 0)
    if flash % 2:
        color = pygame.color.Color('White')                

    pressed = pygame.key.get_pressed()
    l, r, u, d = map(lambda x: x*4, [pressed[k] for k in pygame.K_a, pygame.K_d, pygame.K_w, pygame.K_s])
    player.move_ip((-l + r, -u + d))

    screen.fill(color)
    color = pygame.color.Color('Black')

    pygame.draw.rect(screen, pygame.color.Color('Grey'), player)

    pygame.display.flip()
    timer.tick(25)<file_sep>"""
Simple pong in python 3 for begginers

tutorial series: https://www.youtube.com/playlist?list=PLlEgNdBJEO-kXk2PyBxhSmo84hsO3HAz2
"""

import turtle

wn = turtle.Screen()
wn.title("Pong by @TokyoEdTech")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)

# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed() #sets the speed of animation to max
paddle_a.shape("square") #default is 20x20 pixels
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5, stretch_len = 1) # strech the square
paddle_a.penup()
paddle_a.goto(-350,0)

# Paddle B
paddle_b = turtle.Turtle()
paddle_b.speed() #sets the speed of animation to max
paddle_b.shape("square") #default is 20x20 pixels
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5, stretch_len = 1) # strech the square
paddle_b.penup()
paddle_b.goto(350,0)

# Ball
ball = turtle.Turtle()
ball.speed() #sets the speed of animation to max
ball.shape("square") #default is 20x20 pixels
ball.color("white")
ball.penup()
ball.goto(0,0)

# main game loop
while True:
	wn.update() #updates screen<file_sep>import pygame

pygame.init()


#---------display-------------
display_width = 800
display_height = 600
#color var
black = (0,0,0)
white = (255,255,255)
red   = (255,0,0)
green = (0,255,0)
blue  = (0,0,255)

gameDisplay = pygame.display.set_mode((display_width,display_height))
#set title
pygame.display.set_caption('Race Game')

clock = pygame.time.Clock()

carImg = pygame.image.load('race_car_transp_v2.png')

#function to display a car
def car(x,y):
	gameDisplay.blit(carImg,(x,y)) #we blit car image to a surface

x = display_width*0.45
y = display_height*0.8
#for computers (x=0,y=0) is top left corner

#------------main game loop---------
chrashed = False
while not chrashed:

	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			chrashed = True

	#------------------------------------
	#first draw background, dont paint over car
	gameDisplay.fill(white)	
	car(x,y)
	pygame.display.update()

	clock.tick(60)	
#------------------------------------
pygame.quit()
quit()<file_sep>"""
Basic Movement and Key Presses
video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5

1. create a rectangle
2. move it by key pressed
"""

import pygame
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2

def draw_vector(screen, startpoint, vector, color, width, DEBUG = False):
    """
             E
            ***
           *****
          L**M**R
             *
             *
             *
             *
         ----S-----
             *
             *
             O
    
    E - vector endpoint  
    M - arrow midpoint  
    L - arrow left point  
    R - arrow right point  
    """
    #------------CALCULATIONS---------------
    #DEBUG = False
    # create points
    E = (0, 0) 
    L = (0, 0)
    M = (0, 0)
    R = (0, 0)

    # copy vector to new
    v = Vector2(int(vector.x), int(vector.y))
    
    # 1) set S - starrpoint
    S = (startpoint[0], startpoint[1])
    
    # 2) set E - endpoint
    E = (v.x + S[0], v.y + S[1])
    
    # 3) Find vector SM
    v_SM = Vector2(v.x, v.y)
    v_SM.normalize()
    v_SM *= 2*width # v_SM *= 10
    v_SM = v - v_SM
    
    M = (S[0]+v_SM.x, S[1]+v_SM.y) 
    
    # 3) Find perpendicular vector
    v_perp = Vector2(-v.y, v.x)
    v_perp.normalize()
    v_perp *= width # v_perp *= 5
    
    # 4) Find arrow head points
    L = (M[0] - v_perp.x, M[1] - v_perp.y)
    R = (M[0] + v_perp.x, M[1] + v_perp.y)
    
    #------------DRAWINGS---------------
    # pixels must be integers
    E = (int(E[0]),int(E[1]))
    M = (int(M[0]),int(M[1]))
    L = (int(L[0]),int(L[1]))
    R = (int(R[0]),int(R[1]))
    
    # draw main vector line
    pygame.draw.line(screen, color, S, M, width)
    
    # draw points for debugging purpose
    # points = S, E, L, M, R
    
    # draw arrow head poligone
    # if very short, dont draw arrow
    #length = sqrt(v.x
    pygame.draw.polygon(screen, color, (L, R, E))
    


WIDTH, HEIGHT = 1000, 800
FPS = 60

WHITE   = (255, 255, 255)
BLACK   = (0, 0, 0)
RED     = (255,0,0)
LIME    = (0,255,0)
BLUE    = (0,0,255)
YELLOW  = (255,255,0)

pygame.init()
pygame.mixer.init()

#### Create a canvas on which to display everything ####
screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
#set windows title
pygame.display.set_caption("8 way movement vector")
# set clock
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((64, 64))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH // 2, HEIGHT // 2)
        # delta time, game loop time
        #self.dt = 0
        
        # position vector
        self.position =  Vector2(100.0, 100.0)
        # direction vector
        self.direction = Vector2(0, 0)  
        # movement speed
        self.speed = 300.        
      

    #def set_time_passed_sec(self, dt):
    #    self.dt_sec = dt / 1000.0
        
    def update(self, dt):
        dt_sec = dt / 1000.0
        
        self.direction.x, self.direction.y = (0, 0)
        
        keystate = pygame.key.get_pressed()
    
        if keystate[pygame.K_UP]:
            self.direction += Vector2(0, -1)
        
        if keystate[pygame.K_DOWN]:
            self.direction += Vector2(0,  1)
        
        if keystate[pygame.K_LEFT]:
            self.direction += Vector2(-1, 0)
        
        if keystate[pygame.K_RIGHT]:
            self.direction += Vector2(1,  0)
        
        # direction vector is a unit vector, normalize it
        # diagonals are 0.707
        self.direction.normalize()
    
        self.position += self.direction * self.speed * dt_sec
        
        # set sprite rectangle position
        self.rect.x = self.position.x
        self.rect.y = self.position.y



all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
    
#main game loop
running = True
while running:
    dt = clock.tick(FPS)
    dt_sec = dt / 1000.0
    
    # pygame.time.delay(100) #this will be a clock for the game
    for event in pygame.event.get(): #check for all events that are happening
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            running = False

    # update
    #player.set_time_passed_sec(dt)
    all_sprites.update(dt)
      
    screen.fill(BLACK)
    all_sprites.draw(screen)

    v_dir = Vector2(player.direction.x, player.direction.y)
    v_dir *= 100
    draw_vector(screen, (player.rect.center[0], player.rect.center[1]), v_dir, BLUE, 4)
        
    pygame.display.update()

# exit pygame
pygame.quit()
exit()
<file_sep>import cocos
from cocos.director import director
from pyglet.window import mouse
from cocos.scenes import *
from random import randint, shuffle
import pyglet

# This needs to be on the top, otherwise the SceneManager won't work
director.init(width=1024, height=576, caption="Match the Shapes!")
director.window.pop_handlers()
director.window.set_location(400, 200)


def load_score(file):
    with open(file, 'r') as f:
        score = f.read()
    return score


def save_score(file, scr):
    with open(file, 'w') as f:
        f.write(str(scr))


def calculate_score(score):
    current_time = score
    loaded_time = load_score("res/score.txt")

    current_minutes = current_time.split(":")[0]
    current_seconds = current_time.split(":")[1]

    loaded_minutes = loaded_time.split(":")[0]
    loaded_seconds = loaded_time.split(":")[1]

    time1 = int(current_minutes) * 60 + int(current_seconds)
    time2 = int(loaded_minutes) * 60 + int(loaded_seconds)

    if time1 < time2:
        return True
    return False


""" ALL THE GAME RELATED LAYERS """
class CardLayer(cocos.layer.Layer):
    is_event_handler = True
    def __init__(self, image_path):
        super().__init__()
        self.clicked = False
        self.spr = cocos.sprite.Sprite(image_path, anchor=(0, 0))
        self.name = image_path.split("/")[2].split(".")[0]

        self.back = cocos.sprite.Sprite('res/sprites/back.png', anchor=(0, 0))

        self.add(self.spr)
        self.add(self.back)

    def card_clicked(self, x, y):
        return x < self.spr.x + self.spr.width and x > self.spr.x and y < self.spr.y + self.spr.height and y > self.spr.y

    def on_mouse_press(self, x, y, button, modifiers):
        if button & mouse.LEFT:
            if self.card_clicked(x, y) and len(CardManager.cards_clicked) < 2:
                self.clicked = True
                self.back.visible = False
            else:
                self.clicked = False
        if self.clicked and self not in CardManager.cards_clicked:
            CardManager.cards_clicked.append(self)
            CardManager.check_cards()


class CardManager():

    cards_clicked = []
    pairs = 0

    def __init__(self):
        """
           6  x=3, y=2
          12  x=4, y=3
          20  x=5, y=4
          24  x=6, y=4
        """
        self.level1 = 6 # number of cards at the start of the game
        self.level2 = 12
        self.level3 = 20
        self.level4 = 24

        self.current_level = self.level4

        path = "res/sprites/"
        files = [path + "circle_blue.png", path + "circle_green.png", path + "circle_red.png",
                 path + "penta_blue.png", path + "penta_green.png", path + "penta_red.png",
                 path + "rect_blue.png", path + "rect_green.png", path + "rect_red.png",
                 path + "star_blue.png", path + "star_green.png", path + "star_red.png"]

        random_list = []

        for i in range(self.current_level // 2):
            r = randint(0, len(files) - 1)
            if files[r] not in random_list:
                random_list.append(files[r])
                random_list.append(files[r])
            else:
                while files[r] in random_list:
                    r = randint(0, len(files) - 1)
                random_list.append(files[r])
                random_list.append(files[r])

        shuffle(random_list)

        positions = self.calc_positions()

        for i, file in enumerate(random_list):
            card = CardLayer(file)
            card.spr.image_anchor_x = 0
            card.spr.image_anchor_y = 0
            card.spr.position = positions[i]
            card.back.position = card.spr.position
            SceneManager.game_scene.add(card)

    def calc_positions(self):
        xx, yy = 0, 0
        if self.current_level == self.level1:
            xx, yy = 3, 2
        elif self.current_level == self.level2:
            xx, yy = 4, 3
        elif self.current_level == self.level3:
            xx, yy = 5, 4
        elif self.current_level == self.level4:
            xx, yy = 6, 4
        positions = []
        x_offset = 50
        y_offset = 50
        for x in range(xx):
            for y in range(yy):
                positions.append((x_offset, y_offset))
                y_offset += 120
            x_offset += 120
            y_offset = 50

        return positions

    @staticmethod
    def flip_cards_back(dt):
        for card in CardManager.cards_clicked:
            card.back.visible = True
        CardManager.cards_clicked = []  # need to set this here also

    @staticmethod
    def remove_cards(dt):
        SceneManager.game_scene.remove(CardManager.cards_clicked[0])
        SceneManager.game_scene.remove(CardManager.cards_clicked[1])
        CardManager.cards_clicked = [] # need to set this here also

    @staticmethod
    def check_cards():
        if len(CardManager.cards_clicked) == 2:
            if CardManager.cards_clicked[0].name == CardManager.cards_clicked[1].name:
                CardManager.pairs += 1
                pyglet.clock.schedule_once(CardManager.remove_cards, 0.5)
            else:
                pyglet.clock.schedule_once(CardManager.flip_cards_back, 1.0)
        if CardManager.pairs == 12:
            CardManager.pairs = 0
            GameScene.game_finished = True
            SceneManager.change_scene(SceneManager.wining_scene)


""" ALL THE MENU RELATED LAYERS """
class MainMenu(cocos.menu.Menu):
    def __init__(self):
        super().__init__('CARD MATCH!')

        items = []

        items.append(cocos.menu.MenuItem('New Game', self.on_new_game))
        items.append(cocos.menu.MenuItem('Best Time', self.on_best_time))
        items.append(cocos.menu.MenuItem('Quit', self.on_quit))

        self.create_menu(items, cocos.menu.shake(), cocos.menu.shake_back())

    def on_new_game(self):
        SceneManager.change_scene(SceneManager.game_scene)

    def on_best_time(self):
        SceneManager.change_scene(SceneManager.best_time_scene)

    def on_quit(self):
        director.window.close()


# Back to main button
class Button(cocos.layer.Layer):
    is_event_handler = True
    def __init__(self, pos):
        super().__init__()
        self.spr = cocos.sprite.Sprite('res/sprites/back_to_main.png')

        self.spr.position = pos

        self.add(self.spr)

    def button_clicked(self, x, y):
        return x > self.spr.x - (self.spr.width//2) and x < self.spr.x + (self.spr.width // 2) and \
               y > self.spr.y - (self.spr.height//2) and y < self.spr.y + (self.spr.height // 2)

    def on_mouse_press(self, x, y, button, modifiers):
        if button & mouse.LEFT:
            if self.button_clicked(x, y):
                SceneManager.change_scene(SceneManager.start_scene)

    def on_mouse_motion(self, x, y, dx, dy):
        if self.button_clicked(x, y):
            self.spr.scale = 1.2
        else:
            self.spr.scale = 1


# The Timer
class Timer(cocos.layer.Layer):

    current_time = ""
    time_start = None
    time_stop = None

    def __init__(self):
        super().__init__()
        self.label = cocos.text.Label("", font_name="Times New Roman", font_size=26,
                                 anchor_x="center", anchor_y="center")
        self.start_time = 0

        self.label.position = 874, 276
        self.add(self.label)

        Timer.time_start = self.run_scheduler
        Timer.time_stop = self.stop_scheduler

    def timer(self, dt):
        if GameScene.game_finished:
            self.stop_scheduler()
            self.start_time = 0
            GameScene.game_finished = False
        else:
            mins, secs = divmod(self.start_time, 60)
            time_format = '{:02d}:{:02d}'.format(mins, secs)
            Timer.current_time = time_format
            self.label.element.text = time_format
            self.start_time += 1

    def run_scheduler(self):
        self.schedule_interval(self.timer, 1.0)

    def stop_scheduler(self):
        self.unschedule(self.timer)


""" ALL THE SCENES """
class StartScene(cocos.scene.Scene):
    def __init__(self):
        super().__init__()

        menu = MainMenu()

        self.add(cocos.layer.ColorLayer(50, 50, 50, 180))
        self.add(menu)


class GameScene(cocos.scene.Scene):

    game_finished = False

    def __init__(self):
        super().__init__()

        self.add(cocos.layer.ColorLayer(50, 50, 50, 180))
        self.add(Button(pos=(874, 376)))
        self.add(Timer())


    # def on_enter(self):
    #     super().on_enter()
    #
    # def on_exit(self):
    #     super().on_exit()


class BestTimeScene(cocos.scene.Scene):
    def __init__(self):
        super().__init__()

        self.add(cocos.layer.ColorLayer(50, 50, 50, 180))
        self.add(Button(pos=(512, 156)))

        self.label = cocos.text.Label("", font_name="Times New Roman", font_size=26,
                                      anchor_x="center", anchor_y="center", position=(512, 300))



        self.add(self.label)

    def on_enter(self):
        super().on_enter()
        self.label.element.text = load_score("res/score.txt")

    def on_exit(self):
        super().on_exit()


class WinningScene(cocos.scene.Scene):
    def __init__(self):
        super().__init__()

        self.add(cocos.layer.ColorLayer(50, 50, 50, 180))
        self.add(Button(pos=(512, 156)))

        self.add(cocos.text.Label("Your time was:", font_name="Times New Roman", font_size=26,
                                      anchor_x="center", anchor_y="center", position=(512,300)))

        self.score = cocos.text.Label("", font_name="Times New Roman", font_size=22,
                                     anchor_x="center", anchor_y="center", position=(512, 220))

        self.add(self.score)



    def on_enter(self):
        super().on_enter()
        self.score.element.text = Timer.current_time
        if calculate_score(Timer.current_time):
            save_score("res/score.txt", Timer.current_time)

    def on_exit(self):
        super().on_exit()


""" THE SCENE MANAGER """
class SceneManager:

    start_scene = StartScene()
    best_time_scene = BestTimeScene()
    game_scene = GameScene()
    wining_scene = WinningScene()

    active_scene = start_scene

    @staticmethod
    def change_scene(scene):
        SceneManager.active_scene = scene
        if SceneManager.active_scene == SceneManager.game_scene:
            CardManager()
            Timer.time_start()
        elif SceneManager.active_scene == SceneManager.start_scene:
            for child in SceneManager.game_scene.get_children():
                if hasattr(child, 'name'):
                    child.kill()
        director.replace(FlipX3DTransition(SceneManager.active_scene, duration=2))


if __name__ == "__main__":
    director.run(SceneManager.active_scene)<file_sep>import pygame
from pygame.locals import *
from sys import exit

from random import *
from math import pi

pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()

    x, y  = pygame.mouse.get_pos() 
    angle = (x/639.)*pi*2. 
    screen.fill((255,255,255))
    pygame.draw.arc(screen, (0,0,0), (0,0,639,479), 0, angle)

    pygame.display.update()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sat Dec 19 10:54:58 2020

@author: crtom
"""

import numpy as np

def var1():
    # build a list of touples from two numpy arrays
    x = np.linspace(0, 500, 6)
    y = np.linspace(0, 500, 6)
    
    z = zip(x,y)
    print(list(z))

def var2():
    # create a list of touple positions
    lst = []
    for x in range(0, 600, 100):
        for y in range(0, 600, 100):
            lst.append((x,y))
    
    print(lst)
    print('first item:',lst[0])
    print('last item:',lst[35])
   
# create a dictionary of grid    
def var3():
    
    thisdict = {
      "position_vertice": (0,0),
      "position_card": (10,10),
      "surface": 1964
    }           
    
    print(thisdict["position_vertice"])
    print(thisdict["position_vertice"])
    print(thisdict["surface"])

def var4():
    pass

    
#var3()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sat Dec 26 22:15:23 2020

@author: crtom
"""

import math

class Vector2D:
    """A two-dimensional vector with Cartesian coordinates."""

    def __init__(self, x, y):
        self.x, self.y = x, y

    def __str__(self):
        """Human-readable string representation of the vector."""
        return '{:g}i + {:g}j'.format(self.x, self.y)

    def __repr__(self):
        """Unambiguous string representation of the vector."""
        return repr((self.x, self.y))

    def dot(self, other):
        """The scalar (dot) product of self and other. Both must be vectors."""

        if not isinstance(other, Vector2D):
            raise TypeError('Can only take dot product of two Vector2D objects')
        return self.x * other.x + self.y * other.y
    # Alias the __matmul__ method to dot so we can use a @ b as well as a.dot(b).
    __matmul__ = dot

    def __sub__(self, other):
        """Vector subtraction."""
        return Vector2D(self.x - other.x, self.y - other.y)

    def __add__(self, other):
        """Vector addition."""
        return Vector2D(self.x + other.x, self.y + other.y)

    def __mul__(self, scalar):
        """Multiplication of a vector by a scalar."""

        if isinstance(scalar, int) or isinstance(scalar, float):
            return Vector2D(self.x*scalar, self.y*scalar)
        raise NotImplementedError('Can only multiply Vector2D by a scalar')

    def __rmul__(self, scalar):
        """Reflected multiplication so vector * scalar also works."""
        return self.__mul__(scalar)

    def __neg__(self):
        """Negation of the vector (invert through origin.)"""
        return Vector2D(-self.x, -self.y)

    def __truediv__(self, scalar):
        """True division of the vector by a scalar."""
        return Vector2D(self.x / scalar, self.y / scalar)

    def __mod__(self, scalar):
        """One way to implement modulus operation: for each component."""
        return Vector2D(self.x % scalar, self.y % scalar)

    def __abs__(self):
        """Absolute value (magnitude) of the vector."""
        return math.sqrt(self.x**2 + self.y**2)

    def distance_to(self, other):
        """The distance between vectors self and other."""
        return abs(self - other)

    def to_polar(self):
        """Return the vector's components in polar coordinates."""
        return self.__abs__(), math.atan2(self.y, self.x)


if __name__ == '__main__':
    v1 = Vector2D(2, 5/3)
    v2 = Vector2D(3, -1.5)
    print('v1 = ', v1)
    print('repr(v2) = ', repr(v2))
    print('v1 + v2 = ', v1 + v2)
    print('v1 - v2 = ', v1 - v2)
    print('abs(v2 - v1) = ', abs(v2 - v1))
    print('-v2 = ', -v2)
    print('v1 * 3 = ', v1 * 3)
    print('7 * v2 = ', 7 * v1)
    print('v2 / 2.5 = ', v2 / 2.5)
    print('v1 % 1 = ', v1 % 1)
    print('v1.dot(v2) = v1 @ v2 = ', v1 @ v2)
    print('v1.distance_to(v2) = ',v1.distance_to(v2))
    print('v1 as polar vector, (r, theta) =', v1.to_polar())<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Dec 20 15:27:13 2020

@author: crtom
"""


import pygame

def draw_rect_alpha(surface, color, rect):
    shape_surf = pygame.Surface(pygame.Rect(rect).size, pygame.SRCALPHA)
    pygame.draw.rect(shape_surf, color, shape_surf.get_rect())
    surface.blit(shape_surf, rect)

def draw_circle_alpha(surface, color, center, radius):
    target_rect = pygame.Rect(center, (0, 0)).inflate((radius * 2, radius * 2))
    shape_surf = pygame.Surface(target_rect.size, pygame.SRCALPHA)
    pygame.draw.circle(shape_surf, color, (radius, radius), radius)
    surface.blit(shape_surf, target_rect)

def draw_polygon_alpha(surface, color, points):
    lx, ly = zip(*points)
    min_x, min_y, max_x, max_y = min(lx), min(ly), max(lx), max(ly)
    target_rect = pygame.Rect(min_x, min_y, max_x - min_x, max_y - min_y)
    shape_surf = pygame.Surface(target_rect.size, pygame.SRCALPHA)
    pygame.draw.polygon(shape_surf, color, [(x - min_x, y - min_y) for x, y in points])
    surface.blit(shape_surf, target_rect)

def draw_background():
    background = pygame.Surface(window.get_size())
    ts, w, h, c1, c2 = 50, *window.get_size(), (160, 160, 160), (192, 192, 192)
    tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]

    for rect, color in tiles:
        pygame.draw.rect(background, color, rect)
    
    window.blit(background, (0, 0))

pygame.init()
window = pygame.display.set_mode((250, 250))
clock = pygame.time.Clock()

#print(window.get_size())

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    
    draw_background()
    
    draw_rect_alpha(window, (0, 0, 255, 127), (55, 90, 140, 140))
    draw_circle_alpha(window, (255, 0, 0, 127), (150, 100), 80)
    draw_polygon_alpha(window, (255, 255, 0, 127), 
        [(100, 10), (100 + 0.8660 * 90, 145), (100 - 0.8660 * 90, 145)])

    pygame.display.flip()

pygame.quit()
exit()<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Dec 15 18:09:41 2020

@author: crtom
"""

import pygame
import sys
#from vector2 import Vector2
#from vector2 import *

from gameobjects.vector2 import *
from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT

# for antialiased
from pygame import gfxdraw

def draw_circle(surface, x, y, radius, color):
    gfxdraw.aacircle(surface, x, y, radius, color)
    gfxdraw.filled_circle(surface, x, y, radius, color)
    
pygame.init()

FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()


# returns pygame.Surface objet for window
DISPLAYSURF = pygame.display.set_mode((400,400))

pygame.display.set_caption('Hello World!')

#point A
A = (10.0, 10.0)
#point B
B = (300.0, 300.0)

# vector of distance between points AB
AB = Vector2.from_points(A, B)

# step vector, length of 1/10 AB
step = AB * .01

#start position vector at point A
position = Vector2(A[0], A[1])

# for n in range(10):
#     position += step
#     print(position)

#create point
#pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size, self.thickness)

Running = True
while Running:
    
    # event handling
    for event in pygame.event.get():
        
        # event objects have type attribute
        if event.type == QUIT:
            Running = False
    
    position += step
    #print(position.x)
    
    # clear background
    DISPLAYSURF.fill((0,0,0))
    
    pygame.draw.line(DISPLAYSURF, (255, 255, 255),(A[0],A[1]),(position.x, position.y))
    #pygame.draw.circle(DISPLAYSURF, (255,255,255), (int(position.x), int(position.y)), 5, 0)    
    draw_circle(DISPLAYSURF, int(position.x), int(position.y), 5, (255,255,255))
    
    # check when vector reaches position
    if position.x >= AB.x and position.y >= AB.y:
        print('reached pos')
        Running = False
        
    # draws surface object stored in DISPLAYSURF
    pygame.display.update()
    
    #pygame.time.wait(100)
    fpsClock.tick(FPS)

pygame.quit()
sys.exit()<file_sep>def alpha_blend(src, dst):
    return src * src.a + dst * (1.0—src.a)
<file_sep># Memory puzzle

http://inventwithpython.com/pygame/
http://inventwithpython.com/pygame/chapter3.html

- v1:    BASIC ARHITECTURE, timing, quit event. stable application
- v2:    mouse coordinates, events
- v3:    create playing grid, and clicked positions, game grid, boxes, transformations
- v3_2:  pixel, grid all using touples
- v4:    finished grid with dictionary, moved to card logic
- v5:    creating card icons, list, shuffle icons
- v6:    creating game logic and state transitions    
- v7:    add animation of turn card around after 2 sec

- Making Sure We Have Enough Icons
Tuples vs. Lists, Immutable vs. Mutable
One Item Tuples Need a Trailing Comma
Converting Between Lists and Tuples
The global statement, and Why Global Variables are Evil
Data Structures and 2D Lists
The “Start Game” Animation
The Game Loop
The Event Handling Loop
Checking Which Box The Mouse Cursor is Over
Handling the First Clicked Box
Handling a Mismatched Pair of Icons
Handling If the Player Won
Drawing the Game State to the Screen
Creating the “Revealed Boxes” Data Structure
Creating the Board Data Structure: Step 1 – Get All Possible Icons
Step 2 – Shuffling and Truncating the List of All Icons
Step 3 – Placing the Icons on the Board
Splitting a List into a List of Lists
Different Coordinate Systems
Converting from Pixel Coordinates to Box Coordinates
Drawing the Icon, and Syntactic Sugar
Syntactic Sugar with Getting a Board Space’s Icon’s Shape and Color
Drawing the Box Cover
Handling the Revealing and Covering Animation
Drawing the Entire Board
Drawing the Highlight
The “Start Game” Animation
Revealing and Covering the Groups of Boxes
The “Game Won” Animation
Telling if the Player Has Won
Why Bother Having a main() Function?<file_sep>import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.fill(0)

    rect = pygame.Rect(window.get_rect().center, (0, 0)).inflate(*([min(window.get_size())//2]*2))
    
    for x in range(rect.width):
        u = x / (rect.width - 1)
        color = (round(u*255), 0, round((1-u)*255))
        for y in range(rect.height):
            window.set_at((rect.left + x, rect.top + y), color) 
    
    pygame.display.flip()

pygame.quit()
exit()<file_sep># game options/settings
WIDTH = 360
HEIGHT = 480
FPS = 30

#RGB color constants
WHITE   = (255, 255, 255)
BLACK   = (0, 0, 0)
RED     = (255,0,0)
LIME    = (0,255,0)
BLUE    = (0,0,255)
YELLOW  = (255,255,0)
CYAN    = (0,255,255)
MAGENTA = (255,0,255)
SILVER  = (192,192,192)
GRAY	= (128,128,128)
MAROON  = (128,0,0)
OLIVE   = (128,128,0)
GREEN   = (0,128,0)
PURPLE  = (128,0,128)
TEAL    = (0,128,128)
NAVY    = (0,0,128)<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Dec 25 21:10:25 2020

@author: crtom
"""

"""
Basic Movement and Key Presses
video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5

1. create a rectangle
2. move it by key pressed
"""

import pygame
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2

# draw antialiase line for vectors
from pygame import gfxdraw

from math import *

# defines  
WIDTH, HEIGHT = 640, 480

WHITE   = (255, 255, 255)
BLACK   = (0, 0, 0)
RED     = (255,0,0)
LIME    = (0,255,0)
BLUE    = (0,0,255)
YELLOW  = (255,255,0)
CYAN    = (0,255,255)
MAGENTA = (255,0,255)
SILVER  = (192,192,192)
GREY	= (128,128,128)
MAROON  = (128,0,0)
OLIVE   = (128,128,0)
GREEN   = (0,128,0)
PURPLE  = (128,0,128)
TEAL    = (0,128,128)
NAVY    = (0,0,128)

pygame.init()
#### Create a canvas on which to display everything ####
screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
#set windows title
pygame.display.set_caption("vector arrow")

#### Create a surface with the same size as the window ####
background = pygame.Surface((WIDTH, HEIGHT))
background.fill(WHITE)

clock = pygame.time.Clock()

def draw_point(screen, color, p, radius): #, color, position, radius
    
    point = (int(p[0]), int(p[1]))
    
    pygame.draw.circle(screen, color, point, radius)
    

def draw_line(screen, color, startpoint, vector, width):
    """
    Draws line representing vector.
    """

    v1 = Vector2(vector.x, vector.y)
    
    endpoint = (v1.x + startpoint[0], v1.y + startpoint[1])
    
    startpoint = (int(startpoint[0]), int(startpoint[1]))
    endpoint = (int(endpoint[0]), int(endpoint[1]))
    
    pygame.draw.line(screen, color, startpoint, endpoint, width)

# ----------drawing
p_A = (WIDTH // 2, HEIGHT // 2)
p_B = (WIDTH // 2, 50)
vector_AB = Vector2.from_points(p_A, p_B)

# print(p_A)
# print(p_B)
# #as_tuple


#------------------------
screen.blit(background, (0,0))

draw_point(screen, RED, p_A, 5)
pygame.display.update()

draw_point(screen, BLUE, p_B, 5)
pygame.display.update()

# draw_line(screen, color, startpoint, vector, width):
# ORIGINAL VECTOR
draw_line(screen, BLACK, p_A, vector_AB, 3)
pygame.display.update()

# ROTATED VECTOR
angle = 45
x_rot = cos(angle)*vector_AB.x - sin(angle)*vector_AB.y
y_rot = sin(angle)*vector_AB.x + cos(angle)*vector_AB.y
vector_AB_rot = Vector2(x_rot, y_rot)
draw_line(screen, GREY, p_A, vector_AB_rot, 3)

# perpendicualar vector
vector_AB_perp = Vector2(-vector_AB_rot.y, vector_AB_rot.x)
draw_line(screen, GREY, p_A, vector_AB_perp, 3)
pygame.display.update()

# arrow head to original vector
# first find point on original vector that is a little bellow vector endpoint
vector_norm = Vector2(vector_AB.x, vector_AB.y)
vector_norm.normalise()
vector_norm *= 10
vector_norm = vector_AB - vector_norm
draw_line(screen, GREY, p_A, vector_norm, 3)
pygame.display.update()

# find perpendicular vector to original
vector_perp = Vector2(-vector_AB.y, vector_AB.x)
vector_perp.normalise()
vector_perp *= 5

point = (int(vector_norm.x) +  p_A[0], int(vector_norm.y) +  p_A[1])
point = (point[0], point[1])

draw_point(screen, BLACK, point, 5)

draw_line(screen, GREY, point, vector_perp, 3)
draw_line(screen, GREY, point, -vector_perp, 3)

# pointL = original_vector_startpoint+
point_R = (point[0] + vector_perp.x, point[1] + vector_perp.y)
point_L = (point[0] - vector_perp.x, point[1] - vector_perp.y)
draw_point(screen, BLACK, point_R, 5)
draw_point(screen, BLACK, point_L, 5)

endpoint = vector_AB.x+ p_A[0], vector_AB.y + p_A[1]

# draw rectangle
pygame.draw.polygon(screen, GREEN, (point_L, point_R, endpoint))

pygame.display.update()

print(vector_AB)
print(vector_norm)
print(point)
print(vector_perp)
# draw_line(screen, RED, p_A, vector_a, 3)
# pygame.display.update()





#----------------------
#main game loop
clock = pygame.time.Clock()
run = True
angle = 0.
while run:
    # pygame.time.delay(100) #this will be a clock for the game
    for event in pygame.event.get(): #check for all events that are happening
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            run = False
    
    # calculate times
    time_passed = clock.tick(30)
    time_passed_seconds = time_passed / 1000.0

# exit pygame
pygame.quit()
exit()

"""
    #draw_arrow(screen, 0, 10, GREEN)
    #------------------DRAWINGS------------------------
    #### Blit the surface onto the canvas ####
    screen.blit(background,(0,0))
    #### Blit the points onto canvas
    
    angle += 0.01
    
    
    #draw_arrow(screen, colour, startpoint, vector, width):
    draw_point(screen, BLUE, p_A, 5)
    #draw_point(screen, GREEN, p_B, 5)
    draw_arrow(screen, BLUE, p_A, vector_AB_rot, 2)
    #screen.blit(arrow, arrow_pos)
    #### display canvas ####
    pygame.display.update()
    x_rot = cos(angle)*vector_AB.x - sin(angle)*vector_AB.y
    y_rot = sin(angle)*vector_AB.x + cos(angle)*vector_AB.y
    
    vector_AB_rot = Vector2(x_rot, y_rot)
"""<file_sep>"""
Game Template
"""
import sys
import pygame as pg
from pygame.locals import*
import random
from settings import *
import time
import math

WIDTH, HEIGHT = 200, 200

# initialize pygame and create a window
pg.init()
pg.mixer.init()
screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption("My Game")
clock = pg.time.Clock()

all_sprites = pg.sprite.Group()

# game loop
running = True
while running:

	# keep looping at the right speed
	clock.tick(FPS)
	# process input (events)
	for event in pg.event.get(): #check for all events that are happening
		if event.type == pg.QUIT:
			running = False
		if event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
			running = False

	# Update
	all_sprites.update()

	# draw/render
	screen.fill(BLACK)
	all_sprites.draw(screen)
	# after drawing everything, flip the display
	pg.display.update()

pg.quit()<file_sep>"""
Simple pong in python 3 for begginers

tutorial series: https://www.youtube.com/playlist?list=PLlEgNdBJEO-kXk2PyBxhSmo84hsO3HAz2
"""

import turtle

wn = turtle.Screen()
wn.title("Pong by @TokyoEdTech")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)

# main game loop
while True:
	wn.update() #updates screen<file_sep>glBegin(GL_QUADS)
glColor(1.0, 0.0, 0.0) # Red 
glVertex(100.0, 100.0, 0.0) # Top left
glVertex(200.0, 100.0, 0.0) # Top right 
glVertex(200.0, 200.0, 0.0) # Bottom right 
glVertex(100.0, 200.0, 0.0) # Bottom left

glEnd()
<file_sep>"""
Python: Bouncing Ball Animation with Real-World Physics!!
video: https://www.youtube.com/watch?v=9LWpCtbSvG4

Analyst Rising 1.36K subscribers

In this tutorial I will be showing you how to code/programme
a bouncing ball, with REAL-WORLD PHYSICS, in Python.
This is one of many great python tutorials that should
get you well on your way to programming some amazing stuff!!
"""

import pygame
from pygame.locals import *
import time

pygame.init()
#---------game constants variables-------------
display_width = 300
display_height = 400
#RGB color constants
black = (0,0,0)
white = (255,255,255)
red   = (255,0,0)
green = (0,255,0)
blue  = (0,0,255)

update_ms = 100
frame_speed_sec = (1/update_ms)*1000

#------------------------------------------------------
#create main display window
gameDisplay = pygame.display.set_mode((display_width,display_height))
#set main display window title
pygame.display.set_caption('gameDisplay')

clock = pygame.time.Clock()

#----------------------FUNCTIONS-------------------------
def fps_display_counter(count):
	#1. set type font
	font = pygame.font.SysFont(None,25)
	#2. render it
	text = font.render("FPS count: " + str(count),True,white)
	#3. blit = draw
	gameDisplay.blit(text,(0,0))

class Particle(object):
	def __init__(self, x, y, size, colour, thickness):
	    self.x = x
	    self.y = y
	    self.size = size
	    self.colour = colour
	    self.thickness = thickness

	def display(self):
		#pygame.draw.
		pygame.draw.circle(gameDisplay, self.colour, (self.x, self.y), self.size, self.thickness)

def game_loop(frame_speed):
	#main game loop
	run = True
	counter = 0
	velocity_x = 10
	velocity_y = -10
	gravity = 0.7
	friction = 0.5

	while run:
		counter += 1
		#-----------check for pressed keys----------------
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				run = False
			if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
				run = False
		#-------------------------------------------------

		#CONSTRAINTS X
		if particle.x - particle.size <= 0 or particle.size + particle.x >= display_width:
			velocity_x = -velocity_x
		
		#CONSTRAINTS Y
		if particle.y - particle.size <= 0 or particle.size + particle.y >= display_height:
			velocity_y = -velocity_y

		particle.x += velocity_x
		particle.y += velocity_y
		#-------------------------------------------------
		gameDisplay.fill(black) # draw background
		fps_display_counter(counter)
		particle.display()			#draw particle ball
		pygame.display.update()		#update display
		clock.tick(frame_speed)	#set FPS update frequency


#---------------------------------------
#-----------initialization--------------
particle = Particle(x=150, y=50, size=10, colour=white, thickness=0)

#-------------main loop-----------------
game_loop(frame_speed_sec)
#---------------------------------------
#---------------------------------------<file_sep>def lerp(value1, value2, factor):
    return value1+(value2-value1)*factor

print(lerp(100, 200, 0.))
print(lerp(100, 200, 1.))
print(lerp(100, 200, .5)) 
print(lerp(100, 200, .25))
<file_sep>"""Snake Game Python Tutorial
youtube video: https://www.youtube.com/watch?v=CD4qAhfFuLo
current time: 33:00
"""
import sys
import math
import random
import pygame
from pygame.locals import *
import tkinter as tk
from tkinter import messagebox

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)

class cube(object):
    """
    """
    w = 500 #set pixel screen width
    rows = 20 #set number of rows

    def __init__(self,start,dirnx=1,dirny=0,color=RED):
        self.pos = start
        self.dirnx = 1
        self.dirny = 0
        self.color = color

    def move(self,dirnx,dirny):
        """
        move cube, by adding new direction to previous position
        """
        self.dirnx = dirnx
        self.dirny = dirny
        self.pos = (self.pos[0]+self.dirnx, self.pos[1]+self.dirny)

    def draw(self,surface,eyes=False):
        """
        drawing: convert x,y grid position to pixel position
        """
        dis = self.w // self.rows #distance between x and y values
        #variables for easy coding
        i = self.pos[0] # row
        j = self.pos[1] # column
        #draw just a little bit less, so we draw inside of the square. and we dont cover grid.
        pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1,dis-2,dis-2 ))

        #draw eyes
        if eyes:
                centre = dis//2
                radius = 3
                circleMiddle = (i*dis+centre-radius, j*dis+8 ) #eye 1
                circleMiddle2 = (i*dis+dis-radius*2, j*dis+8 ) #eye 2
                pygame.draw.circle(surface, BLACK, circleMiddle, radius)
                pygame.draw.circle(surface, BLACK, circleMiddle2, radius)

def drawGrid(w,rows,surface):
    """
    This function draws a square grid on main display
    """
    #distance between grid lines
    sizeBtwn = w // rows
    x = 0
    y = 0

    #create grid by drawing lines
    for l in range(rows):
        x = x + sizeBtwn
        y = y + sizeBtwn
        #vertical lines
        pygame.draw.line(surface, WHITE, (x,0), (x,w))
        #horizontal lines
        pygame.draw.line(surface, WHITE, (0,y), (w,y))

def redrawWindow(surface):
    global rows, width, s
    #background
    surface.fill(BLACK)
    #draw grid
    drawGrid(width, rows, surface)
    #update display
    pygame.display.update()


def main():
    global width, rows, s
    #create game display
    width = 500
    rows = 20
    win = pygame.display.set_mode((width, width)) #square display

    clock = pygame.time.Clock()

    flag = True
    FPScount = 0
    print(FPScount)
    while flag:
        #pygame.time.delay(50)
        clock.tick(10)  #game max speed 10 FPS
        s.move()
        redrawWindow(win)

        FPScount += 1
        print(f'FPScount:{FPScount}')

#rows = 0
#w = 0
#h = 0

#cube.rows = rows
#cube.w = w
main()
pygame.quit()
sys.exit()<file_sep>"""Summary

Attributes:
    BLACK (tuple): Description
    BLUE (tuple): Description
    CYAN (tuple): Description
    FPS (int): Description
    GRAY (tuple): Description
    GREEN (tuple): Description
    HEIGHT (int): Description
    LIME (tuple): Description
    MAGENTA (tuple): Description
    MAROON (tuple): Description
    NAVY (tuple): Description
    OLIVE (tuple): Description
    PURPLE (tuple): Description
    RED (tuple): Description
    SILVER (tuple): Description
    TEAL (tuple): Description
    TITLE (str): Description
    WHITE (tuple): Description
    WIDTH (int): Description
    YELLOW (tuple): Description
"""
# game options/settings
TITLE = "Doodle Jump!"
WIDTH = 480
HEIGHT = 600
WIDTH_MID = WIDTH // 2
HEIGHT_MID = HEIGHT // 2
FPS = 60
FONT_NAME = 'arial'
HIGHSCORE_FILE = "highscore.txt"
SPRITESHEET_FILE ="spritesheet_jumper.png"

#player properties
#if positive = move DOWN, negative = move UP
PLAYER_ACC = 0.7
PLAYER_FRICTION = -0.1
PLAYER_GRAVITY = 1
PLAYER_JUMP_VELOCITY = -40

# Starting platforms Platform(x, y, width, height)
PLATFORM_LIST = [
(0, HEIGHT - 60),
(WIDTH//2-50, HEIGHT*3/4),
(125, HEIGHT-350),
(350, 200),
(175, 100)
]

#RGB color constants
BLACK   = (0, 0, 0)
WHITE   = (255, 255, 255)
RED     = (255,0,0)
LIME    = (0,255,0)
BLUE    = (0,0,255)

YELLOW  = (255,255,0)
CYAN    = (0,255,255)
MAGENTA = (255,0,255)
SILVER  = (192,192,192)
GRAY	= (128,128,128)
MAROON  = (128,0,0)
OLIVE   = (128,128,0)
GREEN   = (0,128,0)
PURPLE  = (128,0,128)
TEAL    = (0,128,128)
NAVY    = (0,0,128)

BG_COLOR = TEAL
PLATFORM_COLOR = LIME<file_sep>link to the site

[Making Games with Python & Pygame (inventwithpython.com)](http://inventwithpython.com/pygame/)

<file_sep># Beginning-Game-Development-with-Python-and-Pygame
Source Code from Beginning Game Development with Python and Pygame by <NAME> and <NAME>

Code is organized by chapter, denoted by the listing name. As the book progresses, we use more and more of the gameobjects library. 
<file_sep>import math

class Vector2:
    
    def __init__(self, x=0, y=0):        
        self.x = x
        self.y = y
        
    def __str__(self):
        return "(%s, %s)"%(self.x, self.y)
        
    def from_points(P1, P2):        
        return Vector2( P2[0] - P1[0], P2[1] - P1[1] )
    
    def get_magnitude(self):        
        return math.sqrt( self.x**2 + self.y**2 )
        
    def normalize(self):
        magnitude = self.get_magnitude()
        self.x /= magnitude
        self.y /= magnitude
        
    def __add__(self, rhs):         
        return Vector2(self.x + rhs.x, self.y + rhs.y)
        
    def __sub__(self, rhs):
        return Vector2(self.x - rhs.x, self.y - rhs.y)
        
    def __neg__(self):
        return Vector2(-self.x, -self.y)
        
    def __mul__(self, scalar):
        return Vector2(self.x * scalar, self.y * scalar)
        
    def __truediv__(self, scalar):
        return Vector2(self.x / scalar, self.y / scalar)
            
        
A = (10.0, 20.0)
B = (30.0, 35.0)
AB = Vector2.from_points(A, B)
step = AB * .1
position = Vector2(*A)
for n in range(10):
    position += step
    print(position)

<file_sep>class World(object):

    def __init__(self):

        self.entities = {} # Store all the entities
        self.entity_id = 0 # Last entity id assigned
        # Draw the nest (a circle) on the background
        self.background = pygame.surface.Surface(SCREEN_SIZE).convert()
        self.background.fill((255, 255, 255)) 
        pygame.draw.circle(self.background, (200, 255, 200), NEST_POSITION, int(NEST_SIZE))

    def add_entity(self, entity):

        # Stores the entity then advances the current id
        self.entities[self.entity_id] = entity
        entity.id = self.entity_id
        self.entity_id += 1

    def remove_entity(self, entity):

        del self.entities[entity.id]

    def get(self, entity_id):

        # Find the entity, given its id (or None if it is not found)
        if entity_id in self.entities:
          return self.entities[entity_id]
        else:
          return None

    def process(self, time_passed):

        # Process every entity in the world
        time_passed_seconds = time_passed / 1000.0
        for entity in self.entities.itervalues():
          entity.process(time_passed_seconds)

    def render(self, surface):

        # Draw the background and all the entities
        surface.blit(self.background, (0, 0))
        for entity in self.entities.values():
          entity.render(surface)

    def get_close_entity(self, name, location, e_range=100):

        # Find an entity within range of a location 
        location = Vector2(*location)

        for entity in self.entities.values():
          if entity.name == name:
             distance = location.get_distance_to(entity.location)
             if distance < e_range:
                 return entity
        return None
<file_sep>Welcome to <NAME>'s minigame repository. This repository will contain all of the codes from my minigames, written mainly in python and also Lua.  
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 11:31:56 2020

@author: crtom
"""

import math
import random

class Vector:
    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y

    # Vector operator overload
    # theory: when called a + b, python calls a.__add__(b)
    # we now overrdide this methods
    
    def __add__(self, other):
        if isinstance (other, self.__class__):
            return Vector(self.x + other.x, self.y + other.y )
        return Vector(self.x + other, self.y + other)

    def __sub__(self, other):
        if isinstance (other, self.__class__):
            return Vector(self.x - other.x, self.y - other.y )
        return Vector(self.x - other, self.y - other)
    
    def __mul__(self, other):
        if isinstance (other, self.__class__):
            return Vector(self.x * other.x, self.y * other.y )
        return Vector(self.x * other, self.y * other)

    # # reverse multiply override
    # def __rmul__(self, other):
    #     return Vector(self.x * other, self.y * other)
    
    def __rmul__(self, other):
        return self.__mul__(other)   # commutative operation
    
    def __truediv__(self, other):
        if isinstance (other, self.__class__):
            return Vector(self.x / other.x, self.y / other.y )
        return Vector(self.x / other, self.y / other)
    
    # check for equal
    def __eq__(self, other):
        if isinstance (other, self.__class__):
            return self.x == other.x and self.y == other.y
        return self.x == other and self.y == other
    
    def make_int_tuple(self):
        return int(self.x), int(self.y)

    def set(self, vec):
        self.x = vec.x
        self.y = vec.y

#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
        
# additional vector calculations
# Skalarni produkt (Dot product)
#Rezultat se izračuna kot produkt dolžin obeh vektorjev in kosinusa vmesnega kota. 
def dot(vec1, vec2):
    return vec1.x * vec2.x + vec1.y * vec2.y    

# calculate vector angle
# angle = arccos[(xa * xb + ya * yb) / (√(xa2 + ya2) * √(xb2 + yb2))]

def angle_between(vec1, vec2):
    return math.acos(dot(vec1, vec2))


#-----------------------------------------------------------------------------
#----------------------DISTANCE AND LENGTH FUNCTIONS--------------------------
#-----------------------------------------------------------------------------



# vector lengt squared, faster
# pitagora a^2+b^2 = c^2
def length_sqr(vec):
    return vec.x**2 + vec.y**2

# vector length
def length(vec):
    return math.sqrt(length_sqr(vec))

# distance between vector squared, faster
def dist_sqr(vec1, vec2):
    return length_sqr(vec1 - vec2)

# distance between vector squared, faster
def dist(vec1, vec2):
    return length(vec1 - vec2)

# create a unit vector
def normalize(vec):
    vec_length = length(vec)
    
    # check if null size
    if vec_length < 0.00001:
        return Vector(0, 1)
    # return unit vector
    return Vector(vec.x / vec_length, vec.y / vec_length)

# reflections
def reflect(incident, normal):
    return incident - dot(normal, incident) * 2.0 * normal

def negate(vec):
    return Vector(-vec.x, -vec.y)

# rotation 90deg clockwise, perpendicual
def right(vec):
    return Vector(-vec.y, vec.x)

def left(vec):
    return negate(right(vec)) 

# create a random vector
def random_vector():
    return Vector(random.random()*2.0 - 1.0, random.random()*2.0-1.0)

def random_direction():
    return normalize(random_vector())

# so we dont have any issues with references
def copy(vec):
    return Vector(vec.x, vec.y)


# ---------- testing code    
def test_operator_overloads():
    a = Vector(5, 10)
    b = Vector(-5, 10)
    
    print(a.x, a.y)
    print(b.x, b.y)
    
    c = a + b #Vector class using __add__ operator overload
    print('__add__:', c.x, c.y)

    c = a - b #Vector class using __add__ operator overload
    print('__sub__:', c.x, c.y)

    c = a * b #Vector class using __add__ operator overload
    print('__mul__:', c.x, c.y)
    
    # normal operator overload
    c = a * 10
    print('__mul__:', c.x, c.y)

    # reverse operator overload
    c = 10 * a
    print('__rmul__:', c.x, c.y)
    
    c = a / b #Vector class using __add__ operator overload
    print('__truediv__:', c.x, c.y)


def test_functions():
    a = Vector(1, 1)
    b = Vector(0, 0)
    
    print('a = Vector(1, 1): ', a.x, a.y)
    print('b = Vector(0, 0)', b.x, b.y)

    print('Skalarni produkt (Dot product):', dot(a, b))
    print('angle_between a and b :', angle_between(a, b))   
    print('length of vector a:', length(a))  
    print('length_squared:', length_sqr(a))   
    
if __name__ == '__main__':
    test_functions()<file_sep># Pong

- create a game grid<file_sep>from OpenGL.GL import *
from OpenGL.GLU import *

import pygame
import os.path

class Material(object):

  def   init (self):

        self.name = ""
        self.texture_fname = None
        self.texture_id = None

class FaceGroup(object):

  def   init (self):

        self.tri_indices = []
        self.material_name = ""

class Model3D(object):

  def   init (self):

        self.vertices = []
        self.tex_coords = []
        self.normals = []
        self.materials = {}
        self.face_groups = []
        # Display list id for quick rendering
        self.display_list_id = None
<file_sep>import arcade

# Physics
MOVEMENT_SPEED = 8
JUMP_SPEED = 28
GRAVITY = 1.1

# Map
MAP_WIDTH = 40 * 128
MAP_HEIGHT = 7 * 128
TILE_WIDTH = 128

# Window
WINDOW_WIDTH = 1280
WINDOW_HEIGHT = 896
WINDOW_HALF_WIDTH = WINDOW_WIDTH // 2


class MyGameWindow(arcade.Window):
    def __init__(self, width, height, title):
        super().__init__(width, height, title)
        self.set_location(400, 100)

        arcade.set_background_color(arcade.color.BLACK)

        self.ground_list = None
        self.coins_list = None
        self.player_list = None
        self.player_sprite = None
        self.physics_engine = None
        self.collected_coins = 0

        self.setup()

    def setup(self):
        my_map = arcade.read_tiled_map("maps/my-map1.tmx", 1)
        self.ground_list = arcade.generate_sprites(my_map, "ground", 1)
        self.coins_list = arcade.generate_sprites(my_map, "coins", 1)

        self.player_list = arcade.SpriteList()
        self.player_sprite = arcade.Sprite("images/character.png", 1)
        self.player_sprite.center_x = 640
        self.player_sprite.center_y = 350
        self.player_list.append(self.player_sprite)

        self.physics_engine = arcade.PhysicsEnginePlatformer(self.player_sprite, self.ground_list, gravity_constant=GRAVITY)


    def on_draw(self):
        arcade.start_render()
        self.ground_list.draw()
        self.player_list.draw()
        self.coins_list.draw()
        arcade.draw_text(f"collected coins: {self.collected_coins}", arcade.get_viewport()[0] + 10, arcade.get_viewport()[2] + 866, arcade.color.GOLD, font_size=20)

    def clamp(self, value, mini, maxi):
        return max(min(value, maxi), mini)

    def on_update(self, delta_time):
        self.physics_engine.update()

        self.player_sprite.center_x = self.clamp(self.player_sprite.center_x, 0, MAP_WIDTH)

        if self.player_sprite.center_x > WINDOW_HALF_WIDTH and self.player_sprite.center_x < MAP_WIDTH - TILE_WIDTH - WINDOW_HALF_WIDTH:
            change_view = True
        else:
            change_view = False

        if change_view:
            arcade.set_viewport(self.player_sprite.center_x - WINDOW_HALF_WIDTH, self.player_sprite.center_x + WINDOW_HALF_WIDTH, 0, WINDOW_HEIGHT)

        coins_hit = arcade.check_for_collision_with_list(self.player_sprite, self.coins_list)
        for coin in coins_hit:
            self.collected_coins += 1
            coin.kill()


    def on_key_press(self, symbol, modifiers):
        if symbol == arcade.key.RIGHT:
            self.player_sprite.change_x = MOVEMENT_SPEED
        if symbol == arcade.key.LEFT:
            self.player_sprite.change_x = -MOVEMENT_SPEED
        if symbol == arcade.key.UP:
            if self.physics_engine.can_jump():
                self.player_sprite.change_y = JUMP_SPEED

    def on_key_release(self, symbol, modifiers):
        if symbol == arcade.key.LEFT or symbol == arcade.key.RIGHT:
            self.player_sprite.change_x = 0


MyGameWindow(WINDOW_WIDTH, WINDOW_HEIGHT, 'Simple Platformer template')
arcade.run()
<file_sep>
# calculation positions

Listing 5-14. Calculating Positions

```python
# point A
A = (10.0, 20.0)
# Point B
B = (30.0, 35.0)
# vector of distance between points AB
AB = Vector2.from_points(A, B)
# step vector, length of 1/10 AB
step = AB * .1
#start position vector at point A
position = Vector2(A[0], A[1])
for n in range(10):
    position += step
    print(position)
```

<file_sep>pygame.mixer.music.load("techno.ogg")
pygame.mixer.music.play()
<file_sep>    def read_obj(self, fname):

        current_face_group = None

        file_in = open(fname)

        for line in file_in:

            # Parse command and data from each line
            words = line.split()
            command = words[0]
            data = words[1:]

            if command == 'mtllib': # Material library

                model_path = os.path.split(fname)[0]
                mtllib_path = os.path.join( model_path, data[0] )                                
                self.read_mtllib(mtllib_path)
                
            elif command == 'v': # Vertex
                x, y, z = data
                vertex = (float(x), float(y), float(z))
                self.vertices.append(vertex)

            elif command == 'vt': # Texture coordinate

                s, t = data
                tex_coord = (float(s), float(t))
                self.tex_coords.append(tex_coord)

            elif command == 'vn': # Normal

                x, y, z = data
                normal = (float(x), float(y), float(z))
                self.normals.append(normal)

            elif command == 'usemtl' : # Use material

                current_face_group = FaceGroup()
                current_face_group.material_name = data[0]
                self.face_groups.append( current_face_group )

            elif command == 'f':

                assert len(data) ==  3, "Sorry, only triangles are supported"

                # Parse indices from triples
                for word in data:
                    vi, ti, ni = word.split('/')
                    indices = (int(vi) - 1, int(ti) - 1, int(ni) - 1)
                    current_face_group.tri_indices.append(indices)


        for material in self.materials.values():

            model_path = os.path.split(fname)[0]
            texture_path = os.path.join(model_path, material.texture_fname)
            texture_surface = pygame.image.load(texture_path)
            texture_data = pygame.image.tostring(texture_surface, 'RGB', True)

            material.texture_id = glGenTextures(1)
            glBindTexture(GL_TEXTURE_2D, material.texture_id)

            glTexParameteri( GL_TEXTURE_2D,
                             GL_TEXTURE_MAG_FILTER,
                             GL_LINEAR)
            glTexParameteri( GL_TEXTURE_2D,
                             GL_TEXTURE_MIN_FILTER,
                             GL_LINEAR_MIPMAP_LINEAR)

            glPixelStorei(GL_UNPACK_ALIGNMENT,1)
            width, height = texture_surface.get_rect().size
            gluBuild2DMipmaps( GL_TEXTURE_2D,
                               3,
                               width,
                               height,
                               GL_RGB,
                               GL_UNSIGNED_BYTE,
                               texture_data)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Dec 15 18:09:41 2020

@author: crtom
"""

import pygame
import sys

from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT

pygame.init()

# returns pygame.Surface objet for window
DISPLAYSURF = pygame.display.set_mode((400,300))

pygame.display.set_caption('Hello World!')

while True:
    
    # event handling
    for event in pygame.event.get():
        
        # event objects have type attribute
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    
    # draws surface object stored in DISPLAYSURF
    pygame.display.update()

    pygame.time.wait(100)<file_sep>import pygame
import os

letterX = pygame.image.load(os.path.join('res', 'letterX.png'))
letterO = pygame.image.load(os.path.join('res', 'letterO.png'))


class Grid:
    def __init__(self):
        self.grid_lines = [((0,200), (600,200)), # first horizontal line
                           ((0,400), (600,400)), # second horizontal line
                           ((200,0), (200,600)), # first vertical line
                           ((400,0), (400,600))] # second vertical line

        self.grid = [[0 for x in range(3)] for y in range(3)]
        self.switch_player = True
        # search directions  N         NW        W       SW       S       SE      E       NE
        self.search_dirs = [(0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1)]
        self.game_over = False



    def draw(self, surface):
        for line in self.grid_lines:
            pygame.draw.line(surface, (200,200,200), line[0], line[1], 2)

        for y in range(len(self.grid)):
            for x in range(len(self.grid[y])):
                if self.get_cell_value(x, y) == "X":
                    surface.blit(letterX, (x*200, y*200))
                elif self.get_cell_value(x, y) == "O":
                    surface.blit(letterO, (x*200, y*200))


    def get_cell_value(self, x, y):
        return self.grid[y][x]

    def set_cell_value(self, x, y, value):
        self.grid[y][x] = value

    def get_mouse(self, x, y, player):
        if self.get_cell_value(x, y) == 0:
            self.switch_player = True
            if player == "X":
                self.set_cell_value(x, y, "X")
            elif player == "O":
                self.set_cell_value(x, y, "O")
            self.check_grid(x, y, player)
        else:
            self.switch_player = False

    def is_within_bounds(self, x, y):
        return x >= 0 and x < 3 and y >= 0 and y < 3

    def check_grid(self, x, y, player):
        count = 1
        for index, (dirx, diry) in enumerate(self.search_dirs):
            if self.is_within_bounds(x+dirx, y+diry) and self.get_cell_value(x+dirx, y+diry) == player:
                count += 1
                xx = x + dirx
                yy = y + diry
                if self.is_within_bounds(xx+dirx, yy+diry) and self.get_cell_value(xx+dirx, yy+diry) == player:
                    count += 1
                    if count == 3:
                        break
                if count < 3:
                    new_dir = 0
                    # mapping the indices to opposite direction: 0-4 1-5 2-6 3-7 4-0 5-1 6-2 7-3
                    if index == 0:
                        new_dir = self.search_dirs[4] # N to S
                    elif index == 1:
                        new_dir = self.search_dirs[5] # NW to SE
                    elif index == 2:
                        new_dir = self.search_dirs[6] # W to E
                    elif index == 3:
                        new_dir = self.search_dirs[7] # SW to NE
                    elif index == 4:
                        new_dir = self.search_dirs[0] # S to N
                    elif index == 5:
                        new_dir = self.search_dirs[1] # SE to NW
                    elif index == 6:
                        new_dir = self.search_dirs[2] # E to W
                    elif index == 7:
                        new_dir = self.search_dirs[3] # NE to SW

                    if self.is_within_bounds(x + new_dir[0], y + new_dir[1]) \
                            and self.get_cell_value(x + new_dir[0], y + new_dir[1]) == player:
                        count += 1
                        if count == 3:
                            break
                    else:
                        count = 1

        if count == 3:
            print(player, 'wins!')
            self.game_over = True
        else:
            self.game_over = self.is_grid_full()


    def is_grid_full(self):
        for row in self.grid:
            for value in row:
                if value == 0:
                    return False
        return True

    def clear_grid(self):
        for y in range(len(self.grid)):
            for x in range(len(self.grid[y])):
                self.set_cell_value(x, y, 0)

    def print_grid(self):
        for row in self.grid:
            print(row)

<file_sep>tank.explode() # Do explosion visual 
explosion_channel = explosion_sound.play() 
if explosion_channel is not None:
    left, right = stereo_pan(tank.position.x, SCREEN_SIZE[0])
    explosion_channel.set_volume(left, right)
<file_sep>self.move_forward()
if self.hit_wall():
    self.change_direction()
<file_sep>    def __del__(self):

        #Called when the model is cleaned up by Python
        self.free_resources()

    def free_resources(self):

        # Delete the display list and textures
        if self.display_list_id is not None:
            glDeleteLists(self.display_list_id, 1)            
            self.display_list_id = None

        # Delete any textures we used
        for material in self.materials.values():
            if material.texture_id is not None:                
                glDeleteTextures(material.texture_id)
                
        # Clear all the materials
        self.materials.clear()        
        
        # Clear the geometry lists
        del self.vertices[:]
        del self.tex_coords[:]
        del self.normals[:]        
        del self.face_groups[:]   
<file_sep>from math import radians

from OpenGL.GL import *
from OpenGL.GLU import *

import pygame
from pygame.locals import *

# Import the Model3D class
import model3d

SCREEN_SIZE = (800, 600)

def resize(width, height):

    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(60.0, float(width)/height, .1, 1000.)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()


def init():

    # Enable the GL features we will be using
    glEnable(GL_DEPTH_TEST)
    glEnable(GL_LIGHTING)
    glEnable(GL_TEXTURE_2D)
    glShadeModel(GL_SMOOTH)

    # Enable light 1 and set position
    glEnable(GL_LIGHTING)
    glEnable(GL_LIGHT0)
    glLight(GL_LIGHT0, GL_POSITION,  (0, .5, 1))


def run():

    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE, FULLSCREEN|HWSURFACE|OPENGL|DOUBLEBUF)

    resize(*SCREEN_SIZE)
    init()    
    
    # Read the skybox model
    sky_box = model3d.Model3D()
    sky_box.read_obj('tanksky/skybox.obj')        
    
    # Set the wraping mode of all textures in the sky-box to GL_CLAMP_TO_EDGE
    for material in sky_box.materials.values():
        
        glBindTexture(GL_TEXTURE_2D, material.texture_id)    
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)        

    
    # Used to rotate the world
    mouse_x = 0.0
    mouse_y = 0.0    
    
    #Don't display the mouse cursor
    pygame.mouse.set_visible(False)

    while True:

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                quit()
            if event.type == KEYDOWN:
                pygame.quit()
                quit()

        # We don't need to clear the color buffer (GL_COLOR_BUFFER_BIT)
        # because the skybox covers the entire screen 
        glClear(GL_DEPTH_BUFFER_BIT)        

        glLoadIdentity()                        

        mouse_rel_x, mouse_rel_y = pygame.mouse.get_rel()
        mouse_x += float(mouse_rel_x) / 5.0
        mouse_y += float(mouse_rel_y) / 5.0
                
        # Rotate around the x and y axes to create a mouse-look camera
        glRotatef(mouse_y, 1, 0, 0)
        glRotatef(mouse_x, 0, 1, 0)        

        # Disable lighting and depth test
        glDisable(GL_LIGHTING)
        glDepthMask(False)
        
        # Draw the skybox
        sky_box.draw_quick()
        
        # Re-enable lighting and depth test before we redraw the world
        glEnable(GL_LIGHTING)
        glDepthMask(True)        
        
        # Here is where we would draw the rest of the world in a game

        pygame.display.flip()

if __name__ == "__main__":
    run()


<file_sep>import pygame
from pygame.locals import *
from random import randint
from gameobjects.vector2 import Vector2

SCREEN_SIZE = (640, 480)

# In pixels per second, per second
GRAVITY = 250.0
# Increase for more bounciness, but don't go over 1!
BOUNCINESS = 0.7

def stero_pan(x_coord, screen_width):

    right_volume = float(x_coord) / screen_width
    left_volume = 1.0 - right_volume

    return (left_volume, right_volume)


class Ball(object):

    def __init__(self, position, speed, image, bounce_sound):

        self.position = Vector2(position)
        self.speed = Vector2(speed)
        self.image = image
        self.bounce_sound = bounce_sound
        self.age = 0.0

    def update(self, time_passed):

        w, h = self.image.get_size()

        screen_width, screen_height = SCREEN_SIZE

        x, y = self.position
        x -= w/2
        y -= h/2

        # Has the ball bounce
        bounce = False

        # Has the ball hit the bottom of the screen?
        if y + h >= screen_height:
            self.speed.y = -self.speed.y * BOUNCINESS
            self.position.y = screen_height - h / 2.0 - 1.0
            bounce = True

        # Has the ball hit the left of the screen?
        if x <= 0:
            self.speed.x = -self.speed.x * BOUNCINESS
            self.position.x = w / 2.0 + 1
            bounce = True

        # Has the ball hit the right of the screen
        elif x + w >= screen_width:
            self.speed.x = -self.speed.x * BOUNCINESS
            self.position.x = screen_width - w / 2.0 - 1
            bounce = True

        # Do time based movement
        self.position += self.speed * time_passed
        # Add gravity
        self.speed.y += time_passed * GRAVITY

        if bounce:
            self.play_bounce_sound()

        self.age += time_passed


    def play_bounce_sound(self):

        channel = self.bounce_sound.play()

        if channel is not None:
            # Get the left and right volumes
            left, right = stero_pan(self.position.x, SCREEN_SIZE[0])
            channel.set_volume(left, right)


    def render(self, surface):

        # Draw the sprite center at self.position
        w, h = self.image.get_size()
        x, y = self.position
        x -= w/2
        y -= h/2
        surface.blit(self.image, (x, y))


def run():

    # Initialise 44KHz 16-bit stero sound
    pygame.mixer.pre_init(44100, 16, 2, 1024*4)
    pygame.init()
    pygame.mixer.set_num_channels(8)
    screen = pygame.display.set_mode(SCREEN_SIZE, 0)

    print(pygame.display.get_wm_info())
    hwnd = pygame.display.get_wm_info()["window"]
    x, y = (200, 200)

    pygame.mouse.set_visible(False)

    clock = pygame.time.Clock()

    ball_image = pygame.image.load("ball.png").convert_alpha()
    mouse_image = pygame.image.load("mousecursor.png").convert_alpha()

    # Load the sound file
    bounce_sound = pygame.mixer.Sound("bounce.wav")

    balls = []

    while True:

        for event in pygame.event.get():

            if event.type == QUIT:
                pygame.quit()
                quit()

            if event.type == MOUSEBUTTONDOWN:

                # Create a new ball at the mouse position
                random_speed = ( randint(-400, 400), randint(-300, 0) )
                new_ball = Ball( event.pos,
                                 random_speed,
                                 ball_image,
                                 bounce_sound )
                balls.append(new_ball)

        time_passed_seconds = clock.tick() / 1000.

        screen.fill((255, 255, 255))

        dead_balls = []

        for ball in balls:

            ball.update(time_passed_seconds)
            ball.render(screen)

            # Make not of any balls that are older than 10 seconds
            if ball.age > 10.0:
                dead_balls.append(ball)

        # remove any 'dead' balls from the main list
        for ball in dead_balls:

            balls.remove(ball)

        # Draw the mouse cursor
        mouse_pos = pygame.mouse.get_pos()
        screen.blit(mouse_image, mouse_pos)

        pygame.display.update()

if __name__ == "__main__":

    run()
<file_sep>from math import radians

from OpenGL.GL import *
from OpenGL.GLU import *

import pygame
from pygame.locals import *

SCREEN_SIZE = (800, 600)

def resize(width, height):

    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(60.0, float(width)/height, .1, 1000.)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

def init():

    glEnable(GL_TEXTURE_2D)
    glClearColor(1.0, 1.0, 1.0, 0.0)

def run():

    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|OPENGL|DOUBLEBUF)

    resize(*SCREEN_SIZE)
    init()

    # Load the textures
    texture_surface = pygame.image.load("sushitex.png")
    # Retrieve the texture data
    texture_data = pygame.image.tostring(texture_surface, 'RGB', True)

    # Generate a texture id
    texture_id = glGenTextures(1)
    # Tell OpenGL we will be using this texture id for texture operations
    glBindTexture(GL_TEXTURE_2D, texture_id)

    # Tell OpenGL how to scale images
    glTexParameteri(GL_TEXTURE_2D,  GL_TEXTURE_MAG_FILTER, GL_LINEAR) 
    glTexParameteri(GL_TEXTURE_2D,  GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)

    # Tell OpenGL that data is aligned to byte boundries
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)

    # Get the dimensions of the image
    width, height = texture_surface.get_rect().size


    gluBuild2DMipmaps( GL_TEXTURE_2D, 
                   3, 
                   width, 
                   height, 
                   GL_RGB, 
                   GL_UNSIGNED_BYTE, 
                   texture_data )


    clock = pygame.time.Clock()

    tex_rotation = 0.0

    while True:

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                quit()


        time_passed = clock.tick()
        time_passed_seconds = time_passed / 1000.
        tex_rotation += time_passed_seconds * 360.0 / 8.0


        # Clear the screen (similar to fill)
        glClear(GL_COLOR_BUFFER_BIT)

        # Clear the model-view matrix
        glLoadIdentity()

        # Set the modelview matrix
        glTranslatef(0.0, 0.0, -600.0)
        glRotate(tex_rotation, 1, 0, 0)

        # Draw a quad (4 vertices, 4 texture coords)
        glBegin(GL_QUADS)

        glTexCoord2f(0, 3) 
        glVertex3f(-300, 300, 0) 
         
        glTexCoord2f(3, 3) 
        glVertex3f(300, 300, 0) 
         
        glTexCoord2f(3, 0) 
        glVertex3f(300, -300, 0) 
         
        glTexCoord2f(0, 0) 
        glVertex3f(-300, -300, 0)

        glEnd()

        pygame.display.flip()

    glDeleteTextures(texture_id)

if __name__ == "__main__":
    run()
<file_sep># pygame-projects


## Links

http://programarcadegames.com/index.php?chapter=example_code

## 1. Import & Initialization

```python
import pygame
pygame.init()
```

## 2. Display, Surfaces, Images, and Transformations

- for computers (x=0,y=0) is top left corner

## Create screen

```python
screen = pygame.display.set_mode((width, height)) 
```

Initializes and creates the window where your game will run, and returns a Surface, here assigned to the name “screen.” Note: you’re passing a tuple, hence the double parenthesis.

## Set title

```python
display.set_caption('Title of the window')
```

## Update - Draw Display: blitting is drawing

```python
pygame.display.update()
```

Redraws the main display surface if argument list is empty. Optionally, you can pass it a list of Rects, and it will just redraw the portions of the screen indicated in the list.

```python
pygame.display.get_surface()
```

Returns a reference to the Surface instantiated with the set_mode() function.
Use this if you forget to assign set_mode() to a name.

```python
screen.blit()
```

Note: “Surface” is the name of the class, so you’d use the name you assigned when you created the surface. For example, if your main display Surface was called “screen” (as it is above), you’d use screen.blit(), not Surface.blit()

```python
Copy pixels from one Surface to another

Surface.blit(sourceSurface, destinationRect, optionalSourceRect) 
```

Used to draw images to the screen. If you omit the third argument, the entire source Surface is copied to the area of the destination Surface specified by the Rect in the second argument

## Drawing objects - primitives

- rectangle

  pygame.draw.rect(surface, color, rectangle_tuple, width)

- polygon

- circle

  pygame.draw.circle(surface, color, center_point, radius, width)

- ellipse

  pygame.draw.ellipse(surface, color, bounding_rectangle, width)

- line

  pygame.draw.line(surface, color, start_point, end_point, width) 

  pygame.draw.lines(surface, color, closed, pointlist, width)

- pixel

- pixel array

```python
pygame.draw.line(Surface, color, (x1,y1), (x2,y2), width)
```

## Colour objects

```python
Creates a color object with RGBA as arguments.

pygame.Color(R, G, B)
black = (0,0,0)
white = (255,255,255)
red   = (255,0,0)
green = (0,255,0)
blue  = (0,0,255)
```

```python
Fills surface with a solid color.

Surface.fill(R,G,B)
```

# Rectangle

pygame.Rect(top-left-corner-x, top-lef-corner-y, width, height)

spamRect = pygame.Rect(10, 20, 200, 300)

### pygame.Rect: rectangle attributes

**myRect.left**					 integer
**myRect.right	 ** 			integer
**myRect.top** 					integer
**myRect.bottom** 			integer
**myRect.centerx			** integer
**myRect.centery**			 integer
**myRect.width** 				integer
**myRect.height**				integer
**myRect.size** 				   A tuple of two ints: (width, height)
**myRect.topleft** 			 A tuple of two ints: (left, top)
**myRect.topright** 		  A tuple of two ints: (right, top)
**myRect.bottomleft** 	 A tuple of two ints: (left, bottom)
**myRect.bottomright**   A tuple of two ints: (right, bottom)
**myRect.midleft** 			A tuple of two ints: (left, centery)
**myRect.midright** 		 A tuple of two ints: (right, centery)
**myRect.midtop** 			A tuple of two ints: (centerx, top)
**myRect.midbottom** 	A tuple of two ints: (centerx, bottom)

All of these attributes can be assigned to:

```
rect1.right = 10
rect2.center = (20,30)
```

## Convert

Before you use convert() on any surface, screen has to be initialized with set_mode()

```
import pygame
pygame.init()
image = pygame.image.load("file_to_load.jpg")
print(image.get_rect().size) # you can get size
screen = pygame.display.set_mode(image.get_rect().size, 0, 32)
image = image.convert() # now you can convert 
```

- Changes pixel format

```python
Surface.convert()
```

Changes pixel format of the Surface’s image to the format used by the main display. Makes things faster. Use it.

```python
Changes pixel format (transparency)

Surface.convert_alpha()
```

Same as above, but when the Surface’s image has alpha transparency values to deal with.

```python
Get dimensions and location of surface

Surface.get_rect()
```

Returns a Rect that will tell you the dimensions and location of the surface.

```python
Loads image from disk and gets image size

image = pygame.image.load('filename')
image_width = image.get_rect().size[0]
image_height = image.get_rect().size[1]

```

Note that in Python, directories are indicated by a forward slash, unlike Windows 

- Rotates Surface counterclockwise by degrees

```python
pygame.transform.rotate(Surface, angle)
```

- Resizes Surface to new resolution

```python
pygame.transform.scale(Surface, (width, height)) 
```

## Circles

```python
pygame.draw.circle(gameDisplay, self.colour, (self.x, self.y), self.size, self.thickness)

## Rectangles
- Returns a Rect moved x pixels horizontally and y pixels vertically
Rect.move(x, y)
```

- Moves the Rect x pixels horizontally and y pixels vertically

```python
Rect.move_ip(x, y) 
```

Assignable attributes (in most cases, a tuple of x and y values):
top, left, bottom, right, topleft, bottomleft, topright, bottomright, midtop, midleft, midbottom, midright, center, centerx, centery, size, width, height

# Display examples

- Classical way of creating image on display

```python
    #1.) draw background, dont paint it over image
    gameDisplay.fill(white)
    #2.) draw image on position (x,y)
    x = display_width*0.45
    y = display_height*0.8
    #use blit to add image to surface
    gameDisplay.blit(carImg,(x,y))
    #3.) update display
    pygame.display.update()
```

## Time

- Create a Clock object 

```python
pygame.time.Clock() 
```

(assign this to a name), which you can then call the tick() method on to find out how much time has passed since the last time you called tick()

```python
Returns the clock framerate

pygame.time.Clock.get_fps()
```

```python
Pause game for time specified

pygame.time.delay(milliseconds)
```

```python
Returns the number of milliseconds passed since pygame.init() was called

pygame.time.get_ticks() 
```

```python
Returns the time used in previous tick

pygame.time.Clock.get_time()
```

## Joystick

    my_joystick = pygame.joystick.Joystick(0)
    my_joystick.init()

## Events

```python
Key press events
        #if key pressed start moving
        if event.type == pygame.EVENTDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -5
            elif event.key == pygame.K_RIGHT:
                x_change = 5
                
        #if key released stop moving
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT::
                x_change = 0

```

this code changes position only if key is pressed down.
When key is released. change is zero.

```python
Event for closing main windows press on (x)

for event in pygame.event.get():
    if event.type == pygame.QUIT:
    pygame.quit()
```

One of the most common ways of event handling, Its a loop which constantly checks for events, quits if the QUIT event is triggered and
prevents your game from freezing.

```python
Places a new event that you specify on the queue

pygame.event.post()
```

```python
Creates a new event object

pygame.event.Event()
```

```python
Gets the event from the queue

pygame.event.get()
```

```python
Remove all the events from the queue

pygame.event.clear()
```

Events are always in a queue. Order of events does matter.

```python
Get a list of events

pygame.event.get() 
```

Call once per frame to get a list of events that occurred since the last time pygame.event.get() was called.

- Event type values:
  - QUIT one
  - KEYDOWN unicode, key, mod (if you import pygame.locals, compare to e.g. K_a for “a”)
  - KEYUP key, mod
  - MOUSEMOTION pos, rel, buttons
  - MOUSEBUTTONUP pos, button
  - MOUSEBUTTONDOWN pos, button
  - JOYAXISMOTION joy, axis, value

### Mouse events

- lmb, mmb, rmb = pygame.mouse.get_pressed Returns the mouse buttons pressed as a tuple of three
  booleans, one for the left, middle, and right mouse buttons.
-  pygame.mouse.get_rel—Returns the relative mouse movement (or mickeys) as a tuple
  with the x and y relative movement.
- pygame.mouse.get_pos—Returns the mouse coordinates as a tuple of the x and y values.
- pygame.mouse.set_pos—Sets the mouse position. Takes the coordinate as a tuple or list
  for x and y.
- pygame.mouse.set_visible—Changes the visibility of the standard mouse cursor. If
  False, the cursor will be invisible
- pygame.mouse.get_focused—Returns True if the Pygame window is receiving mouse
  input. When Pygame runs in a window, it will only receive mouse input when the window
  is selected and at the front of the display.
- pygame.mouse.set_cursor—Sets the standard cursor image. This is rarely needed since
  better results can be achieved by blitting an image to the mouse coordinate.
- pyGame.mouse.get_cursor—Gets the standard cursor image. See the previous item.

### Joystic Events

• pygame.joystick.init—Initializes the joystick module. This is called automatically by
pygame.init, so you rarely need to call it yourself.
• pygame.joystick.quit—Uninitializes the joystick module. Like init, this function is
called automatically and so is not often needed.
• pygame.joystick.get_init—Returns True if the joystick module has been initialized. If it
returns False, the following joystick functions won’t work.
• pygame.joystick.get_count—Returns the number of joysticks currently plugged into
the computer.
• pygame.joystick.Joystick—Creates a new joystick object that is used to access all information
for that stick. The constructor takes the ID of the joystick—the first joystick is ID
0, then ID 1, and so on, up to the number of joysticks available on the system.

## Fonts

```python
f = pygame.font.Font(None, 32) 
```

Creates a font object of size 32 using the default font. If you know where the .TTF file of the font you want to use is located, you can use the filename as the first argument

- create a message and display it on screen

```

```

## Rendering

```python
surf = f.render(“Hello”, 1, (255,0,255), (255,255,0))
```

Creates a surface of rendered text using the font of the font object. The first argument is the text itself, the second is whether the text is anti-aliased or not (0 for no), the third argument is a 3-item tuple that defines the RGB values of the color of the text, and the fourth (optional) argument is a 3-item tuple that defines the RGB values of the color of the background. If the fourth argument is not specified, the background will be transparent. This command creates a surface that has the word Hello in magenta on a yellow background, which can then be blitted to the screen like any surface. It’s quite ugly.

## Audio

### Initialize

```
pygame.mixer.init()
```

### Playing Sound Effects

```python
# 1. create a sound object
soundObj = pygame.mixer.Sound('beeps.wav') # must be an uncompressed WAV or OGG
# 2. start sound
soundObj.play()
# 3. wait and let the sound play for 1 second
time.sleep(1) 
# 4. stop sound
soundObj.stop()
```

### Playing Background

For background music, you do not create objects, since you can only have one music track running at any time. Music is streamed, never fully loaded at once. You can use MIDI files.

```python
pygame.mixer.music.load(filename)
pygame.mixer.music.play(loops=0, offset) #  -1 to repeat indefinitely, offset in sec
pygame.mixer.music.stop()
```

# Sprites,module with basic game object classes

| [pygame.sprite.Sprite](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite) | Simple base class for visible game objects.                  |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| [pygame.sprite.DirtySprite](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.DirtySprite) | A subclass of Sprite with more attributes and features.      |
| [pygame.sprite.Group](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group) | A container class to hold and manage multiple Sprite objects. |
| [pygame.sprite.RenderPlain](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.RenderPlain) | Same as pygame.sprite.Group                                  |
| [pygame.sprite.RenderClear](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.RenderClear) | Same as pygame.sprite.Group                                  |
| [pygame.sprite.RenderUpdates](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.RenderUpdates) | Group sub-class that tracks dirty updates.                   |
| [pygame.sprite.OrderedUpdates](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.OrderedUpdates) | RenderUpdates sub-class that draws Sprites in order of addition. |
| [pygame.sprite.LayeredUpdates](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.LayeredUpdates) | LayeredUpdates is a sprite group that handles layers and draws like OrderedUpdates. |
| [pygame.sprite.LayeredDirty](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.LayeredDirty) | LayeredDirty group is for DirtySprite objects. Subclasses LayeredUpdates. |
| [pygame.sprite.GroupSingle](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.GroupSingle) | Group container that holds a single sprite.                  |
| [pygame.sprite.spritecollide](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.spritecollide) | Find sprites in a group that intersect another sprite.       |
| [pygame.sprite.collide_rect](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_rect) | Collision detection between two sprites, using rects.        |
| [pygame.sprite.collide_rect_ratio](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_rect_ratio) | Collision detection between two sprites, using rects scaled to a ratio. |
| [pygame.sprite.collide_circle](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_circle) | Collision detection between two sprites, using circles.      |
| [pygame.sprite.collide_circle_ratio](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_circle_ratio) | Collision detection between two sprites, using circles scaled to a ratio. |
| [pygame.sprite.collide_mask](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide_mask) | Collision detection between two sprites, using masks.        |
| [pygame.sprite.groupcollide](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.groupcollide) | Find all sprites that collide between two groups.            |
| [pygame.sprite.spritecollideany](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.spritecollideany) | Simple test if a sprite intersects anything in a group.      |

### Class pygame.sprite.Sprite

*Simple base class for visible game objects.*

| [pygame.sprite.Sprite.update](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.update) | method to control sprite behavior       |
| ------------------------------------------------------------ | --------------------------------------- |
| [pygame.sprite.Sprite.add](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.add) | add the sprite to groups                |
| [pygame.sprite.Sprite.remove](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.remove) | remove the sprite from groups           |
| [pygame.sprite.Sprite.kill](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.kill) | remove the Sprite from all Groups       |
| [pygame.sprite.Sprite.alive](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.alive) | does the sprite belong to any groups    |
| [pygame.sprite.Sprite.groups](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite.groups) | list of Groups that contain this Sprite |

### Class pygame.sprite.Group

*A container class to hold and manage multiple Sprite objects.*

| [pygame.sprite.Group.sprites](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.sprites) | list of the Sprites this Group contains     |
| ------------------------------------------------------------ | ------------------------------------------- |
| [pygame.sprite.Group.copy](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.copy) | duplicate the Group                         |
| [pygame.sprite.Group.add](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.add) | add Sprites to this Group                   |
| [pygame.sprite.Group.remove](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.remove) | remove Sprites from the Group               |
| [pygame.sprite.Group.has](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.has) | test if a Group contains Sprites            |
| [pygame.sprite.Group.update](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.update) | call the update method on contained Sprites |
| [pygame.sprite.Group.draw](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.draw) | blit the Sprite images                      |
| [pygame.sprite.Group.clear](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.clear) | draw a background over the Sprites          |
| [pygame.sprite.Group.empty](https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.empty) | remove all Sprites                          |

## Default subclassing Sprite Object

```python
class Block(pygame.sprite.Sprite):
    # Constructor. Pass in the color of the block,
    # and its x and y position
    def __init__(self, color, width, height):
       # Call the parent class (Sprite) constructor
       pygame.sprite.Sprite.__init__(self)

       # Create an image of the block, and fill it with a color.
       # This could also be an image loaded from the disk.
       self.image = pygame.Surface([width, height])
       self.image.fill(color)

       # Fetch the rectangle object that has the dimensions of the image
       # Update the position of this object by setting the values of rect.x and rect.y
       self.rect = self.image.get_rect()
```

# Groups, and Collision Detection

Check if a sprite collides with a group. If collision, returns True

```python
# check if sprite and a group walls collides
if pg.sprite.spritecollideany(self, self.game.walls)
```
Check for collision

```
hits = pg.sprite.spritecollide(self, self.game.walls, False) 
```



```python
class Monster(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(“monster.png”)
self.rect = self.image.get_rect()
...
monsters = pygame.sprite.RenderPlain((monster1, monster2, monster3))
monsters.update()
monsters.draw()
Rect.contains(Rect): return True or False
Rect.collidepoint(x, y): return True or False
Rect.colliderect(Rect): return True or False
Rect.collidelist(list): return index
pygame.sprite.spritecollide(sprite, group, dokill):
return Sprite_list
pygame.sprite.groupcollide(group1, group2, dokill1,
dokill2): return Sprite_dict
```

### Updating sprites icons

This two codes are the same

```python
    self.all_sprites.draw(self.screen)
```
```python
for sprite in self.all_sprites:
    self.screen.blit(sprite.image, sprite.rect)
```
## OOP Examples

- drawing a circle

```
class Particle:
  def __init__(self, (x, y), size):
    self.x = x
    self.y = y
    self.size = size
    self.colour = (0, 0, 255)
    self.thickness = 1

    def display(self):
      pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size, self.thickness)

particle = Particle((150, 50), 15)
particle.display()
```

## Resources

- [PyGame with Python 3 WEBSITE](https://pythonprogramming.net/pygame-python-3-part-1-intro/)
- [PyGame with Python 3 YOUTUBE](https://www.youtube.com/watch?list=PLQVvvaa0QuDdLkP8MrOXLe_rKuf6r80KO&v=ujOTNg17LjI&feature=emb_title)
- [pygame cheat sheet](pygame-cheatsheet.pdf)
- [create an image with GIMP](https://www.youtube.com/watch?v=5myI73oFvAA)
- SW to create image with transparent background
  [GIMP open source image editor](https://www.gimp.org/)


# Examples

## Simplest pygame code

```python
import pygame

pygame.init()

#### Create a canvas on which to display everything ####
window = (400,400)
screen = pygame.display.set_mode(window)
#### Create a canvas on which to display everything ####

#### Create a surface with the same size as the window ####
background = pygame.Surface(window)
#### Create a surface with the same size as the window ####

#### Populate the surface with objects to be displayed ####
pygame.draw.rect(background,(0,255,255),(20,20,40,40))
pygame.draw.rect(background,(255,0,255),(120,120,50,50))
#### Populate the surface with objects to be displayed ####

#### Blit the surface onto the canvas ####
screen.blit(background,(0,0))
#### Blit the surface onto the canvas ####

#### Update the the display and wait ####
pygame.display.flip()
done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
#### Update the the display and wait ####

pygame.quit()
```

## 1_Intro

[readme](1_intro/readme.md)

## Tetris

[Python and Pygame Tutorial - Build Tetris! Full GameDev Course](https://www.youtube.com/watch?v=zfvxp7PgQ6c&t=1188s)

## Tile map editor

www.mapeditor.org

Loading .tmx files made from tile-editors. 

INSTAL pip install pytmx



## **GAME PHYSICS - MECHANICS**

### Tweening- easing functions

- linear
- quadratic
- cubic
- quartic
- quintic
- sinusoidal
- exponential
- crcular
- elastic
- back

```python
conda install -c conda-forge pytweening
```

<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 20:47:46 2020

@author: crtom
"""


import pygame

# you'll be able to shoot every 450ms
RELOAD_SPEED = 450

# the foes move every 1000ms sideways and every 3500ms down
MOVE_SIDE = 1000
MOVE_DOWN = 3500

screen = pygame.display.set_mode((300, 200))
clock = pygame.time.Clock()

pygame.display.set_caption("Micro Invader")

# create a bunch of events 
move_side_event = pygame.USEREVENT + 1
move_down_event = pygame.USEREVENT + 2
reloaded_event  = pygame.USEREVENT + 3

move_left, reloaded = True, True

invaders, colors, shots = [], [] ,[]
for x in range(15, 300, 15):
    for y in range(10, 100, 15):
        invaders.append(pygame.Rect(x, y, 7, 7))
        colors.append(((x * 0.7) % 256, (y * 2.4) % 256))

# set timer for the movement events
pygame.time.set_timer(move_side_event, MOVE_SIDE)
pygame.time.set_timer(move_down_event, MOVE_DOWN)

player = pygame.Rect(150, 180, 10, 7)

while True:
    clock.tick(40)
    if pygame.event.get(pygame.QUIT): break
    for e in pygame.event.get():
        if e.type == move_side_event:
            for invader in invaders:
                invader.move_ip((-10 if move_left else 10, 0))
            move_left = not move_left
        elif e.type == move_down_event:
            for invader in invaders:
                invader.move_ip(0, 10)
        elif e.type == reloaded_event:
            # when the reload timer runs out, reset it
            reloaded = True
            pygame.time.set_timer(reloaded_event, 0)

    for shot in shots[:]:
        shot.move_ip((0, -4))
        if not screen.get_rect().contains(shot):
            shots.remove(shot)
        else:
            hit = False
            for invader in invaders[:]:
                if invader.colliderect(shot):
                    hit = True
                    i = invaders.index(invader)
                    del colors[i]
                    del invaders[i]
            if hit:
                shots.remove(shot)

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_LEFT]: player.move_ip((-4, 0))
    if pressed[pygame.K_RIGHT]: player.move_ip((4, 0))

    if pressed[pygame.K_SPACE]: 
        if reloaded:
            shots.append(player.copy())
            reloaded = False
            # when shooting, create a timeout of RELOAD_SPEED
            pygame.time.set_timer(reloaded_event, RELOAD_SPEED)

    player.clamp_ip(screen.get_rect())

    screen.fill((0, 0, 0))

    for invader, (a, b) in zip(invaders, colors): 
        pygame.draw.rect(screen, (150, a, b), invader)

    for shot in shots: 
        pygame.draw.rect(screen, (255, 180, 0), shot)

    pygame.draw.rect(screen, (180, 180, 180), player)    
    pygame.display.flip()<file_sep>import pymunkoptions
pymunkoptions.options["debug"] = False

import pymunk
import arcade
from math import degrees

space = pymunk.Space()
space.gravity = 0, -1000

mass = 1
radius = 30

segment_shape1 = pymunk.Segment(space.static_body, (500,400), (1300,440), 2)
segment_shape1.elasticity = 0.8
segment_shape1.friction = 1.0
space.add(segment_shape1)

segment_shape2 = pymunk.Segment(space.static_body, (100,160), (900,100), 2)
segment_shape2.elasticity = 0.8
segment_shape2.friction = 1.0
space.add(segment_shape2)


class MyGameWindow(arcade.Window):
    def __init__(self, width, height, title):
        super().__init__(width, height, title)
        self.set_location(400, 200)

        arcade.set_background_color(arcade.color.BLACK)

        self.sprites = arcade.SpriteList()


    def on_draw(self):
        arcade.start_render()
        arcade.draw_lines([segment_shape1.a, segment_shape1.b], arcade.color.RED, 4)
        arcade.draw_lines([segment_shape2.a, segment_shape2.b], arcade.color.RED, 4)

        self.sprites.draw()


    def on_update(self, delta_time):
        space.step(delta_time)
        for index, sprite in enumerate(self.sprites):
            sprite.angle = degrees(space.bodies[index].angle)
            sprite.set_position(space.bodies[index].position.x, space.bodies[index].position.y)
            for body in space.bodies:
                if body.position.y < -100:
                    self.sprites.remove(sprite)
                    space.remove(body, body.shapes)


    def on_mouse_press(self, x, y, button, modifiers):
        if button == arcade.MOUSE_BUTTON_LEFT:
            circle_moment = pymunk.moment_for_circle(mass, 0, radius)
            circle_body = pymunk.Body(mass, circle_moment)
            circle_body.position = x, y
            circle_shape = pymunk.Circle(circle_body, radius)
            circle_shape.elasticity = 0.8
            circle_shape.friction = 1.0
            space.add(circle_body, circle_shape)
            self.sprites.append(arcade.Sprite("sprites/smile.png", center_x=circle_body.position.x, center_y=circle_body.position.y))



MyGameWindow(1280, 720, 'My game window')
arcade.run()
<file_sep>print("type (q) = Exit")
while True:
	user_input = input("type input")
	if user_input == "q":
		break
	print(user_input)<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Dec 15 18:09:41 2020

@author: crtom
"""

import pygame
import sys

from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT

def drawPoint(x,y,color):

    s = pygame.Surface((1,1))   # the object surface 1 x 1 pixel (a point!)

    s.fill(color)               # color as (r,g,b); e.g. (100,20,30)

    # now get an object 'rectangle' from the object surface and place it at position x,y

    r,r.x,r.y = s.get_rect(),x,y    

    screen.blit(s,r)            # link the object rectangle to the object surface

pygame.init()

# returns pygame.Surface objet for window
DISPLAYSURF = pygame.display.set_mode((400,300))

pygame.display.set_caption('Hello World!')

while True:
    
    # event handling
    for event in pygame.event.get():
        
        # event objects have type attribute
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    
    
    #drawPoint(1, 1, (0,0,0))
    #window_surface.set_at((x, y), my_color)
    DISPLAYSURF.set_at((100, 100), (255,255,0))
    # draws surface object stored in DISPLAYSURF
    pygame.display.update()

    pygame.time.wait(100)<file_sep>import pygame
from pygame.locals import *
from gameobjects.vector3 import Vector3
from gameobjects.matrix44 import Matrix44 as Matrix
from math import *
from random import randint

SCREEN_SIZE =  (640, 480)
CUBE_SIZE = 300

def calculate_viewing_distance(fov, screen_width):
    
    d = (screen_width/2.0) / tan(fov/2.0)
    return d


def run():
    
    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE, 0)
        
    font = pygame.font.SysFont("courier new", 16, True)
    
    ball = pygame.image.load("ball.png").convert_alpha()
    
    points = []
    
    fov = 75. # Field of view
    viewing_distance = calculate_viewing_distance(radians(fov), SCREEN_SIZE[0])
    
    # Create a list of points along the edge of a cube
    for x in range(0, CUBE_SIZE+1, 10):
        edge_x = x == 0 or x == CUBE_SIZE
        
        for y in range(0, CUBE_SIZE+1, 10):
            edge_y = y == 0 or y == CUBE_SIZE
            
            for z in range(0, CUBE_SIZE+1, 10):
                edge_z = z == 0 or z == CUBE_SIZE
                
                if sum((edge_x, edge_y, edge_z)) >= 2:
                    
                    point_x = float(x) - CUBE_SIZE/2
                    point_y = float(y) - CUBE_SIZE/2
                    point_z = float(z) - CUBE_SIZE/2
                    
                    points.append(Vector3(point_x, point_y, point_z))
        
    def point_z(point):
        return point[2]
    
    center_x, center_y = SCREEN_SIZE
    center_x /= 2
    center_y /= 2
    
    ball_w, ball_h = ball.get_size()
    ball_center_x = ball_w / 2
    ball_center_y = ball_h / 2
    
    camera_position = Vector3(0.0, 0.0, 600.)
        
    rotation = Vector3()
    rotation_speed = Vector3(radians(20), radians(20), radians(20))
    
    clock = pygame.time.Clock()
    
    # Some colors for drawing
    red = (255, 0, 0)
    green = (0, 255, 0)
    blue = (0, 0, 255)    
    white = (255, 255, 255)
    
    # Labels for the axes
    x_surface = font.render("X", True, white)
    y_surface = font.render("Y", True, white)
    z_surface = font.render("Z", True, white)
        
    while True:
        
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                quit()
        
        screen.fill((0, 0, 0))        
        
        time_passed = clock.tick()
        time_passed_seconds = time_passed / 1000.                
        
        rotation_direction = Vector3()
        
        #Adjust the rotation direction depending on key presses
        pressed_keys = pygame.key.get_pressed()
        
        if pressed_keys[K_q]:
            rotation_direction.x = +1.0
        elif pressed_keys[K_a]:
            rotation_direction.x = -1.0
                        
        if pressed_keys[K_w]:
            rotation_direction.y = +1.0
        elif pressed_keys[K_s]:
            rotation_direction.y = -1.0
        
        if pressed_keys[K_e]:
            rotation_direction.z = +1.0
        elif pressed_keys[K_d]:
            rotation_direction.z = -1.0
        
        # Apply time based movement to rotation
        rotation += rotation_direction * rotation_speed * time_passed_seconds
        
        # Build the rotation matrix
        rotation_matrix = Matrix.x_rotation(rotation.x)
        rotation_matrix *= Matrix.y_rotation(rotation.y)
        rotation_matrix *= Matrix.z_rotation(rotation.z)        
        
        transformed_points = []

        # Transform all the points and adjust for camera position
        for point in points:
            
            p = rotation_matrix.transform_vec3(point) - camera_position            
            
            transformed_points.append(p)
        
        transformed_points.sort(key=point_z)
        
        # Perspective project and blit all the points
        for x, y, z in transformed_points:            
            
            if z < 0:
                x = center_x + x * -viewing_distance / z
                y = center_y + -y * -viewing_distance / z
            
                screen.blit(ball, (x-ball_center_x, y-ball_center_y))
                
        
        # Function to draw a single axes, see below
        def draw_axis(color, axis, label):
            
            axis = rotation_matrix.transform_vec3(axis * 150.)
            SCREEN_SIZE =  (640, 480)
            center_x = SCREEN_SIZE[0] / 2.0
            center_y = SCREEN_SIZE[1] / 2.0
            x, y, z = axis - camera_position
                
            x = center_x + x * -viewing_distance / z
            y = center_y + -y * -viewing_distance / z
            
            pygame.draw.line(screen, color, (center_x, center_y), (x, y), 2)
            
            w, h = label.get_size()
            screen.blit(label, (x-w/2, y-h/2))
        
        # Draw the x, y and z axes
        x_axis = Vector3(1, 0, 0)
        y_axis = Vector3(0, 1, 0)
        z_axis = Vector3(0, 0, 1)        
        
        draw_axis(red, x_axis, x_surface)
        draw_axis(green, y_axis, y_surface)
        draw_axis(blue, z_axis, z_surface)
            
        # Display rotation information on screen
        degrees_txt = tuple(degrees(r) for r in rotation)
        rotation_txt = "Rotation: Q/A %.3f, W/S %.3f, E/D %.3f" % degrees_txt
        txt_surface = font.render(rotation_txt, True, white)
        screen.blit(txt_surface, (5, 5))
        
        # Displat the rotation matrix on screen
        matrix_txt = str(rotation_matrix)
        txt_y = 25
        for line in matrix_txt.split('\n'):
            txt_surface = font.render(line, True, white)
            screen.blit(txt_surface, (5, txt_y))
            txt_y += 20
            
        pygame.display.update()
        
if __name__ == "__main__":
    run()
    
    
    
<file_sep>from tank import Tank 
 
tanks = {"a":Tank("Alice"), "b":Tank("Bob"), "c":Tank("Carol") } 
alive_tanks = len(tanks) 
 
while alive_tanks > 1: 
 

      for tank_name in sorted( tanks.keys() ): 
            print(tank_name, tanks[tank_name])
 
      first = input("Who fires? ").lower() 
      second = input("Who at? " ).lower() 
 
      try: 
            first_tank = tanks[first] 
            second_tank = tanks[second] 
      except KeyError as name: 
            print("No such tank!", name)
            continue 
 
      if not first_tank.alive or not second_tank.alive: 
            print("One of those tanks is dead!")  
            continue 
 

      print("*" * 30)
 
      first_tank.fire_at(second_tank) 
      if not second_tank.alive: 
          alive_tanks -= 1  
 
      print("*" * 30)
 
for tank in tanks.values(): 
      if tank.alive: 
         print(tank.name, "is the winner!")  
         break 
<file_sep>"""
website: https://techwithtim.net/tutorials/game-development-with-python/pygame-tutorial/pygame-animation/
Character Animation
video: https://www.youtube.com/watch?v=2-DNswzCkqk&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5&index=2

"""

import pygame
from pygame.locals import *

from rgb_color_dictionary import *

pygame.init()

#create window
win = pygame.display.set_mode((500,500))
#set windows title
pygame.display.set_caption("First Game")

#load images for animation
walkRight =[
pygame.image.load("R1.png"),
pygame.image.load("R2.png"),
pygame.image.load("R3.png"),
pygame.image.load("R4.png"),
pygame.image.load("R5.png"),
pygame.image.load("R6.png"),
pygame.image.load("R7.png"),
pygame.image.load("R8.png"),
pygame.image.load("R9.png")]

walkLeft =[
pygame.image.load("L1.png"),
pygame.image.load("L2.png"),
pygame.image.load("L3.png"),
pygame.image.load("L4.png"),
pygame.image.load("L5.png"),
pygame.image.load("L6.png"),
pygame.image.load("L7.png"),
pygame.image.load("L8.png"),
pygame.image.load("L9.png")]

bg = pygame.image.load("bg.jpg")
char = pygame.image.load("standing.png")

#defining clock for the game
clock=pygame.time.Clock()

#character variables
x = 50
y = 50
width = 40
height = 60
vel = 5

isJump = False
jumpCount = 10

left = False
right = False
walkCount = 0

def redrawGameWindow():
	global walkCount
	#draw background
	win.blit(bg,(0,0))
	#if we are walking. displaying 9 sprites, 3 per frame = 27
	#afte
	print(walkCount)
	if walkCount + 1 >=27:
		walkCount = 0

	if left:
		win.blit(walkLeft[walkCount//3],(x,y)) #integer division to get sprite picture index
		walkCount += 1

	elif right:
		win.blit(walkRight[walkCount//3],(x,y)) #integer division to get sprite picture index
		walkCount += 1

	else:
		win.blit(char,(x,y))

	pygame.display.update()

#main game loop
run = True
while run:
	#1st set time for the game
	#pygame.time.delay(100) #this will be a clock for the game
	clock.tick(27)

	keys = {'left':False,'right':False, 'up':False, 'down':False}

	for event in pygame.event.get(): #check for all events that are happening
		if event.type == pygame.QUIT:
			run = False
		if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
			run = False

	vx = 0
	vy = 0
	keystate = pygame.key.get_pressed()
	#straight moves with screen constraints
	#cant move up
	if keystate[pygame.K_UP] and y > vel:
		vy = -vel
	#cant move down
	elif keystate[pygame.K_DOWN] and y < 500 - height - vel:
		vy = vel

	#while jumping cant move left or right
	if not isJump:
		#cant move off the left screen border
		if keystate[pygame.K_LEFT] and x > vel:
			vx = -vel
			left = True
			right = False
		#cant move off the right screen border
		elif keystate[pygame.K_RIGHT] and x < 500 - width - vel:
			vx = vel
			left = False
			right = True
		#if right or left not pressed, reset movement
		else:
			left = False
			right = False
			walkCount = 0
		#-----------------jump---------------
		if keystate[pygame.K_SPACE]:
			isJump = True
	else:
		if jumpCount >= -10: # we jump for 10 pixels
			neg = 1
			if jumpCount < 0: #when we get to the top of jump
				neg = -1
			y -= (jumpCount ** 2) * 0.5 * neg
			jumpCount -= 1
			#if jumping than we are not walking left or right
			left = False
			right = False
			walkCount = 0
		else:
			isJump = False
			jumpCount = 10

	#diagonals must be slower for sq(2)= 1.414 pitagora
	if vx != 0 and vy != 0:
		vx /= 1.414
		vy /= 1.414

	x += vx
	y += vy

	redrawGameWindow()

<file_sep>"""
Doodle Jump

Attributes:
    g (TYPE): Description
"""

import pygame as pg
import random
from settings import *
from sprites import *
import os
from os import path

class Game:

	"""Summary

	Attributes:
	    all_sprites (TYPE): Description
	    clock (TYPE): Description
	    playing (bool): Description
	    running (bool): Description
	    screen (TYPE): Description
	"""

	def __init__(self):
		"""initialize game window, etc
		- load data: load graphics, sound, highscore file
		"""
		pg.init()
		pg.mixer.init()
		self.screen = pg.display.set_mode((WIDTH, HEIGHT))
		pg.display.set_caption(TITLE)
		self.clock = pg.time.Clock()
		self.running = True
		self.playing = True
		#closeste match to our font name
		self.font_name = pg.font.match_font(FONT_NAME)
		self.highscore = 0
		self.load_data()

	def read_highscore_file(self, filename):
		#if file exists, read from it
		if os.path.exists(filename):
			with open(filename, 'r') as f:
				try:
					data = int(f.read())
					return data
				except:
					return 0
		# if file doesnt exists, create new
		else:
			with open(filename, 'w') as f:
				try:
					f.write("0")
					return 0
				except:
					return 0

	def load_data(self):
		""" method for loading date before starting the game
		- get folder directories, build paths for files
		- load graphics
		- load sounds
		- load files: highscore
		"""
		self.dir = path.dirname(__file__) #get application folder path

		# load spritesheet image
		self.img_dir = path.join(self.dir, 'img')
		spritesheet_file = path.join(self.img_dir, SPRITESHEET_FILE)
		self.spritesheet = Spritesheet(spritesheet_file)

		# load high score file
		highscore_file = path.join(self.dir, HIGHSCORE_FILE)
		self.highscore = self.read_highscore_file(highscore_file)

		# load sounds: .ogg files are best
		self.snd_dir = path.join(self.dir, 'snd')
		# load jump sound
		self.jump_snd_file = path.join(self.snd_dir, 'Jump33.wav')
		self.jump_sound = pg.mixer.Sound(self.jump_snd_file)
		self.jump_sound.set_volume(0.2)

	def new(self):
		"""Start a New Game
		"""
		self.score = 0
		#create sprites groups
		self.all_sprites = pg.sprite.Group()

		#create platform group
		self.platforms = pg.sprite.Group()

		#add player to sprites group
		"""create a new instance of Player and send it reference to game object
		so we can access platforms also in player class"""
		self.player = Player(self) #send reference
		self.all_sprites.add(self.player)

		#add platform list to platform group and to sprites group
		for plat in PLATFORM_LIST:
			#p = Platform(plat[0],plat[1],plat[2],plat[3]) same as bottom
			p = Platform(self, *plat) #explode plat list to components
			self.all_sprites.add(p)
			self.platforms.add(p)
		#load music before start of game
		pg.mixer.music.load(path.join(self.snd_dir, 'Happy Tune.ogg'))
	
	def run(self):
		"""Game Loop
		"""
		# start music: infinite loop
		pg.mixer.music.play(loops = -1)
		self.playing = True
		while self.playing:
			self.clock.tick(FPS) # keep looping at the right speed
			self.events()
			self.update()
			self.draw()
		# stop music with fadeout
		pg.mixer.music.fadeout(1000) # 1sec fade

	def update(self):
		"""Game Loop - Update
		- update all sprites
		- checking if player hits platform - only if falling
		-
		"""
		#debug number of platforms, check if deleted properly
		#print(len(self.platforms))
		# update all sprites
		self.all_sprites.update()

		# PLAYER-PLATFORM COLLISION DETECTION - this stops us from falling
		# checking if player hits platform - only if falling
		if self.player.vel.y > 0:
			# do a collision check with platform
			hits = pg.sprite.spritecollide(self.player, self.platforms, False)
			if hits: # hits is a list of multiple collisions
				# find which platform is lowes
				lowest = hits[0]
				for hit in hits:
					if hit.rect.bottom > lowest.rect.bottom:
						lowest = hit
				if self.player.pos.x < lowest.rect.right + 10 and \
					self.player.pos.x > lowest.rect.left - 10:
					#dont snap if the ears touch platform. only feet
					if self.player.pos.y < lowest.rect.bottom:
						self.player.pos.y = lowest.rect.top
						self.player.vel.y = 0
						# when we land on paltform, reset jumping ability
						self.player.jumping = False

		# SCROLING WINDOW
		# if player reaches top 1/4 of screen
		if self.player.rect.top <= HEIGHT/4:
			#litle math for nicer screnn scrolling. take player speed or number 2
			# even if player is not moving, the screen moves until in range
			self.player.pos.y += max(abs(self.player.vel.y),2)
			for plat in self.platforms:
				plat.rect.y += max(abs(self.player.vel.y),2)
				#remove platforms on the bottom
				if plat.rect.top >= HEIGHT:
					plat.kill() #remove bottom ones
					self.score += 1

		# spawn new platforms to keep some avarage number
		while len(self.platforms) < 6:
			#randomize creation of platforms
			width = random.randrange(50, 100)
			p = Platform(self,
				random.randrange(0, WIDTH-width),
				random.randrange(-75, -30))
			self.platforms.add(p)
			self.all_sprites.add(p)

		# GAME OVER
		# Die! and game over condition
		if self.player.rect.bottom > HEIGHT:
			#do a bling when dying- looks like scroling camera
			for sprite in self.all_sprites:
				sprite.rect.y -= max(self.player.vel.y, 10)
				if sprite.rect.bottom < 0:
					sprite.kill()

		if len(self.platforms) == 0:
			self.playing = False

	def events(self):
		"""Game Loop - events
		- close window + escape key event stops game
		"""
		for event in pg.event.get():
			# check for closing window
			if (event.type == pg.QUIT) or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):
				if self.playing:
					self.playing = False
				self.running = False
				self.player.vel.y = 0

			# jumping section. jump higher if we hold space
			if event.type == pg.KEYDOWN:
				if event.key == pg.K_SPACE:
					self.player.jump()
			if event.type == pg.KEYUP:
				if event.key == pg.K_SPACE:
					self.player.jump_cut()

	def draw(self):
		"""Game Loop - draw
		- fill with background colour
		- draw all sprites
		- draw text score
		- flip everything to display
		"""
		self.screen.fill(BG_COLOR)
		self.all_sprites.draw(self.screen)
		# put player always in front of other stuff
		self.screen.blit(self.player.image, self.player.rect)
		self.draw_text(str(self.score), 22, WHITE, WIDTH_MID, 15)
		pg.display.flip()

	def show_start_screen(self):
		"""game splash/start screen
		"""
		# start playing music
		pg.mixer.music.load(path.join(self.snd_dir, 'Yippee.ogg'))
		pg.mixer.music.set_volume(0.2) # 0 < x < 1
		pg.mixer.music.play(loops = -1)

		self.screen.fill(BG_COLOR)
		self.draw_text(TITLE, 48, WHITE, WIDTH_MID, HEIGHT//4)
		self.draw_text("Arrows to move, Space to jump", 22, WHITE, WIDTH_MID, HEIGHT_MID)
		self.draw_text("Press a key to play", 22, WHITE, WIDTH_MID, HEIGHT*3/4)
		self.draw_text("High score : " + str(self.highscore), 22, WHITE, WIDTH_MID, 15)
		pg.display.flip()
		self.wait_for_key()

		# stop music
		pg.mixer.music.fadeout(1000) # s0.5sec fade

	def show_go_screen(self):
		"""game over/continue screen
		If player presses (X), than ignore game over screen
		Game over screen is called only if a player dies
		- handle highscore file
		"""
		if not self.running:
			return
		# start playing music
		pg.mixer.music.load(path.join(self.snd_dir, 'Yippee.ogg'))
		pg.mixer.music.set_volume(0.2) # 0 < x < 1
		pg.mixer.music.play(loops = -1)

		self.screen.fill(BG_COLOR)
		self.draw_text("GAME OVER", 48, WHITE, WIDTH_MID, HEIGHT//4)
		self.draw_text("Score : "+str(self.score), 22, WHITE, WIDTH_MID, HEIGHT_MID)
		self.draw_text("press a key to play again", 22, WHITE, WIDTH_MID, HEIGHT*3/4)
		# save highscore
		if self.score > self.highscore:
			self.highscore = self.score
			self.draw_text("NEW HIGH SCORE ! CONGRATS", 22, WHITE, WIDTH_MID, HEIGHT_MID + 40)
			with open(path.join(self.dir, HIGHSCORE_FILE), "w") as f:
				f.write(str(self.highscore))
		else:
			self.draw_text("High score : " + str(self.highscore), 22, WHITE, WIDTH_MID, 15)
		pg.display.flip()
		self.wait_for_key()
		# stop music
		pg.mixer.music.fadeout(1000) # s0.5sec fade

	def wait_for_key(self):
		waiting = True
		while waiting:
			self.clock.tick(FPS)
			for event in pg.event.get():
				#check for closing window
				if (event.type == pg.QUIT) or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):
					""" this is original, but doesnt close screen at game over
					if self.playing:
						waiting = False
						self.running = False
						self.playing = False
					"""
					waiting = False
					self.running = False
					self.playing = False
				if event.type == pg.KEYUP:
					waiting = False

	def draw_text(self, text, size, color, x, y):
		font = pg.font.Font(self.font_name, size)
		text_surface = font.render(text, True, color)
		text_rect = text_surface.get_rect()
		text_rect.midtop = (x, y)
		self.screen.blit(text_surface, text_rect)

#----------------MAIN GAME------------------
g = Game() # instance of game object

g.show_start_screen()
while g.running:
	g.new()
	g.run()
	g.show_go_screen()
pg.quit()

<file_sep>print("loading jutri: 10% ##________")<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Dec 25 11:08:39 2020

@author: crtom
"""


import pygame
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2

pygame.init()
HEIGHT, WIDTH = (400,400)

#### Create a canvas on which to display everything ####
screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)

#### Create a surface with the same size as the window ####
background = pygame.Surface((WIDTH, HEIGHT))

#background = pygame.image.load(background_image_filename).convert()
#sprite = pygame.image.load(sprite_image_filename).convert_alpha()

clock = pygame.time.Clock()
position = Vector2(100.0, 100.0)
speed = 250.
heading = Vector2()

sprite = pygame.Surface((50, 50))
sprite.fill((255,255,255))
rect = sprite.get_rect()
rect.center = (WIDTH / 2, HEIGHT / 2)

# at start destination is the same as object position
destination = (WIDTH / 2, HEIGHT / 2)

while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
        
        if event.type == MOUSEBUTTONDOWN:
            destination_x = event.pos[0] - sprite.get_width()/2.0 
            destination_y = event.pos[1] - sprite.get_height()/2.0 
            destination = (destination_x, destination_y)
            print(destination)
    
            heading = Vector2.from_points(position, destination) 
            heading.normalize()
            
    #### Blit the surface onto the canvas ####
    screen.blit(background,(0,0))

    #### Blit the surface onto the canvas ####
    screen.blit(sprite,(int(position.x), int(position.y)))   
    
    time_passed = clock.tick()
    time_passed_seconds = time_passed / 1000.0
    
    distance_moved = time_passed_seconds * speed
    position += heading * distance_moved

        
    pygame.display.update()<file_sep>import pygame as pg
vec = pg.math.Vector2

# define some colors (R, G, B)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARKGREY = (40, 40, 40)
LIGHTGREY = (100, 100, 100)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
BROWN = (106, 55, 5)
CYAN = (0, 255, 255)

# game settings
WIDTH = 1024   # 16 * 64 or 32 * 32 or 64 * 16
HEIGHT = 768  # 16 * 48 or 32 * 24 or 64 * 12
FPS = 60
TITLE = "Tilemap Demo"
BGCOLOR = BROWN

TILESIZE = 64
GRIDWIDTH = WIDTH / TILESIZE
GRIDHEIGHT = HEIGHT / TILESIZE

WALL_IMG = 'tileGreen_39.png'

# Player settings
PLAYER_HEALTH = 100
PLAYER_SPEED = 280
PLAYER_ROT_SPEED = 200
PLAYER_IMG = 'manBlue_gun.png'
PLAYER_HIT_RECT = pg.Rect(0, 0, 35, 35)
BARREL_OFFSET = vec(30, 10)

# Gun settings
BULLET_IMG = 'bullet.png'
BULLET_SPEED = 500
BULLET_LIFETIME = 1000
BULLET_RATE = 150
KICKBACK = 200
GUN_SPREAD = 5
BULLET_DAMAGE = 10

# Mob settings
MOB_IMG = 'zombie1_hold.png'
MOB_SPEEDS = [50, 75, 100, 125, 150]
MOB_HIT_RECT = pg.Rect(0, 0, 30, 30)
MOB_HEALTH = 100
MOB_DAMAGE = 10
MOB_KNOCKBACK = 20
AVOID_RADIUS = 50

# Effects
MUZZLE_FLASHES = ['whitePuff15.png',
                  'whitePuff16.png',
                  'whitePuff17.png',
                  'whitePuff18.png']
FLASH_DURATION = 40

# Layers
WALL_LAYER    = 1
PLAYER_LAYER  = 2
BULLET_LAYER  = 3
MOB_LAYER     = 4
EFFECTS_LAYER = 5
ITEMS_LAYER = 1

# Items
ITEM_IMAGES = {'health': 'health_pack.png'}
HEALTH_PACK_AMOUNT = 20<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 11:44:03 2020

@author: crtom
"""


from vector import Vector

a = Vector(5, 10)
b = Vector(-5, 10)

c = a + b #Vector class using __add__ operator overload

print(a.x, a.y)
print(b.x, b.y)
print(c.x, c.y)

# if we want to do a*b. vector multiplication
# we need to create constructor overload
<file_sep>if self.state == "exploring":
    self.random_heading()
    if self.can_see(player):
        self.state = "seeking"

elif self.state == "seeking":
    self.head_towards("player")
    if self.in_range_of(player):
        self.fire_at(player)
    if not self.can_see(player):
        self.state = "exploring"
<file_sep># -*- coding: utf-8 -*-
"""
http://inventwithpython.com/pygame/

Created on Tue Dec 15 18:09:41 2020

@author: crtom

- BASIC ARHITECTURE, get mouse coordinates

#------------------------------------------------------------------------------
    #--------------------------------------------------------------------------
        #----------------------------------------------------------------------
            #------------------------------------------------------------------
                #--------------------------------------------------------------
"""

import pygame
import sys

from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT

#--------------------------------------------------------------------------
#-------------------------constants----------------------------------------
#--------------------------------------------------------------------------

FPS = 30
WIN_W = 600
WIN_H = 600 
""" grid calculations
 GRID = 600*600
 GRID 6x6 = 36 pieces
 100x100 per square
 one piece is 80x80 + margin = 100x100
"""
MARGIN_L = 10
BOX_L = 80

#REVEALSPEED = 8

#GAPSIZE = 10
BOARD_W = 6
BOARD_H = 6

# check
#assert(BOARDWIDTH*BOARDHEIGHT) % 2 == 0, 'Board needs to have an even number of boxes for pairs of matches'

#XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE + GAPSIZE))) / 2)
#YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE))) / 2)

# COLORS  ( R ,  G ,  B )
WHITE   = (255, 255, 255)
BLACK   = (  0,   0,   0)
RED     = (255,   0,   0)
LIME    = (  0, 255,   0)
BLUE    = (  0,   0, 255)
NAVYBLUE= ( 60,  60, 100)
YELLOW  = (255, 255,   0)
ORANGE  = (255, 128,   0)
CYAN    = (  0, 255, 255)
MAGENTA = (255,   0, 255)
SILVER  = (192, 192, 192)
GRAY	= (128, 128, 128)
MAROON  = (128,   0,   0)
OLIVE   = (128, 128,   0)
GREEN   = (  0, 128,   0)
PURPLE  = (128,   0, 128)
TEAL    = (  0, 128, 128)
NAVY    = (  0,   0, 128)

BGCOLOR = NAVYBLUE
LIGHTBGCOLOR = GRAY
BOXCOLOR = WHITE
HIGHLIGHTCOLOR = BLUE

LINE = 'line'
DONUT = 'donut'
SQUARE = 'square'
DIAMOND = 'diamond' 
LINES = 'lines'
OVAL = 'oval'


#ALLCOLORS = (RED, GREEN, BLUE, YELLOW, ORANGE, PURPLE, CYAN)
#ALLSHAPES = (LINE, DONUT, SQUARE, DIAMOND, LINES, OVAL)

#assert len(ALLCOLORS) * len(ALLSHAPES) * 2 <= BOARDWIDTH * BOARDHEIGHT,'Board is too big for the number of shapes/colors defined.'

# create coordiantion
grid_vertices = 0

grid_vertices = [[0 for i in range(6)] for j in range(6)]

# create a list of touple positions
grid_touple_lst = []
for y in range(0, 6):
    for x in range(0, 6):
        grid_touple_lst.append((x,y))
    

print(grid_touple_lst)
# print('first item:', grid_touple_lst[0])
# print('last item:', grid_touple_lst[35])

square_touple_lst = []
for x in range(10, 610, 100):
    for y in range(10, 610, 100):
        square_touple_lst.append((x,y))
# print(square_touple_lst)

# 'back'
# 'front'    
state_lst = ['back' for i in range(36)]
print(state_lst)

#------------------------------------------------------------------------------
#----------------------------main loop-----------------------------------------
#------------------------------------------------------------------------------
def main():
    
    # global variables
    global FPSCLOCK, DISPLAYSURF
    
    # for positions
    position_pixel = (None, None)
    position_grid = (None, None)
    position_box = None
    
    # for user events
    mouseMoved = False
    mouseClicked = False
    
    #--------------------------------------------------------------------------
    # init pygame
    pygame.init()
    
    FPSCLOCK = pygame.time.Clock() # initialize clock
    
    DISPLAYSURF = pygame.display.set_mode((WIN_W, WIN_H)) # initialize surface
    DISPLAYSURF.fill(BGCOLOR)
    
    pygame.display.set_caption('Memory Game')

    # Draws boxes being covered/revealed. "boxes" is a list
    # of two-item lists, which have the x & y spot of the box.
    # coordinartes of grid
    
    #left, top = leftTopCoordsOfBox(box[0], box[1])
    #pygame.draw.rect(DISPLAYSURF, BGCOLOR, (left, top, BOXSIZE, BOXSIZE))
    # DRAW GRID
    for touple in square_touple_lst:
        x, y = touple
        pygame.draw.rect(DISPLAYSURF, WHITE, (x, y, 80, 80))

    
    #shape, color = getShapeAndColor(board, box[0], box[1])
    #drawIcon(shape, color, box[0], box[1])

    
    #--------------------------------------------------------------------------
    #-------------------------GAME loop----------------------------------------
    #--------------------------------------------------------------------------
    while True:
        
        #----------------------event handling---------------------------------
        for event in pygame.event.get():
            
            # event objects have type attribute
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

            elif event.type == MOUSEMOTION:
                position_pixel = event.pos
                mouseMoved = True
                #print('mouse moved')

            elif event.type == MOUSEBUTTONUP:
                # mouse click position is in pixels
                position_pixel = event.pos
                # set click is true for functions
                mouseCicked = True
                #print('mouse clicked')
        #---------------------------------------------------------------------
        # if mouse moved than highlight box
        if mouseMoved:
            # window pixels to game grid 
            position_grid = pixel_pos_to_game_grid(position_pixel)
            # game grid to box number
            position_box = game_grid_to_touple_pos(position_grid)
            
            print('position_pixel = ', position_pixel)
            print('position_grid = ', position_grid)
            print('position_box = ', position_box)
              
            # reset event flag
            mouseMoved = False
        #---------------------------------------------------------------------
        if mouseClicked:
            mouseClicked = False
        #------------------------timing----------------------------------------
        # draws surface object stored in DISPLAYSURF
        pygame.display.update()
        FPSCLOCK.tick(FPS)
    
#------------------------------------------------------------------------------
#-------------------------function definitions---------------------------------
#------------------------------------------------------------------------------
def pixel_pos_to_game_grid(touple_pixel):
    """
    Parameters
    ----------
    touple_pixel : touple
        position in pixels coordinates.

    Returns
    -------
    touple_grid : touple
        position in game grid coordinates.
    """

    x_grid = touple_pixel[0] // 100 # integere division
    y_grid = touple_pixel[1] // 100
    touple_grid = (x_grid, y_grid)

    return touple_grid

def game_grid_to_touple_pos(touple_grid):
    """
    Parameters
    ----------
    mytouple : touple
        position in game grid coordinates.

    Returns
    -------
    box_n : number
        list index from grid_touple_lst
    """

    box_n = None
    for i, touple in enumerate(grid_touple_lst):
        if touple_grid == touple:
            box_n = i
    
    return box_n

    

def change_box_state(grid_nx, grid_ny):
    global state_lst
    
    
    
    # for state in state_lst:
    #     # if back, turn to front
    #     if state == 'front':
    #         pygame.draw.rect(DISPLAYSURF, WHITE, (x, y, 80, 80))
    #     # if front, turn to back
    #     else:
    #         pygame.draw.rect(DISPLAYSURF, RED, (x, y, 80, 80))



def leftTopCoordsOfBox(boxx, boxy):
    # Convert board coordinates to pixel coordinates
    left = boxx * (BOXSIZE + GAPSIZE) + XMARGIN
    top = boxy * (BOXSIZE + GAPSIZE) + YMARGIN
    return (left, top)    
#------------------------------------------------------------------------------
#-------------------------Start application------------------------------------
#------------------------------------------------------------------------------        
if __name__ == '__main__':
    main()<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Dec 21 22:32:03 2020

@author: crtom
"""


import random

number_list = [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
print("Original list:", number_list)

random.shuffle(number_list)
print("List after first shuffle:", number_list)

random.shuffle(number_list)
print("List after second shuffle:", number_list)<file_sep>require('game')

function love.load()
  love.window.setPosition(500, 50, 1)
  interval = 20
  add_apple()
end

function love.draw()
  game_draw()
  if state == GameStates.game_over then -- draw Game Over when the state is game_over
    love.graphics.print("Game Over!", 330, 350, 0, 4, 4)
    love.graphics.print("Press Space to restart", 270, 450, 0, 3, 3)
  end
end

function love.update()
  if state == GameStates.running then
    interval = interval - 1
    if interval < 0 then
      game_update()
      if tail_length <= 5 then
        interval = 20
      elseif tail_length > 5 and tail_length <= 10 then -- the game will run faster after every 6 collected apple
        interval = 15
      elseif tail_length > 10 and tail_length <= 15 then
        interval = 10
      else
        interval = 5
      end
    end
  end
end

function love.keypressed(key)
  if key == 'escape' then
    love.event.quit()
  elseif key == 'left' and state == GameStates.running then 
    left, right, up, down = true, false, false, false
  elseif key == 'right' and state == GameStates.running then
    left, right, up, down = false, true, false, false
  elseif key == 'up' and state == GameStates.running then
    left, right, up, down = false, false, true, false
  elseif key == 'down' and state == GameStates.running then
    left, right, up, down = false, false, false, true
  elseif key == 'space' and state == GameStates.game_over then
    game_restart()
  elseif key == 'p' then
    if state == GameStates.running then
      state = GameStates.pause
    else
      state = GameStates.running
    end
  end
end
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 17:58:20 2020

@author: crtom
"""


<file_sep>from OpenGL.GL import *
from OpenGL.GLU import *

import pygame
from pygame.locals import *

SCREEN_SIZE = (800, 600)

def resize(width, height):

    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45.0, float(width)/height, .1, 1000.)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()


def init():

    glEnable(GL_TEXTURE_2D)
    glEnable(GL_BLEND)
    glClearColor(1.0, 1.0, 1.0, 0.0)    


def upload_texture(filename, use_alpha=False):
    
    # Read an image file and upload a texture    
    if use_alpha:
        format, gl_format, bits_per_pixel = 'RGBA', GL_RGBA, 4        
    else:
        format, gl_format, bits_per_pixel = 'RGB', GL_RGB, 3
    
    img_surface = pygame.image.load(filename)
    
    #img_surface = premul_surface(img_surface)
    
    data = pygame.image.tostring(img_surface, format, True)    
    
    texture_id = glGenTextures(1)
    
    glBindTexture(GL_TEXTURE_2D, texture_id)
    
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR )
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR )
    
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
    
    width, height =  img_surface.get_rect().size
    
    glTexImage2D(   GL_TEXTURE_2D,
                    0,
                    bits_per_pixel,
                    width,
                    height,
                    0,
                    gl_format,
                    GL_UNSIGNED_BYTE,
                    data )
    
    # Return the texture id, so we can use glBindTexture
    return texture_id
    
    
def draw_quad(x, y, z, w, h):
    
    # Send four vertices to draw a quad
    glBegin(GL_QUADS)
    
    glTexCoord2f(0, 0)
    glVertex3f(x-w/2, y-h/2, z)

    glTexCoord2f(1, 0)
    glVertex3f(x+w/2, y-h/2, z)

    glTexCoord2f(1, 1)
    glVertex3f(x+w/2, y+h/2, z)

    glTexCoord2f(0, 1)
    glVertex3f(x-w/2, y+h/2, z)
        
    glEnd()
    

def run():
    
    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|OPENGL|DOUBLEBUF)
      
    resize(*SCREEN_SIZE)
    init()
       
    # Upload the background and fugu texture
    background_tex = upload_texture('background.png')
    fugu_tex = upload_texture('fugu.png', True)    

    while True:
        
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                quit()
            if event.type == KEYDOWN:
                if event.key == K_1:
                    # Simple alpha blending
                    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
                    glBlendEquation(GL_FUNC_ADD)
                elif event.key == K_2:
                    # Additive alpha blending
                    glBlendFunc(GL_SRC_ALPHA, GL_ONE)                    
                    glBlendEquation(GL_FUNC_ADD)
                elif event.key == K_3:
                    # Subtractive blending
                    glBlendFunc(GL_SRC_ALPHA, GL_ONE)
                    glBlendEquation(GL_FUNC_REVERSE_SUBTRACT)

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
                                
        # Draw the background
        glBindTexture(GL_TEXTURE_2D, background_tex)
        
        glDisable(GL_BLEND)
        draw_quad(0, 0, -SCREEN_SIZE[1], 600, 600)
        glEnable(GL_BLEND)
        
        # Draw a texture at the mouse position
        glBindTexture(GL_TEXTURE_2D, fugu_tex)
        x, y = pygame.mouse.get_pos()
        x -= SCREEN_SIZE[0]/2
        y -= SCREEN_SIZE[1]/2
        draw_quad(x, -y, -SCREEN_SIZE[1], 256, 256)
        
        pygame.display.flip()
        
    # Free the textures we used
    glDeleteTextures(background_tex)
    glDeleteTextures(fugu_tex)
        
if __name__ == "__main__":
    run()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 23:08:54 2020

@author: crtom
"""

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
YELLOW = (255, 255, 0)
DARKGREY = (40, 40, 40)
LIGHTGREY = (140, 140, 140)

# game settings
WIDTH = 1024 # divisible by 16*64 32*32
HEIGHT = 768 # 16*48 32*24 66*12

FPS = 60

TITLE = 'Tilemap demo'
BGCOLOR = DARKGREY

TILESIZE = 32

GRIDWIDTH = WIDTH / TILESIZE
GRIDHEIGHT = HEIGHT / TILESIZE

# player settings
PLAYER_SPEED = 600 # 100 px/seconds
<file_sep>import pygame
from board import Grid
from player import Player, Stats
from enum import Enum, auto

import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (400,100)

surface = pygame.display.set_mode((1200, 900))
pygame.display.set_caption('Minesweeper')


class States(Enum):
    running = auto()
    game_over = auto()
    win = auto()

state = States.running

player = Player()
grid = Grid(player)

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN and state == States.running:
            if pygame.mouse.get_pressed()[0]: # check for the left mouse button
                pos = pygame.mouse.get_pos()
                grid.click(pos[0], pos[1])
            elif pygame.mouse.get_pressed()[2]:
                pos = pygame.mouse.get_pos()
                grid.mark_mine(pos[0]//30, pos[1]//30)
            if grid.check_if_win():
                state = States.win
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and (state == States.game_over or state == States.win):
                grid.reload()
                state = States.running
            if event.key == pygame.K_b:
                grid.show_mines()

    surface.fill((0,0,0))

    if player.get_health() == 0:
        state = States.game_over

    if state == States.game_over:
        Stats.draw(surface, 'Game over!', (970, 350))
        Stats.draw(surface, 'Press Space to restart', (920, 400))
    elif state == States.win:
        Stats.draw(surface, 'You win!', (1000, 350))
        Stats.draw(surface, 'Press Space to restart', (920, 400))

    grid.draw(surface)
    Stats.draw(surface, 'Lives remaining', (950, 100))
    Stats.draw(surface, str(player.get_health()), (1020, 200))
    Stats.draw(surface, 'RMB to mark mine', (950, 550))
    Stats.draw(surface, 'press b to show mines', (920, 650))

    pygame.display.flip()
<file_sep>import pygame

my_name = "<NAME>"
pygame.init()
my_font = pygame.font.SysFont("arial", 64) 
name_surface = my_font.render(my_name, True, (0, 0, 0), (255, 255, 255)) 
pygame.image.save(name_surface, "name.png")
<file_sep>import math
import random
import pygame
import tkinter as tk
from tkinter import messagebox

class cube(object):
	rows = 0
	w = 0
	def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)):
		pass

	def move(self,dirnx,dirny):
		pass

	def draw(self,surface,eyes=False):
		pass

class snake(object):
	def __init__(self,color,pos):
		pass

	def move(self):
		pass

	def reset(self,pos):
		pass

	def addCube(self):
		pass

	def draw(self,surface):
		pass

def drawGrid(w,rows,surface):
	pass

def redrawWindow(surface):
	pass

def randomSnack(rows,items):
	pass

def message_box(subject,content):
	pass

def main():
	pass

rows = 0
w = 0
h = 0

cube.rows = rows
cube.w = w

main()<file_sep>Python Game Programming Tutorial: Pong for Beginners

[Youtube playlist](https://www.youtube.com/playlist?list=PLlEgNdBJEO-kXk2PyBxhSmo84hsO3HAz2)

- [Pong Part 1 Getting Started](1_pong.py)
- [Pong Part 2 Game Objects](2_pong.py)
- [Pong Part 3 Moving the Paddles](3_pong.py)
- [Pong Part 4 Moving the Ball](4_pong.py)
- [Pong Part 5 Colliding with the Paddles](5_pong.py)
- [Pong Part 6 Scoring](6_pong.py)
- [Pong Part 7 Sounds](7_pong.py)
<file_sep>import math
import random
import pygame
import tkinter as tk
from tkinter import messagebox

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)

class cube(object):
	rows = 0
	w = 0
	def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)):
		pass

	def move(self,dirnx,dirny):
		pass

	def draw(self,surface,eyes=False):
		pass

class snake(object):
	def __init__(self,color,pos):
		pass

	def move(self):
		pass

	def reset(self,pos):
		pass

	def addCube(self):
		pass

	def draw(self,surface):
		pass

def drawGrid(w,rows,surface):
	"""
	This function draws a square grid on main display
	"""
	#distance between grid lines
	sizeBtwn = w // rows
	x = 0
	y = 0

	#create grid by drawing lines
	for l in range(rows):
		x = x + sizeBtwn
		y = y + sizeBtwn

		#vertical lines
		pygame.draw.line(surface, WHITE, (x,0), (x,w))
		#horizontal lines
		pygame.draw.line(surface, WHITE, (0,y), (w,y))

def redrawWindow(surface):
	global rows, width
	#background
	surface.fill(BLACK)
	#draw grid
	drawGrid(width, rows, surface)
	#update display
	pygame.display.update()


def randomSnack(rows,items):
	pass

def message_box(subject,content):
	pass

def main():
	global width, rows
	#create game display
	width = 500
	rows = 20
	win = pygame.display.set_mode((width, width)) #square display
	#snake start position
	s = snake(color=RED, pos=(10,10))

	clock = pygame.time.Clock()

	flag = True
	while flag:
		#pygame.time.delay(50)
		clock.tick(10)	#game max speed 10 FPS
		redrawWindow(win)


#rows = 0
#w = 0
#h = 0

#cube.rows = rows
#cube.w = w
print("here")
main()<file_sep>"""
Basic Movement and Key Presses
video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5

1. create a rectangle
2. move it by key pressed
"""

import pygame
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2

from math import *

# define colors  
BLACK = (0 , 0 , 0)  
GREEN = (0 , 255 , 0)  

pygame.init()

WIDTH, HEIGHT = 640, 480
#### Create a canvas on which to display everything ####
screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
#set windows title
pygame.display.set_caption("rotating sprite")

#### Create a surface with the same size as the window ####
background = pygame.Surface((WIDTH, HEIGHT))

#character variables
x = 50
y = 50
width = 40
height = 60
vel = 5

# define a surface (RECTANGLE)  
sprite_orig = pygame.Surface((50 , 50))  
# for making transparent background while rotating an image  
sprite_orig.set_colorkey(BLACK)  
# fill the rectangle / surface with green color  
sprite_orig.fill(GREEN)  
# creating a copy of orignal image for smooth rotation  
sprite = sprite_orig.copy()  
sprite.set_colorkey(BLACK)  
# define rect for placing the rectangle at the desired position  
rect = sprite.get_rect()  
rect.center = (WIDTH // 2 , HEIGHT // 2)  
# keep rotating the rectangle until running is set to False 
screen.blit(sprite , rect)

# sprite = pygame.Surface((50, 50))
# sprite.fill((255,255,255))
# rect = sprite.get_rect()
# rect.center = (WIDTH / 2, HEIGHT / 2)
 
# sprite_pos = Vector2(100.0, 100.0)
sprite_speed = 300.
sprite_rotation = 0.
sprite_rotation_speed = 180. # deg/second

clock = pygame.time.Clock()

key_direction = Vector2(0, 0)

#main game loop
clock = pygame.time.Clock()
run = True
while run:
    # pygame.time.delay(100) #this will be a clock for the game
    for event in pygame.event.get(): #check for all events that are happening
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            run = False
    	
    # key_direction.x, key_direction.y = (0, 0)
    rotation_direction = 0.
    
    keystate = pygame.key.get_pressed()
    if keystate[pygame.K_LEFT]:
        rotation_direction = +1
    
    if keystate[pygame.K_RIGHT]:
         rotation_direction = -1
    
    time_passed = clock.tick(30)
    time_passed_seconds = time_passed / 1000.0
    
    #-----FIRST DO ROTATION AND POSITION CALCULATIONS
    # calculate sprite rotation
    sprite_rotation += rotation_direction * sprite_rotation_speed * time_passed_seconds
    sprite_rotation %= 360 
    
    # making a copy of the old center of the rectangle  
    old_center = rect.center
    
    # now do the drawings 
    rotated_sprite = pygame.transform.rotate(sprite_orig, sprite_rotation)
    rect = rotated_sprite.get_rect()  
    
    # set the rotated rectangle to the old center  
    rect.center = old_center  
    
    # clear the screen every time before drawing new objects  
    screen.fill(BLACK) 
    # drawing the rotated rectangle to the screen  
    screen.blit(rotated_sprite , rect)  
    
    # w, h = rotated_sprite.get_size()
    # sprite_draw_pos = Vector2(sprite_pos.x - w/2, sprite_pos.y - h/2)
    # #screen.blit(rotated_sprite, sprite_draw_pos)
    # #screen.blit(rotated_sprite, (int(sprite_pos.x), int(sprite_pos.y))) 
    
    # making a copy of the old center of the rectangle  
    # old_center = rect.center 
    



    
    #### Blit the surface onto the canvas ####
    # screen.blit(background,(0,0))
    #### Blit the surface onto the canvas ####
    # screen.blit(sprite,(int(sprite_pos.x), int(sprite_pos.y))) 
    #### display canvas ####
    pygame.display.update()

    print(sprite_rotation)
    #print(heading)
# exit pygame
pygame.quit()
exit()
<file_sep>from math import tan

def calculate_viewing_distance(fov, screen_width):

    d = (screen_width/2.0) / tan(fov/2.0)
    return d
<file_sep>import pymunkoptions
pymunkoptions.options["debug"] = False
import pyglet
from pyglet.window import FPSDisplay, key
import pymunk
from pymunk.pyglet_util import DrawOptions
from pymunk.vec2d import Vec2d
import random

collision_types = {
    "ball":1,
    "brick":2,
    "bottom":3,
    "player":4
}

class Bricks:
    def __init__(self, space):
        for x in range(10):
            for y in range(10):
                body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
                body.position = x*110+90, y*30+500
                shape = pymunk.Segment(body, (0,0), (100,0), 8)
                shape.elasticity = 0.98
                shape.collision_type = collision_types["brick"]
                space.add(body, shape)

        handler = space.add_collision_handler(collision_types["brick"], collision_types["ball"])
        handler.separate = self.remove_brick

    def remove_brick(self, arbiter, space, data):
        brick_shape = arbiter.shapes[0]
        space.remove(brick_shape, brick_shape.body)





class Walls:
    def __init__(self, space):
        left = pymunk.Segment(space.static_body, (50,110), (50,800), 2)
        top = pymunk.Segment(space.static_body, (50,800), (1230,800), 2)
        right = pymunk.Segment(space.static_body, (1230,800), (1230,110), 2)

        left.elasticity = 0.98
        top.elasticity = 0.98
        right.elasticity = 0.98

        bottom = pymunk.Segment(space.static_body, (50,50), (1230,50), 2)
        bottom.sensor = True
        bottom.collision_type = collision_types["bottom"]

        handler = space.add_collision_handler(collision_types["ball"], collision_types["bottom"])
        handler.begin = self.reset_game

        space.add(left, top, right, bottom)

    def reset_game(self, arbiter, space, data):
        window.reset_game()
        return True



class Ball(pymunk.Body):
    def __init__(self, space, position):
        super().__init__(1, pymunk.inf)
        self.position = position.x, position.y+18
        shape = pymunk.Circle(self, 10)
        shape.elasticity = 0.98
        shape.collision_type = collision_types["ball"]
        self.spc = space
        self.on_paddle = True
        self.velocity_func = self.constant_velocity

        self.joint = pymunk.GrooveJoint(space.static_body, self, (100,118), (1180,118), (0,0))

        space.add(self, shape, self.joint)

    def shoot(self):
        self.on_paddle = False
        self.spc.remove(self.joint)
        direction = Vec2d(random.choice([(50,500), (-50,500)]))
        self.apply_impulse_at_local_point(direction)

    def constant_velocity(self, body, gravity, damping, dt):
        body.velocity = body.velocity.normalized()*600

    def update(self):
        if self.position.x < 50 or self.position.x > 1230 or self.position.y > 800:
            self.velocity *= -1



class Player(pymunk.Body):
    def __init__(self, space):
        super().__init__(10, pymunk.inf)
        self.position = 640, 100
        shape = pymunk.Segment(self, (-50,0), (50,0), 8)
        shape.elasticity = 0.98
        shape.collision_type = collision_types["player"]

        joint = pymunk.GrooveJoint(space.static_body, self, (100,100), (1180,100), (0,0))

        space.add(self, shape, joint)


class GameWindow(pyglet.window.Window):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.set_location(300, 50)
        self.fps = FPSDisplay(self)

        self.space = pymunk.Space()
        self.options = DrawOptions()

        self.player = Player(self.space)
        self.ball = Ball(self.space, self.player.position)
        self.walls = Walls(self.space)
        self.bricks = Bricks(self.space)

    def on_draw(self):
        self.clear()
        self.space.debug_draw(self.options)
        self.fps.draw()

    def on_key_press(self, symbol, modifiers):
        if symbol == key.RIGHT:
            self.player.velocity = 600, 0
            if self.ball.on_paddle:
                self.ball.velocity = self.player.velocity
        if symbol == key.LEFT:
            self.player.velocity = -600, 0
            if self.ball.on_paddle:
                self.ball.velocity = self.player.velocity
        if symbol == key.SPACE:
            if self.ball.on_paddle:
                self.ball.shoot()
        if symbol == key.R:
            self.reset_game()

    def on_key_release(self, symbol, modifiers):
        if symbol in (key.RIGHT, key.LEFT):
            self.player.velocity = 0, 0
            if self.ball.on_paddle:
                self.ball.velocity = 0, 0

    def reset_game(self):
        for shape in self.space.shapes:
            if shape.body != self.space.static_body and shape.body.body_type != pymunk.Body.KINEMATIC:
                self.space.remove(shape.body, shape)
        for constraint in self.space.constraints:
            self.space.remove(constraint)
        self.player = Player(self.space)
        self.ball = Ball(self.space, self.player.position)

    def update(self, dt):
        self.space.step(dt)
        self.ball.update()




if __name__ == "__main__":
    window = GameWindow(1280, 900, "Breakout game", resizable=False)
    pyglet.clock.schedule_interval(window.update, 1/60.0)
    pyglet.app.run()<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Dec 21 11:41:03 2020

@author: crtjur
"""

import pygame as py

# define constants
WIDTH = 500
HEIGHT = 500
FPS = 30

# define colors
BLACK = (0 , 0 , 0)
GREEN = (0 , 255 , 0)

# initialize pygame and create screen
py.init()
screen = py.display.set_mode((WIDTH , HEIGHT))
# for setting FPS
clock = py.time.Clock()

rot = 0
rot_speed = 2

# define a surface (RECTANGLE)
image_orig = py.Surface((100 , 100))
# for making transparent background while rotating an image
image_orig.set_colorkey(BLACK)
# fill the rectangle / surface with green color
image_orig.fill(GREEN)
# creating a copy of orignal image for smooth rotation
image = image_orig.copy()
image.set_colorkey(BLACK)
# define rect for placing the rectangle at the desired position
rect = image.get_rect()
rect.center = (WIDTH // 2 , HEIGHT // 2)
# keep rotating the rectangle until running is set to False
running = True
while running:
    # set FPS
    clock.tick(FPS)
    # clear the screen every time before drawing new objects
    screen.fill(BLACK)
    # check for the exit
    for event in py.event.get():
        if event.type == py.QUIT:
            running = False

    # making a copy of the old center of the rectangle
    old_center = rect.center
    # defining angle of the rotation
    rot = (rot + rot_speed) % 360
    # rotating the orignal image
    new_image = py.transform.rotate(image_orig , rot)
    rect = new_image.get_rect()
    # set the rotated rectangle to the old center
    rect.center = old_center
    # drawing the rotated rectangle to the screen
    screen.blit(new_image , rect)
    # flipping the display after drawing everything
    py.display.flip()

py.quit()<file_sep>import cx_Freeze

executables = [cx_Freeze.Executable("ants_game.py")]

cx_Freeze.setup(
    name="Ant Game",
    options={"build_exe": {"packages":["pygame"],
                           "include_files":["ant.png","leaf.png","spider.png",'gameobjects']}},
    executables = executables

    )
<file_sep>#pseudocode
tank_heading = Vector3(tank_matrix.forward)
tank_matrix.translation += tank_heading * tank_speed * time_passed
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 19:16:26 2020

@author: crtom

 GRID = 600*600
 GRID 6x6 = 36 pieces
 100x100 per square
 one piece is 80x80 + margin = 100x100
"""

# create a list of touple positions
grid_touple_list = []
grid_pixel_pos_list = []
card_position_list = []

for y in range(0, 6):
    for x in range(0, 6):
        grid_touple_list.append((x,y))
        grid_pixel_pos_list.append((x*100, y*100))
        card_position_list.append(((x*100) + 10, (y*100) + 10))

# for x in range(0, 600, 100):
#     for y in range(0, 600, 100):
#         grid_pixel_pos_list.append((x, y))
#         card_position_list.append((x + 10, y + 10))

print(grid_touple_list)
print(grid_pixel_pos_list)
print(card_position_list)<file_sep>import pygame

pygame.font.init()
myfont = pygame.font.SysFont('Comic Sans MS', 24)

class Player:
    def __init__(self):
        self.health = 5

    def sub_health(self):
        self.health -= 1

    def get_health(self):
        return self.health


class Stats:
    @staticmethod
    def draw(surface, label, pos):
        textsurface = myfont.render(label, False, (255, 255, 255))
        surface.blit(textsurface, (pos[0], pos[1]))
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 18:24:42 2020

@author: crtom

vector class from the book game development with pygame

Vectors describe: magnitude and direction.
"""
import math

class Vector2(object):
    def __init__(self, x=0.0, y=0.0):
        self.x = x
        self.y = y
    
    def __str__(self):
        return "(%s, %s)"%(self.x, self.y)
    
    # create vector from two points
    """These class methods are called from the class
    and not an instance of the class"""
    @classmethod
    def from_points(cls, P1, P2):
        return cls( P2[0] - P1[0], P2[1] - P1[1] )

    # pitagora for distance calculation
    def get_magnitude(self):
        return math.sqrt( self.x**2 + self.y**2 )
    
    """Unit vectors always have a length of 1,
    are often used to represent a heading. When we move into the third dimension,
    essential for everything from collision detection to lighting.
    """
    def normalize(self):
        magnitude = self.get_magnitude()
        self.x /= magnitude
        self.y /= magnitude

    # Addition: rhs stands for Right Hand Side
    def __add__(self, rhs):
        return Vector2(self.x + rhs.x, self.y + rhs.y)

    # Substraction: substracting means going in the opposite direction
    def __sub__(self, rhs):
        return Vector2(self.x - rhs.x, self.y - rhs.y)

    # Negation
    def __neg__(self):
        return Vector2(-self.x, -self.y)
    
    # Multiplication by scalar
    def __mul__(self, scalar):
        return Vector2(self.x * scalar, self.y * scalar)
    
    def __rmul__(self, scalar):
        return self.__mul__(scalar)   # commutative operation
    
    # Division by scalar
    def __truediv__(self, scalar):
        return Vector2(self.x / scalar, self.y / scalar)
    
    # check for equal
    def __eq__(self, other):
        if isinstance (other, self.__class__):
            return self.x == other.x and self.y == other.y
        return self.x == other and self.y == other
    
    # greater or equal
    def __ge__(self, other):
        if isinstance (other, self.__class__):
            return self.x >= other.x and self.y >= other.y
        return self.x >= other and self.y >= other
    
    def get_value(self):
        return (self.x, self.y)
#-----------------------------------------------------------------------------
def test_function_v1():

    # create vectors
    vector_a = Vector2(1, 1)
    vector_b = Vector2(0, 0)
    
    print(vector_a)
    print(vector_a.x, vector_a.y)
    
    # test_create_vector_from_two_points
    A = (10.0, 20.0)
    B = (30.0, 35.0)
    
    AB = Vector2.from_points(A, B)
    print('vector AB:',AB)    
    
    # get vector length, magnitude
    print('magnitude: ', AB.get_magnitude())
    
    AB.normalize()
    print('normalized:', AB)
 
 
def test_function_v2():

    A = (10.0, 20.0)
    B = (30.0, 35.0)
    C = (15.0, 45.0)
    
    AB = Vector2.from_points(A, B)
    BC = Vector2.from_points(B, C)
    print("Vector AB is", AB)
    print("Vector BC is", BC)
    
    AC = Vector2.from_points(A, C)
    print("Vector AC is", AC)
    
    AC = AB + BC
    print("Addition: AB + BC is", AC)
    
    AC = AB - BC
    print("Subtraction: AB - BC is", AC)

    AC = -AB
    print("Negation: -AB is", AC)        
    
    AC = 10*AB
    print("Multiplication: 10*AB is", AC) 
    
    AC = AB/2
    print("Division: AB/2 is", AC)

def calculate_position():
    #point A
    A = (10.0, 20.0)
    #point B
    B = (30.0, 35.0)
    
    # vector of distance between points AB
    AB = Vector2.from_points(A, B)
    
    # step vector, length of 1/10 AB
    step = AB * .1
    
    #start position vector at point A
    position = Vector2(A[0], A[1])
    
    for n in range(10):
        position += step
        print(position)
     
if __name__ == '__main__':
    #test_function_v2()
    calculate_position()<file_sep>def stereo_pan(x_coord, screen_width):

    right_volume = float(x_coord) / screen_width 
    left_volume = 1.0 - right_volume

    return (left_volume, right_volume)
<file_sep>import pygame
from pygame.locals import *
from sys import exit

pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)

while True:

    for event in pygame.event.get():
      if event.type == QUIT:
          pygame.quit()
          exit()
 
    screen.fill((255, 255, 255)) 

    mouse_pos = pygame.mouse.get_pos()

    for x in range(0,640,20):
        pygame.draw.line(screen, (0, 0, 0), (x, 0), mouse_pos)
        pygame.draw.line(screen, (0, 0, 0), (x, 479), mouse_pos)

    for y in range(0,480,20):
        pygame.draw.line(screen, (0, 0, 0), (0, y), mouse_pos)
        pygame.draw.line(screen, (0, 0, 0), (639, y), mouse_pos)

    pygame.display.update()
<file_sep>from math import sqrt 

class Vector3(object):

    def init (self, x, y, z):

        self.x = x 
        self.y = y 
        self.z = z

    def add (self, x, y, z):

        return Vector3(self.x + x, self.y + y, self.z + z)

    def get_magnitude(self):

        return sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
<file_sep>class Vector2:
    
    def __init__(self, x=0, y=0):        
        self.x = x
        self.y = y
        
    def __str__(self):
        return "(%s, %s)"%(self.x, self.y)
        
    def from_points(P1, P2):
        # ( P2[0] - P1[0], P2[1] - P1[1] ) is the same as:
        # numpy.array(P1) - numpy.array(P1)
        return Vector2(P2[0] - P1[0], P2[1] - P1[1])


A = (10.0, 20.0) 
B = (30.0, 35.0)
AB = Vector2.from_points(A, B)
print(AB)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Dec 25 21:10:25 2020

@author: crtom
"""

"""
Basic Movement and Key Presses
video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5

1. create a rectangle
2. move it by key pressed
"""

import pygame
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2

# draw antialiase line for vectors
from pygame import gfxdraw

from math import *

# defines  
WIDTH, HEIGHT = 640, 480

WHITE   = (255, 255, 255)
BLACK   = (0, 0, 0)
RED     = (255,0,0)
LIME    = (0,255,0)
BLUE    = (0,0,255)
YELLOW  = (255,255,0)
CYAN    = (0,255,255)
MAGENTA = (255,0,255)
SILVER  = (192,192,192)
GREY	= (128,128,128)
MAROON  = (128,0,0)
OLIVE   = (128,128,0)
GREEN   = (0,128,0)
PURPLE  = (128,0,128)
TEAL    = (0,128,128)
NAVY    = (0,0,128)

pygame.init()
#### Create a canvas on which to display everything ####
screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
#set windows title
pygame.display.set_caption("vector arrow")

#### Create a surface with the same size as the window ####
background = pygame.Surface((WIDTH, HEIGHT))
background.fill(WHITE)

clock = pygame.time.Clock()

def draw_point(screen, color, p, radius): #, color, position, radius
    
    point = (int(p[0]), int(p[1]))
    
    pygame.draw.circle(screen, color, point, radius)
    

def draw_line(screen, color, startpoint, vector, width):
    """
    Draws line representing vector.
    """

    v1 = Vector2(vector.x, vector.y)
    
    endpoint = (v1.x + startpoint[0], v1.y + startpoint[1])
    
    startpoint = (int(startpoint[0]), int(startpoint[1]))
    endpoint = (int(endpoint[0]), int(endpoint[1]))
    
    pygame.draw.line(screen, color, startpoint, endpoint, width)

# ----------drawing
p_A = (WIDTH // 2, HEIGHT // 2)
p_B = (WIDTH // 2, 50)
vector_AB = Vector2.from_points(p_A, p_B)

# print(p_A)
# print(p_B)
# #as_tuple


#------------------------
screen.blit(background, (0,0))

# draw_point(screen, RED, p_A, 5)
# pygame.display.update()

# draw_point(screen, BLUE, p_B, 5)
# pygame.display.update()

# draw_line(screen, color, startpoint, vector, width):
# ORIGINAL VECTOR
# draw_line(screen, BLACK, p_A, vector_AB, 3)
# pygame.display.update()

# ROTATED VECTOR
angle = 45
x_rot = cos(angle)*vector_AB.x - sin(angle)*vector_AB.y
y_rot = sin(angle)*vector_AB.x + cos(angle)*vector_AB.y
vector_AB_rot = Vector2(x_rot, y_rot)
# draw_line(screen, GREY, p_A, vector_AB_rot, 3)

# perpendicualar vector
vector_AB_perp = Vector2(-vector_AB_rot.y, vector_AB_rot.x)
# draw_line(screen, GREY, p_A, vector_AB_perp, 3)
# pygame.display.update()

# arrow head to original vector
# first find point on original vector that is a little bellow vector endpoint
vector_norm = Vector2(vector_AB.x, vector_AB.y)
# vector_norm.normalise()
vector_norm *= 10
vector_norm = vector_AB - vector_norm
# draw_line(screen, GREY, p_A, vector_norm, 3)
# pygame.display.update()

# find perpendicular vector to original
vector_perp = Vector2(-vector_AB.y, vector_AB.x)
vector_perp.normalize()
vector_perp *= 5

point = (int(vector_norm.x) +  p_A[0], int(vector_norm.y) +  p_A[1])
point = (point[0], point[1])

# draw_point(screen, BLACK, point, 5)

draw_line(screen, GREY, point, vector_perp, 3)
draw_line(screen, GREY, point, -vector_perp, 3)

# pointL = original_vector_startpoint+
point_R = (point[0] + vector_perp.x, point[1] + vector_perp.y)
point_L = (point[0] - vector_perp.x, point[1] - vector_perp.y)
# draw_point(screen, BLACK, point_R, 5)
# draw_point(screen, BLACK, point_L, 5)

endpoint = vector_AB.x+ p_A[0], vector_AB.y + p_A[1]

# draw rectangle
# pygame.draw.polygon(screen, GREEN, (point_L, point_R, endpoint))

# pygame.display.update()

# print(vector_AB)
# print(vector_norm)
# print(point)
# print(vector_perp)
# draw_line(screen, RED, p_A, vector_a, 3)
# pygame.display.update()

def draw_vector(screen, startpoint, vector, color, width, DEBUG = False):
    """
             E
            ***
           *****
          L**M**R
             *
             *
             *
             *
         ----S-----
             *
             *
             O
    
    E - vector endpoint  
    M - arrow midpoint  
    L - arrow left point  
    R - arrow right point  
    """
    #------------CALCULATIONS---------------
    #DEBUG = False
    # create points
    E = (0, 0) 
    L = (0, 0)
    M = (0, 0)
    R = (0, 0)

    # copy vector to new
    v = Vector2(int(vector.x), int(vector.y))
    
    # 1) set S - starrpoint
    S = (startpoint[0], startpoint[1])
    
    # 2) set E - endpoint
    E = (v.x + S[0], v.y + S[1])
    
    # 3) Find vector SM
    v_SM = Vector2(v.x, v.y)
    v_SM.normalize()
    v_SM *= 2*width # v_SM *= 10
    v_SM = v - v_SM
    
    M = (S[0]+v_SM.x, S[1]+v_SM.y) 
    
    # 3) Find perpendicular vector
    v_perp = Vector2(-v.y, v.x)
    v_perp.normalize()
    v_perp *= width # v_perp *= 5
    
    # 4) Find arrow head points
    L = (M[0] - v_perp.x, M[1] - v_perp.y)
    R = (M[0] + v_perp.x, M[1] + v_perp.y)
    
    #------------DRAWINGS---------------
    # pixels must be integers
    E = (int(E[0]),int(E[1]))
    M = (int(M[0]),int(M[1]))
    L = (int(L[0]),int(L[1]))
    R = (int(R[0]),int(R[1]))
    
    # draw main vector line
    pygame.draw.line(screen, color, S, M, width)
    
    # draw points for debugging purpose
    # points = S, E, L, M, R
    if DEBUG:
        print('S = ', S)
        print('E = ', E)
        print('M = ', M)
        print('M = ', L)
        print('M = ', R)
        pygame.draw.circle(screen, BLUE, S, 5)
        pygame.draw.circle(screen, BLUE, E, 5)
        
        pygame.draw.circle(screen, GREEN, M, 5)
        pygame.draw.circle(screen, RED, L, 5)
        pygame.draw.circle(screen, GREY, R, 5)
    
    # draw arrow head poligone
    # if very short, dont draw arrow
    #length = sqrt(v.x
    pygame.draw.polygon(screen, color, (L, R, E))
    
draw_vector(screen, p_A, vector_AB, BLACK, 5)

#----------------------
#main game loop
clock = pygame.time.Clock()
run = True
angle = 0.

while run:
    # pygame.time.delay(100) #this will be a clock for the game
    for event in pygame.event.get(): #check for all events that are happening
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            run = False
    
    # calculate times
    time_passed = clock.tick(30)
    time_passed_seconds = time_passed / 1000.0

    angle += 0.01

    x_rot = cos(angle)*vector_AB.x - sin(angle)*vector_AB.y
    y_rot = sin(angle)*vector_AB.x + cos(angle)*vector_AB.y
    vector_AB_rot = Vector2(x_rot, y_rot)

    # get X component
    magnitude = sqrt(vector_AB.x**2 + vector_AB.y**2)
    
    direction = Vector2(vector_AB_rot.x, vector_AB_rot.y)
    direction.normalize()
    # print(direction)
    
    #x_component = magnitude * sin(angle)
    x_component = direction.x * magnitude
    y_component = direction.y * magnitude
    #y_component = magnitude * cos(angle)
    
    # print('angle:', angle, 'x_component:', x_component,'y_component:', y_component)
    
    v_x = Vector2(x_component, 0)
    v_y = Vector2(0, y_component)
    
    #---------------UPDATE DISPALY-----------
    screen.blit(background, (0,0))
    # draw circle
    
    pygame.draw.circle(screen, GREY, p_A, int(magnitude),2)
    pygame.draw.line(screen, GREY, (0, HEIGHT//2), (WIDTH, HEIGHT//2), 2)
    pygame.draw.line(screen, GREY, (WIDTH//2, 0), (WIDTH//2, HEIGHT), 2)
    
    draw_vector(screen, p_A, vector_AB_rot, BLACK, 5)
    draw_vector(screen, p_A, v_x, RED, 5)
    draw_vector(screen, p_A, v_y, BLUE, 5)

    # update all drawing objects
    pygame.display.update()
    
# exit pygame
pygame.quit()
exit()

"""
    #draw_arrow(screen, 0, 10, GREEN)
    #------------------DRAWINGS------------------------
    #### Blit the surface onto the canvas ####
    screen.blit(background,(0,0))
    #### Blit the points onto canvas
    
    angle += 0.01
    
    
    #draw_arrow(screen, colour, startpoint, vector, width):
    draw_point(screen, BLUE, p_A, 5)
    #draw_point(screen, GREEN, p_B, 5)
    draw_arrow(screen, BLUE, p_A, vector_AB_rot, 2)
    #screen.blit(arrow, arrow_pos)
    #### display canvas ####
    pygame.display.update()
    x_rot = cos(angle)*vector_AB.x - sin(angle)*vector_AB.y
    y_rot = sin(angle)*vector_AB.x + cos(angle)*vector_AB.y
    
    vector_AB_rot = Vector2(x_rot, y_rot)
"""<file_sep>def perspective_project(vector3, d):
    x, y, z = vector3
    return (x * d/z, -y * d/z)
<file_sep>import sys
import math
import random
import pygame
from pygame.locals import *
import tkinter as tk
from tkinter import messagebox

clock = pygame.time.Clock()

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
#--------------------------draw grid fuction----------------------------
def drawGrid(w,rows,surface):
	"""
	This function draws a square grid on main display
	"""
	#distance between grid lines
	sizeBtwn = w // rows
	x = 0
	y = 0

	#create grid by drawing lines
	for l in range(rows):
		x = x + sizeBtwn
		y = y + sizeBtwn

		#vertical lines
		pygame.draw.line(surface, WHITE, (x,0), (x,w))
		#horizontal lines
		pygame.draw.line(surface, WHITE, (0,y), (w,y))

#-------------------------cube object-----------------------------------------
class cube(object):
	"""
	class to create a single grid cube, that has position and movement
	"""
	rows = 20 #set number of rows
	w = 500 #set pixel screen width
	def __init__(self, start, dirnx, dirny, color = WHITE):
		self.pos = start	#touple (x,y)
		self.dirnx = 0
		self.dirny = 0
		self.color = color	#touple(r,g,b)

	def set_direction(self,dirnx,dirny):
		self.dirnx = dirnx
		self.dirny = dirny

	def move(self):
		"""
		move cube, by adding new direction to previous position
		"""
		self.pos = (self.pos[0]+self.dirnx, self.pos[1]+self.dirny)

	def draw(self,surface):
		"""
		drawing: convert x,y grid position to pixel position
		"""
		dis = self.w // self.rows #distance between x and y values
		#variables for easy coding
		i = self.pos[0] # row
		j = self.pos[1] # column
		#draw just a little bit less, so we draw inside of the square. and we dont cover grid.
		pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1,dis-2,dis-2 ))
#-----------------------------------------------------------------------------------
class snake(object):
	"""
	class for snake
	"""
	body = [] #list of cube objects
	turns = {} #dictionary of turns  ADDING A KEY OF-->
	# key = current position of snake head
	# value = direction of turn]
	def __init__(self,color,pos):
		self.color = color
		self.head = cube(pos)
		self.body.append(self.head) # snake starts with one cube = head
		self.dirnx = 0	#direction moving x 1, -1
		self.dirny = 1	#direction moving y 1, -1
	#---------------------------------------------------------------------
	def move(self):
		"""
		moving our snake in x,y thinking
		LEFT  	(self.dirnx=-1, self.dirny=0)
		RIGHT 	(self.dirnx=1, self.dirny=0)
		UP 		(self.dirnx=0, self.dirny=1)
		DOWN 	(self.dirnx=0, self.dirny=-1)
		"""
		for event in pygame.event.get():
			if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
				pygame.quit()
				sys.exit()

			keys = pygame.key.get_pressed()
			for key in keys:
				if keys[pygame.K_LEFT]:
					self.dirnx = -1
					self.dirny = 0
					# we mustremember where we turned, so other cubes can follow
					# add a new key
					#example - here we turned in thar way
					self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
				elif keys[pygame.K_RIGHT]:
					self.dirnx = 1
					self.dirny = 0
					self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
				elif keys[pygame.K_UP]:
					self.dirnx = 0
					self.dirny = -1
					self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
				elif keys[pygame.K_DOWN]:
					self.dirnx = 0
					self.dirny = 1
					self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

		#look trough all position of snake
		#we get the index=i and the cube=c of body
		for i, c in enumerate(self.body):
			p = c.pos[:]
			#for each of the sube, we grab position and check turn
			#if this position in turns, than we move
			if p in self.turns:
				turn = self.turns[p]
				#here we store direction where to move
				c.move(turn[0],turn[1])
				#if we are on the last cube of the snake, remove the turn, we finished it
				if i == len(self.body)-1:
					self.turns.pop(p)

			else:	#CHECK IF WE REACHED EDGE OF THE SCREEN
				#if MOVE LEFT & we are at the left side of screen
				if (c.dirnx == -1) and (c.pos[0] <= 0):
					c.pos = (c.rows-1,c.pos[1])
					#c.pos = (c.rows-1,c.pos[1])
				#if MOVE RIGHT & we are at the left side of screen
				elif (c.dirnx == 1) and (c.pos[0] >= c.rows-1):
					c.pos = (0,c.pos[1])
				#if MOVE DOWN & we are at the left side of screen
				elif (c.dirny == 1) and (c.pos[1] >= c.rows-1):
					c.pos = (c.pos[0],0)
				#if MOVE UP & we are at the left side of screen
				elif (c.dirny == -1) and (c.pos[1] <= 0):
					c.pos = (c.pos[0],c.rows-1)
				#normal move of cube
				else:
					c.move(c.dirnx,c.dirny)
	#---------------------------------------------------------------------
	def addCube(self):
		"""
		Figure out where is tail, and add a cube after it
		"""
		tail = self.body[-1]
		dx, dy = tail.dirnx, tail.dirny

		if dx == 1 and dy == 0:
			self.body.append(cube((tail.pos[0]-1,tail.pos[1])))
		elif dx == -1 and dy == 0:
			self.body.append(cube((tail.pos[0]+1,tail.pos[1])))
		elif dx == 0 and dy == 1:
			self.body.append(cube((tail.pos[0],tail.pos[1]-1)))
		elif dx == 0 and dy == -1:
			self.body.append(cube((tail.pos[0],tail.pos[1]+1)))

		self.body[-1].dirnx = dx
		self.body[-1].dirny = dy

	#---------------------------------------------------------------------
	def draw(self,surface):
		for index, cube in enumerate(self.body):
			#check where to draw eyes for snake head
			if index == 0:
				cube.draw(surface,True) #with eyes
			else:
				cube.draw(surface,False) #without eyes

#-----------------------------------------------------------------------------------
def redrawWindow(surface):
	global rows, width
	#background
	surface.fill(BLACK)
	#draw grid
	drawGrid(width, rows, surface)
	#draw ball
	ball.draw(surface)
	#update display
	pygame.display.update()
#---------------------------------------------------------------------------------------
def key_events():
	for event in pygame.event.get():
			if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
				#pygame.quit()
				#sys.exit()
				return True

	#in pong we move in only y directions
	keys = pygame.key.get_pressed()
	for key in keys:
		if keys[pygame.K_UP]:
			self.dirny = -1
			self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
		elif keys[pygame.K_DOWN]:
			self.dirny = 1
			self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

	return False
#---------------------------------------------------------------------------------------
def main():
	global width, rows, ball
	#---------------game initialization---------------------------
	#create game display
	width = 500
	rows = 20

	#create game objects
	win = pygame.display.set_mode((width, width)) #square display
	ball = cube((10,1),0,0,WHITE)
	ball.set_direction(1,1) #set initial ball movement direction

	FPScount = 0
	#-----------------------continuous game loop-------------
	GameOver = False
	while not GameOver:
		#pygame.time.delay(50)
		clock.tick(10)	#game max speed 10 FPS
		GameOver = key_events()

		#update ball position
		ball.move()
		#check next direction-------------------------------
		#CONSTRAINTS X
		if ball.pos[0] <= 0 or ball.pos[0] >= rows-1:
			ball.dirnx = -ball.dirnx
		#CONSTRAINTS Y
		if ball.pos[1] <= 0 or ball.pos[1] >= rows-1:
			ball.dirny = -ball.dirny

		#-------------------------------------------------
		#if we are moving in right direction
		#print(f'rows:{rows} ball.pos[0]:{ball.pos[0]} ball.pos[1]:{ball.pos[1]}')
		#FPScount += 1
		#print(FPScount)

		redrawWindow(win)
#---------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------
main()
pygame.quit()
sys.exit()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Dec 28 18:28:20 2020

@author: crtom
"""
import pygame as pg
from settings import * 

class Map:
    def __init__(self, filename):
        self.data = []
        with open(filename, 'rt') as f:
            for line in f:
                self.data.append(line.strip()) # remove new line char at end
                # print(line)
    
        # how big map is
        self.tilewidth = len(self.data[0]) # N of columns
        self.tileheight = len(self.data) # N of rows
        
        # pixel width of the map
        self.width = self.tilewidth * TILESIZE
        self.height = self.tileheight * TILESIZE

# camera object is independant from other objects. it needs only tilemap
class Camera:
    # 1. must shift the drawing rectangle to what we want to draw
    # 2. camera must update to where the player offset is
    
    """ theory
    - Returns a Rect moved x pixels horizontally and y pixels vertically
    Rect.move(x, y)
    """
    def __init__(self, width, height):
        # use rectangle to track camera
        #self.camera = pg. Rect(SHIFT_X, SHIFT_Y, width, height)
        self.camera = pg. Rect(0, 0, width, height)
        self.width = width
        self.height = height
        
    def apply(self, entity):
        return entity.rect.move(self.camera.topleft)
    
    # update and follow targeted sprite
    def update(self, target):
        # if player moves to right, map moves to the left
        x = -target.rect.x + int(WIDTH / 2)
        y = -target.rect.y + int(HEIGHT / 2)
        
        # now limit scrolling, so we dont see over the map
        x = min(0, x) # left side
        y = min(0, y) # top side
        
        x = max(-(self.width - WIDTH), x) # right side
        y = max(-(self.height - HEIGHT), y) # bottom side
                
        
        # ADJUST WHERE our camera rectangle is
        self.camera = pg.Rect(x, y, self.width, self.height)
    <file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Dec 15 18:09:41 2020

@author: crtom

- BASIC ARHITECTURE, get mouse coordinates

#------------------------------------------------------------------------------
    #--------------------------------------------------------------------------
        #----------------------------------------------------------------------
            #------------------------------------------------------------------
                #--------------------------------------------------------------
"""

import pygame
import sys

from pygame.locals import * # this is for shortcut pygame.QUIT -> QUIT

#--------------------------------------------------------------------------
#-------------------------constants----------------------------------------
#--------------------------------------------------------------------------

FPS = 30
WINDOWWIDTH = 640 
WINDOWHEIGHT = 480 
REVEALSPEED = 8
BOXSIZE = 40
GAPSIZE = 10
BOARDWIDTH = 10
BOARDHEIGHT = 7

# check
assert(BOARDWIDTH*BOARDHEIGHT) % 2 == 0, 'Board needs to have an even number of boxes for pairs of matches'

XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE + GAPSIZE))) / 2)
YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE))) / 2)

# COLORS  ( R ,  G ,  B )
WHITE   = (255, 255, 255)
BLACK   = (  0,   0,   0)
RED     = (255,   0,   0)
LIME    = (  0, 255,   0)
BLUE    = (  0,   0, 255)
NAVYBLUE= ( 60,  60, 100)
YELLOW  = (255, 255,   0)
ORANGE  = (255, 128,   0)
CYAN    = (  0, 255, 255)
MAGENTA = (255,   0, 255)
SILVER  = (192, 192, 192)
GRAY	= (128, 128, 128)
MAROON  = (128,   0,   0)
OLIVE   = (128, 128,   0)
GREEN   = (  0, 128,   0)
PURPLE  = (128,   0, 128)
TEAL    = (  0, 128, 128)
NAVY    = (  0,   0, 128)

BGCOLOR = NAVYBLUE
LIGHTBGCOLOR = GRAY
BOXCOLOR = WHITE
HIGHLIGHTCOLOR = BLUE

DONUT = 'donut'
SQUARE = 'square'
DIAMOND = 'diamond' 
LINES = 'lines'
OVAL = 'oval'

ALLCOLORS = (RED, GREEN, BLUE, YELLOW, ORANGE, PURPLE, CYAN)
ALLSHAPES = (DONUT, SQUARE, DIAMOND, LINES, OVAL)

assert len(ALLCOLORS) * len(ALLSHAPES) * 2 <= BOARDWIDTH * BOARDHEIGHT,'Board is too big for the number of shapes/colors defined.'

#------------------------------------------------------------------------------
#----------------------------main loop-----------------------------------------
#------------------------------------------------------------------------------
def main():
    
    # global variables
    global FPSCLOCK, DISPLAYSURF
    
    # for mouse pos
    mousex = 0
    mousey = 0
    
    #--------------------------------------------------------------------------
    # init pygame
    pygame.init()
    
    FPSCLOCK = pygame.time.Clock() # initialize clock
    
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) # initialize surface
    DISPLAYSURF.fill(BGCOLOR)
    
    pygame.display.set_caption('Memory Game')

    #--------------------------------------------------------------------------
    #-------------------------GAME loop----------------------------------------
    #--------------------------------------------------------------------------
    while True:
        
        #----------------------event handling---------------------------------
        for event in pygame.event.get():
            
            # event objects have type attribute
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEMOTION:
                mousex, mousey = event.pos
            elif event.type == MOUSEBUTTONUP:
                mousex, mousey = event.pos
                mouseCicked = True
                print(mousex, mousey)
        
        #------------------------timing----------------------------------------
        # draws surface object stored in DISPLAYSURF
        pygame.display.update()
        FPSCLOCK.tick(FPS)
    
#------------------------------------------------------------------------------
#-------------------------function definitions---------------------------------
#------------------------------------------------------------------------------
    
#------------------------------------------------------------------------------
#-------------------------Start application------------------------------------
#------------------------------------------------------------------------------        
if __name__ == '__main__':
    main()<file_sep>"""
Basic Movement and Key Presses
video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5

1. create a rectangle
2. move it by key pressed
"""

import pygame
from pygame.locals import *

from rgb_color_dictionary import *

pygame.init()

#create window
win = pygame.display.set_mode((500,500))
#set windows title
pygame.display.set_caption("First Game")

#character variables
x = 50
y = 50
width = 40
height = 60
vel = 5

class player(object):
	def __init__(self, x, y, vx, vy, width, height):
		self.x = x
		self.y = y
		self.width = width
		self.height = height
		self.vx = vx
		self.vy = vy
		self.vel = 5
		self.isJump = False
		self.jumpCount = 10
		self.left = False
		self.right = False
		self.up = False
		self.down = False
		self.walkCount = 0

	def draw(self,win):
		pygame.draw.rect(win,RED,(self.x,self.y,self.width,self.height)) #draw player

	def set_speed(self, vx, vy):
		red_cube.vx = vx
		red_cube.vy = vy


def redrawGameWindow():
	pygame.display.update()

#create a player
red_cube = player(x=50,y=50,vx=0,vy=0, width=40,height=60)

#main game loop
run = True
while run:

	pygame.time.delay(100) #this will be a clock for the game
	keys = {'left':False,'right':False, 'up':False, 'down':False}

	for event in pygame.event.get(): #check for all events that are happening
		if event.type == pygame.QUIT:
			run = False
		if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
			run = False

	red_cube.set_speed(0,0)	#cube not moving

	keystate = pygame.key.get_pressed()
	#straight moves
	if keystate[pygame.K_UP]:
		red_cube.vy = -5
	if keystate[pygame.K_DOWN]:
		red_cube.vy = 5
	if keystate[pygame.K_LEFT]:
		red_cube.vx = -5
	if keystate[pygame.K_RIGHT]:
		red_cube.vx = 5
	#diagonals must be slower for sq(2)= 1.414 pitagora
	if red_cube.vx != 0 and red_cube.vy != 0:
		red_cube.vx /= 1.414
		red_cube.vy /= 1.414

	red_cube.x += red_cube.vx
	red_cube.y += red_cube.vy
	#print(keys)

	win.fill(BLACK)	#draw background
	#pygame.draw.rect(win,RED,(x,y,width,height)) #draw player
	red_cube.draw(win)

	redrawGameWindow()
<file_sep>import os
from random import randint


class Grid:
    def __init__(self, WIDTH, HEIGHT):
        self.WIDTH = WIDTH
        self.HEIGHT  = HEIGHT
        self.grid = self.create()
        self.p_x = self.WIDTH // 2
        self.p_y = self.HEIGHT - 2
        self.set_player_pos(self.p_x, self.p_y)
        self.timer = 2
        self.catched = 0
        self.lost = 0

    def create(self):
        brd = []
        for h in range(self.HEIGHT):
            brd.append([])
            for w in range(self.WIDTH):
                if w < 1 or w == self.WIDTH-1:
                    brd[h].append('x')
                elif h == self.HEIGHT-1:
                    brd[h].append('x')
                else:
                    brd[h].append('.')
        return brd

    def draw(self):
        self.clear()
        for row in self.grid:
            for character in row:
                print(character, end='')
            print()
        print("Eggs catched: " + str(self.catched) + "    " + "Eggs lost: " + str(self.lost))

    def update(self):
        self.timer -= 0.5
        if self.timer < 0:
            self.add_egg(randint(1, self.WIDTH-2), 1)
            self.timer = randint(1, 5)

        self.move_eggs()

    def clear(self):
        os.system('cls') # only works with CMD and Powershell, doesn't work with Git-Bash

    def set_player_pos(self, x, y):
        self.p_x, self.p_y = x, y

    def get_player_pos(self):
        return self.p_x, self.p_y

    def set_cell(self, x, y, chr):
        self.grid[y][x] = chr

    def get_cell(self, x, y):
        return self.grid[y][x]

    def check_Hbounds(self, x):
        return x > 0 and x < self.WIDTH-1

    def check_Vbounds(self, y):
        return y >= 0 and y < self.HEIGHT-2

    def add_egg(self, x, y):
        self.grid[y][x] = 'o'

    def move_eggs(self):
        for y in range(len(self.grid)-1, 0, -1):
            for x in range(len(self.grid[y])):
                if self.get_cell(x, y) == 'o' and self.check_Vbounds(y):
                    self.set_cell(x, y, '.')
                    self.set_cell(x, y+1, 'o')
                    if self.get_cell(x, y+2) == 'U':
                        self.catched += 1
                elif self.get_cell(x, y) == 'o':
                    self.set_cell(x, y, '.')
                    self.lost += 1

    <file_sep>"""
Lists & Tic Tac Toe Game - Python 3 Programming Tutorial p.3
user: sentdex
playlist: https://www.youtube.com/playlist?list=PLQVvvaa0QuDeAams7fkdcwOGBpGdHpXln
link: https://www.youtube.com/watch?v=tf3ezjeTpfI

stayed here: https://www.youtube.com/watch?v=BYpSfx7I6x4
"""

game = [[1,2,3],
		[4,5,6],
		[7,8,9]]

def game_board(game_map, player=0, row=0, column=0, just_display = False):
	try:
		#print column names
		print("   a  b  c")
		if not just_display:
			game_map[row][column] = player

		for count,row in enumerate(game_map):
			print(count,row)

		return game_map

	except IndexError as e:
		print("Error: make sure you input row/column as 0,1,2", e)

	except Exception as e:
		print("something went very wrong",e)

def win(current_game):
	#check horizontal row for same [1,1,1]"""
	for row in current_game:
		if row.count(row[0]) == len(row) and row[0] != 0:
			#print(f"wineer")

	#check vertical column for same [1,1,1]"""

	for column in current_game:
		print(game[column])

game = game_board(game, just_display = True)
#game = game_board(game, player=1, row=2, column=1)
win(game)<file_sep>
print("steamchine example!")


# This variable holds the current state of the machine
stateNum = 0

def advance_state_machine():
    global stateNum
    if stateNum == 0:      # Transition from state 0 to state 1
       print("yellow")
       stateNum = 1
    elif stateNum == 1:    # Transition from state 1 to state 2
       print("red")
       stateNum = 2
    else:                  # Transition from state 2 to state 0
       print("green")
       stateNum = 0

while True:
  user_input = input("press up, pres down")
  print(user_input)
  if user_input == "q":
    break
  elif user_input == "w":
    advance_state_machine()
<file_sep>"""
Simple pong in python 3 for begginers

tutorial series: https://www.youtube.com/playlist?list=PLlEgNdBJEO-kXk2PyBxhSmo84hsO3HAz2
"""

import turtle

wn = turtle.Screen()
wn.title("Pong by @TokyoEdTech")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)

# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed() #sets the speed of animation to max
paddle_a.shape("square") #default is 20x20 pixels
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5, stretch_len = 1) # strech the square
paddle_a.penup()
paddle_a.goto(-350,0)

# Paddle B
paddle_b = turtle.Turtle()
paddle_b.speed() #sets the speed of animation to max
paddle_b.shape("square") #default is 20x20 pixels
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5, stretch_len = 1) # strech the square
paddle_b.penup()
paddle_b.goto(350,0)

# Ball
ball = turtle.Turtle()
ball.speed() #sets the speed of animation to max
ball.shape("square") #default is 20x20 pixels
ball.color("white")
ball.penup()
ball.goto(0,0)

# Functions
def paddle_a_up():
	y = paddle_a.ycor() #method, returns y coor
	y+= 20 #add 20 pixels to y coor
	paddle_a.sety(y)

def paddle_a_down():
	y = paddle_a.ycor() #method, returns y coor
	y -= 20 #add 20 pixels to y coor
	paddle_a.sety(y)

def paddle_b_up():
	y = paddle_b.ycor() #method, returns y coor
	y+= 20 #add 20 pixels to y coor
	paddle_b.sety(y)

def paddle_b_down():
	y = paddle_b.ycor() #method, returns y coor
	y -= 20 #add 20 pixels to y coor
	paddle_b.sety(y)

#keyboard biding
wn.listen() #listen for key inputs
wn.onkey(paddle_a_up,"w") #when user press "w" call function paddle_a_up
wn.onkey(paddle_a_down,"s") #when user press "w" call function paddle_a_up
wn.onkey(paddle_b_up,"Up") #when user press "w" call function paddle_a_up
wn.onkey(paddle_b_down,"Down") #when user press "w" call function paddle_a_up


# main game loop
while True:
	wn.update() #updates screen<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 23:13:08 2020

@author: crtom
"""

import pygame as pg
from settings import *
from tilemap import collide_hit_rect

vec = pg.math.Vector2

class Player(pg.sprite.Sprite):
    def __init__(self, game, x, y):
       
        # so player can acces all sprites in the game
        self.game = game
        self.groups = game.all_sprites
        
        # 1.) sprite class default override:
        #Call the parent class (Sprite) constructor
        pg.sprite.Sprite.__init__(self, self.groups)

        # 2.) sprite class default override:
        # tile based game - player is only one tile large
        
        # self.image = pg.Surface((TILESIZE, TILESIZE)) # YELLOW BLOCK SPRITE
        # self.image.fill(YELLOW)
        self.image = game.player_img
        # 3.) sprite class default override:
        # Fetch the rectangle object that has the dimensions of the image
        # Update the position of this object by setting the values of rect.x and rect.y       
        self.rect = self.image.get_rect()
        
        self.hit_rect = PLAYER_HIT_RECT
        self.hit_rect.center = self.rect.center
        
        # CUSTOM ATTRIBUTES
        #self.dt = 0
        self.vel = vec(0, 0)
        self.pos = vec(x, y) * TILESIZE
        self.rot = 0
    
    def get_keys(self):
        self.vel = vec(0, 0)
        self.rot_speed = 0
        
        keys = pg.key.get_pressed()
        
        if keys[pg.K_LEFT] or keys[pg.K_a]:
            # self.player.move(dx=-1)
            self.rot_speed = PLAYER_ROT_SPEED
        elif keys[pg.K_RIGHT] or keys[pg.K_d]: # IF ENABLES DIAG
            self.rot_speed = -PLAYER_ROT_SPEED
        if keys[pg.K_UP] or keys[pg.K_w]: # IF ENABLES DIAG
            self.vel = vec(PLAYER_SPEED, 0).rotate(-self.rot)
        # backwards move is slower
        if keys[pg.K_DOWN] or keys[pg.K_s]: # IF ENABLES DIAG
            self.vel = vec(-PLAYER_SPEED / 2, 0).rotate(-self.rot)
    
    def collide_with_walls(self, direction):
        # x collision check
        if direction == 'x':
            
            # modify this to use hit_rect instead
            #hits = pg.sprite.spritecollide(self, self.game.walls, False) # false= dont delete the wall
            hits = pg.sprite.spritecollide(self, 
                                           self.game.walls, 
                                           False,
                                           collide_hit_rect) # false= dont delete the wall
            
            if hits:
                # sprite was moving to the right
                # we need to put the sprite to the left edge of the wall
                if self.vel.x > 0:
                    #because we use rectangle centre / 2
                    self.pos.x = hits[0].rect.left - self.hit_rect.width / 2
                # sprite was moving to the left
                # we need to put the sprite to the right edge of the wall
                if self.vel.x < 0:
                    self.pos.x = hits[0].rect.right + self.hit_rect.width / 2 #- self.rect.width    
                
                # we run into the wall, x velocity = 0
                self.vel.x = 0
                # update new position of hit_rect
                self.hit_rect.centerx = self.pos.x

        if direction == 'y':
            #hits = pg.sprite.spritecollide(self, self.game.walls, False) # false= dont delete the wall
            hits = pg.sprite.spritecollide(self, 
                                           self.game.walls,
                                           False,
                                           collide_hit_rect) # false= dont delete the wall
            
            if hits:
                # sprite was moving down
                # we need to put the sprite to the top of the wall
                if self.vel.y > 0: 
                    self.pos.y = hits[0].rect.top - self.hit_rect.height / 2
                # sprite was moving to the top
                # we need to put the sprite to the bottom edge of the wall
                if self.vel.y < 0:
                    self.pos.y = hits[0].rect.bottom + self.hit_rect.height / 2 #- self.rect.width    
                
                # we run into the wall, x velocity = 0
                self.vel.y = 0
                # update new position of hit_rect
                self.hit_rect.centery = self.pos.y
                    
    def update(self):
        # 1.) read keyboard
        self.get_keys()
        # 2.) calculate rotation
        self.rot = (self.rot + self.rot_speed*self.game.dt) % 360
        # 3.) Update player sprite image with rotation
        self.image = pg.transform.rotate(self.game.player_img, self.rot)
        
        self.rect = self.image.get_rect()
        self.rect.center = self.pos
        # 4.) calculate position
        # this will make movement independant of frame rate
        self.pos += self.vel * self.game.dt # get dt from game object
        
        # 5.) check if collision with walls
        # if collision, than dont reverse to old position aka dont move
        self.hit_rect.centerx = self.pos.x
        self.collide_with_walls('x')
        
        self.hit_rect.centery = self.pos.y
        self.collide_with_walls('y')
        
        # 6.)when we update movement, be set equal 
        # sprite image rectangle and hit rectangle
        self.rect.center = self.hit_rect.center


class Wall(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        
        # so player can acces all sprites in the game
        # member of all sprites group
        # member of all walls group
        self.groups = game.all_sprites, game.walls
        
        pg.sprite.Sprite.__init__(self, self.groups)
        
        self.game = game
        # tile based game - player is only one tile large
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y
        
        self.rect.x = x * TILESIZE
        self.rect.y = y * TILESIZE<file_sep>"""Snake Game Python Tutorial
youtube video: https://www.youtube.com/watch?v=CD4qAhfFuLo
current time: 34:00
"""
import sys
import math
import random
import pygame
from pygame.locals import *
import tkinter as tk
from tkinter import messagebox

BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
#-----------------------------------------------------------------------------------
class cube(object):
	"""
	"""
	rows = 20 #set number of rows
	w = 500 #set pixel screen width
	def __init__(self, start, dirnx=1, dirny=0, color = RED):
		self.pos = start
		self.dirnx = 1
		self.dirny = 0
		self.color = color

	def move(self,dirnx,dirny):
		"""
		move cube, by adding new direction to previous position
		"""
		self.dirnx = dirnx
		self.dirny = dirny
		self.pos = (self.pos[0]+self.dirnx, self.pos[1]+self.dirny)

	def draw(self,surface,eyes=False):
		"""
		drawing: convert x,y grid position to pixel position
		"""
		dis = self.w // self.rows #distance between x and y values
		#variables for easy coding
		i = self.pos[0] # row
		j = self.pos[1] # column
		#draw just a little bit less, so we draw inside of the square. and we dont cover grid.
		pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1,dis-2,dis-2 ))

		#draw eyes
		if eyes:
				centre = dis//2
				radius = 3
				circleMiddle = (i*dis+centre-radius, j*dis+8 ) #eye 1
				circleMiddle2 = (i*dis+dis-radius*2, j*dis+8 ) #eye 2
				pygame.draw.circle(surface, BLACK, circleMiddle, radius)
				pygame.draw.circle(surface, BLACK, circleMiddle2, radius)
#-----------------------------------------------------------------------------------
class snake(object):
	"""
	class for snake
	"""
	body = [] #list of cube objects
	turns = {} #dictionary of turns  ADDING A KEY OF-->
	# key = current position of snake head
	# value = direction of turn]
	def __init__(self,color,pos):
		self.color = color
		self.head = cube(pos)
		self.body.append(self.head) # snake starts with one cube = head
		self.dirnx = 0	#direction moving x 1, -1
		self.dirny = 1	#direction moving y 1, -1
	#---------------------------------------------------------------------
	def move(self):
		"""
		moving our snake in x,y thinking
		LEFT  	(self.dirnx=-1, self.dirny=0)
		RIGHT 	(self.dirnx=1, self.dirny=0)
		UP 		(self.dirnx=0, self.dirny=1)
		DOWN 	(self.dirnx=0, self.dirny=-1)
		"""
		for event in pygame.event.get():
			if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
				pygame.quit()
				sys.exit()

			keys = pygame.key.get_pressed()
			for key in keys:
				if keys[pygame.K_LEFT]:
					self.dirnx = -1
					self.dirny = 0
					# we mustremember where we turned, so other cubes can follow
					# add a new key
					#example - here we turned in thar way
					self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
				elif keys[pygame.K_RIGHT]:
					self.dirnx = 1
					self.dirny = 0
					self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
				elif keys[pygame.K_UP]:
					self.dirnx = 0
					self.dirny = -1
					self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
				elif keys[pygame.K_DOWN]:
					self.dirnx = 0
					self.dirny = 1
					self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

		#look trough all position of snake
		#we get the index=i and the cube=c of body
		for i, c in enumerate(self.body):
			p = c.pos[:]
			#for each of the sube, we grab position and check turn
			#if this position in turns, than we move
			if p in self.turns:
				turn = self.turns[p]
				#here we store direction where to move
				c.move(turn[0],turn[1])
				#if we are on the last cube of the snake, remove the turn, we finished it
				if i == len(self.body)-1:
					self.turns.pop(p)

			else:	#CHECK IF WE REACHED EDGE OF THE SCREEN
				#if MOVE LEFT & we are at the left side of screen
				if (c.dirnx == -1) and (c.pos[0] <= 0):
					c.pos = (c.rows-1,c.pos[1])
					#c.pos = (c.rows-1,c.pos[1])
				#if MOVE RIGHT & we are at the left side of screen
				elif (c.dirnx == 1) and (c.pos[0] >= c.rows-1):
					c.pos = (0,c.pos[1])
				#if MOVE DOWN & we are at the left side of screen
				elif (c.dirny == 1) and (c.pos[1] >= c.rows-1):
					c.pos = (c.pos[0],0)
				#if MOVE UP & we are at the left side of screen
				elif (c.dirny == -1) and (c.pos[1] <= 0):
					c.pos = (c.pos[0],c.rows-1)
				#normal move of cube
				else:
					c.move(c.dirnx,c.dirny)
	#---------------------------------------------------------------------
	def reset(self,pos):
		"""
		- reset snake back to start state
		- delete turns
		- delete body
		- change direction dirnx, dirny
		"""
		self.head = cube(pos)
		self.body = []
		self.body.append(self.head)
		self.turns = {}
		self.dirnx = 0
		self. dirny = 1

	#---------------------------------------------------------------------
	def addCube(self):
		"""
		Figure out where is tail, and add a cube after it
		"""
		"""
		tail = self.body[-1] #last element in list is tail
		dx = tail.dirnx
		dy = tail.dirny

		#check in which direction is tail movin, so we know if we add it to left,right,up,down
		#we append a new cube to the body, that has one less position that the tail
		#are we moving right, append to left
		if dx == 1 and dy == 0:
			self.body.append(cube((tail.pos[0]-1,tail.pos[1]))

		#are we moving left, append to right
		#if dx == -1 and dy == 0:
		#	self.body.append(cube((tail.pos[0]+1,tail.pos[1]))
		#are we moving up, append to down
		#if dx == 0 and dy == 1:
		#	self.body.append(cube((tail.pos[0],tail.pos[1]-1))
		#are we moving down, append to up
		#if dx == 0 and dy == -1:
		#	self.body.append(cube((tail.pos[0],tail.pos[1]+1))

		#if we just leave it like this. the cube is not moving
		#add it moving
		self.body[-1].dirnx = dx
		self.body[-1].dirny = dy
		"""
		tail = self.body[-1]
		dx, dy = tail.dirnx, tail.dirny

		if dx == 1 and dy == 0:
			self.body.append(cube((tail.pos[0]-1,tail.pos[1])))
		elif dx == -1 and dy == 0:
			self.body.append(cube((tail.pos[0]+1,tail.pos[1])))
		elif dx == 0 and dy == 1:
			self.body.append(cube((tail.pos[0],tail.pos[1]-1)))
		elif dx == 0 and dy == -1:
			self.body.append(cube((tail.pos[0],tail.pos[1]+1)))

		self.body[-1].dirnx = dx
		self.body[-1].dirny = dy

	#---------------------------------------------------------------------
	def draw(self,surface):
		for index, cube in enumerate(self.body):
			#check where to draw eyes for snake head
			if index == 0:
				cube.draw(surface,True) #with eyes
			else:
				cube.draw(surface,False) #without eyes

#-----------------------------------------------------------------------------------
def drawGrid(w,rows,surface):
	"""
	This function draws a square grid on main display
	"""
	#distance between grid lines
	sizeBtwn = w // rows
	x = 0
	y = 0

	#create grid by drawing lines
	for l in range(rows):
		x = x + sizeBtwn
		y = y + sizeBtwn
		#vertical lines
		pygame.draw.line(surface, WHITE, (x,0), (x,w))
		#horizontal lines
		pygame.draw.line(surface, WHITE, (0,y), (w,y))
#-----------------------------------------------------------------------------------
def redrawWindow(surface):
	global rows, width, s, snack
	#background
	surface.fill(BLACK)
	s.draw(surface)
	snack.draw(surface)
	#draw grid
	drawGrid(width, rows, surface)
	#update display
	pygame.display.update()
#-----------------------------------------------------------------------------------
def randomSnack(rows,item):
	"""
	create random snack cubes:
	we must be sure we dont put a snack on top of the snake
	"""
	#global rows
	positions = item.body

	while True:
		x = random.randrange(rows)
		y = random.randrange(rows)
		#we get a list of filtered list and check if and of the positions
		#are the current positions of the snake
		#if snack position is equal to the *random(x,y) than repeat the loop
		if len(list(filter(lambda z:z.pos ==(x,y), positions))) > 0:
			continue
		else:
			break
	return (x,y) #return snack position that is not on the snake
#-----------------------------------------------------------------------------------
def message_box(subject,content):
	"""
	universal message box created from tkinter
	"""
	root = tk.Tk()
	root.attributes("-topmost",True)
	root.withdraw()
	messagebox.showinfo(subject,content)
	try:
		root.destroy()
	except:
		pass

#-----------------------------------------------------------------------------------
def key_events():
	pass

#directions = {"right":(1,0), "left":(0,-1), "up":(0,-1), "down":(0,1)}
#-----------------------------------------------------------------------------------
def main():
	global width, rows, s, snack
	#---------------game initialization---------------------------
	#create game display
	width = 500
	rows = 20
	win = pygame.display.set_mode((width, width)) #square display
	#snake start position
	s = snake(color=RED, pos=(10,10))
	snack = cube(randomSnack(rows,s), color = GREEN)
	print(snack.pos)
	clock = pygame.time.Clock()
	flag = True
	FPScount = 0
	print(FPScount)
	redrawWindow(win)
	#-----------------------continuous game loop-------------
	while flag:
		#pygame.time.delay(50)
		clock.tick(1)	#game max speed 10 FPS
		s.move()
		#check if the snack was eaten. if it was
		if s.body[0].pos == snack.pos:
			s.addCube() #add new cube to snake
			snack = cube(randomSnack(rows,s), color = GREEN) #generate new snack cube
		#check for chrash
		#is the position that we moved to in list of every snake body cube
		for x in range(len(s.body)):
			if s.body[x].pos in list(map(lambda z:z.pos,s.body[x+1:])):
				print("score: ", len(s.body))
				message_box("game over","play again")
				s.reset((10,10))
				break
		#------------debug fps counter---------
		FPScount += 1
		print(f'FPScount:{FPScount}')
		#--------------------------------------
		redrawWindow(win)
#rows = 0
#w = 0
#h = 0

#cube.rows = rows
#cube.w = w
main()
pygame.quit()
sys.exit()<file_sep>import os
from os import path

HIGHSCORE_FILE = "highscore.txt"

folder = path.dirname(__file__) #get application folder path

filename = path.join(folder, HIGHSCORE_FILE)
print(filename)

#if file exists, read from it
if os.path.exists(filename):
	with open(filename, 'r') as f:
		try:
			print("file opened")
			highscore = int(f.read())
			print(highscore)
		except:
			print("file read error")
# if file doesnt exists, create newread from it
else:
	with open(filename, 'w') as f:
		try:
			f.write("0")
		except:
			pass
<file_sep>from math import log, ceil
def next_power_of_2(size):
    return 2 ** ceil(log(size, 2))
<file_sep>from gameobjects.vector3 import *

A = (-6, 2, 2) 
B = (7, 5, 10)
plasma_speed = 100 # meters per second

AB = Vector3.from_points(A, B)
print("Vector to droid is", AB)

distance_to_target = AB.get_magnitude()
print("Distance to droid is", distance_to_target, "meters")

plasma_heading = AB.get_normalized()
print("Heading is", plasma_heading)
<file_sep># -*- coding: utf-8 -*-
"""
There are six steps to making text appear on the screen:

1. Create a pygame.font.Font object.

2. Create a Surface object with the text drawn on it by calling the Font object’s render() method.

3. Create a Rect object from the Surface object by calling the Surface object’s get_rect() method.
 This Rect object will have the width and height correctly set for the text that was rendered,
 but the top and left attributes will be 0.

4. Set the position of the Rect object by changing one of its attributes.
 On line 15, we set the center of the Rect object to be at 200, 150.

5. Blit the Surface object with the text onto
 the Surface object returned by pygame.display.set_mode().

6. Call pygame.display.update() to make the display Surface appear on the screen.
"""

import pygame, sys
from pygame.locals import *

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')

FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()

WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0, 0, 128)

fontObj = pygame.font.Font('freesansbold.ttf', 32)
textSurfaceObj = fontObj.render('Hello world!', True, GREEN, BLUE)
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (200, 150)

while True: # main game loop
    DISPLAYSURF.fill(WHITE)
    DISPLAYSURF.blit(textSurfaceObj, textRectObj)

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()

    # must be called after display.update
    fpsClock.tick(FPS)<file_sep> 
# Steering Behavior Examples
# Seek & Approach
# KidsCanCode 2016
# Video lesson: https://youtu.be/g1jo_qsO5c4

import pygame as pg
from random import randint, uniform
from sys import exit

vec = pg.math.Vector2

WIDTH = 800
HEIGHT = 600
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
DARKGRAY = (40, 40, 40)

# Mob properties
MOB_SIZE = 32
MAX_SPEED = 5
MAX_FORCE = 0.1
APPROACH_RADIUS = 120

class Mob(pg.sprite.Sprite):
    def __init__(self):
        self.groups = all_sprites
        pg.sprite.Sprite.__init__(self, self.groups)
        self.image = pg.Surface((MOB_SIZE, MOB_SIZE))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.pos = vec(randint(0, WIDTH), randint(0, HEIGHT))
        self.vel = vec(MAX_SPEED, 0).rotate(uniform(0, 360))
        self.acc = vec(0, 0)
        self.rect.center = self.pos

    def follow_mouse(self):
        mpos = pg.mouse.get_pos()
        self.acc = (mpos - self.pos).normalize() * 0.5 #original

    def seek(self, target):
        self.desired = (target - self.pos).normalize() * MAX_SPEED
        steer = (self.desired - self.vel)
        if steer.length() > MAX_FORCE:
            steer.scale_to_length(MAX_FORCE)
        return steer

    def seek_with_approach(self, target):
        self.desired = (target - self.pos)
        dist = self.desired.length()
        self.desired.normalize_ip()
        if dist < APPROACH_RADIUS:
            self.desired *= dist / APPROACH_RADIUS * MAX_SPEED
        else:
            self.desired *= MAX_SPEED
        steer = (self.desired - self.vel)
        if steer.length() > MAX_FORCE:
            steer.scale_to_length(MAX_FORCE)
        return steer

    def update(self):
        # self.follow_mouse()
        self.acc = self.seek_with_approach(pg.mouse.get_pos())
        #self.acc = self.seek(pg.mouse.get_pos())
        # equations of motion
        self.vel += self.acc
        if self.vel.length() > MAX_SPEED:
            self.vel.scale_to_length(MAX_SPEED)
        self.pos += self.vel
        if self.pos.x > WIDTH:
            self.pos.x = 0
        if self.pos.x < 0:
            self.pos.x = WIDTH
        if self.pos.y > HEIGHT:
            self.pos.y = 0
        if self.pos.y < 0:
            self.pos.y = HEIGHT
        self.rect.center = self.pos

    def draw_vectors(self):
        scale = 25
        # vel
        pg.draw.line(screen, GREEN, self.pos, (self.pos + self.vel * scale), 5)
        # desired
        pg.draw.line(screen, RED, self.pos, (self.pos + self.desired * scale), 5)
        # approach radius
        pg.draw.circle(screen, WHITE, pg.mouse.get_pos(), APPROACH_RADIUS, 1)

pg.init()
screen = pg.display.set_mode((WIDTH, HEIGHT))
clock = pg.time.Clock()

all_sprites = pg.sprite.Group()

Mob()

paused = False
show_vectors = False
running = True
while running:
    clock.tick(FPS)
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                running = False
            if event.key == pg.K_SPACE:
                paused = not paused
            if event.key == pg.K_v:
                show_vectors = not show_vectors
            if event.key == pg.K_m:
                Mob()

    if not paused:
        all_sprites.update()
    pg.display.set_caption("{:.2f}".format(clock.get_fps()))
    screen.fill(DARKGRAY)
    all_sprites.draw(screen)
    if show_vectors:
        for sprite in all_sprites:
            sprite.draw_vectors()
    pg.display.flip()

pg.quit()
exit()<file_sep>function love.conf(tbl)
  tbl.window.width = 900
  tbl.window.height = 900
  tbl.window.title = 'My Snake game'
  tbl.window.console = true
end
<file_sep>import pygame

pygame.init()

#---------display-------------
display_width = 800
display_height = 600
#color var
black = (0,0,0)
white = (255,255,255)
red   = (255,0,0)
green = (0,255,0)
blue  = (0,0,255)

gameDisplay = pygame.display.set_mode((display_width,display_height))
#set title
pygame.display.set_caption('Race Game')

clock = pygame.time.Clock()

# load image
carImg = pygame.image.load('race_car_transp_v2.png')
#get image size in pixels. for colision detection
carImg_width = carImg.get_rect().size[0]
carImg_height = carImg.get_rect().size[1]

#function to display a car
def car(x,y):
	gameDisplay.blit(carImg,(x,y)) #we blit car image to a surface

def game_loop():
	x = display_width*0.45
	y = display_height*0.8
	#for computers (x=0,y=0) is top left corner

	#------------main game loop---------
	x_change = 0
	
	gameExit = False
	
	while not gameExit:

		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				gameExit = True

				#if key pressed start moving
			if event.type == pygame.KEYDOWN:
			    if event.key == pygame.K_LEFT:
			    	x_change = -5
			    elif event.key == pygame.K_RIGHT:
			    	x_change = 5

				#if key released stop moving
			if event.type == pygame.KEYUP:
			    if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
			    	x_change = 0

		x += x_change

		#------------------------------------
		gameDisplay.fill(white)	#draw background
		car(x,y)				#draw car

		#check boundaries for chrash
		if x > display_width - carImg_width or x < 0:
			gameExit = True

		pygame.display.update() #update all changes to display
		clock.tick(60)	
#------------------------------------
game_loop()		#game is running here, until pygame.QUIT
pygame.quit()	
quit()<file_sep>def parallel_project(vector3):
    return (vector3.x, vector3.y)
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 16:29:01 2020

@author: crtom

https://www.youtube.com/watch?v=Qdeb1iinNtk&list=PLX5fBCkxJmm1fPSqgn9gyR3qih8yYLvMj&index=2

Pygame Tutorial - Making a Platformer ep. 2: Images, Input, and Collisions
"""

import sys
import pygame
from pygame.locals import*
import random
#from settings import *
import time
import math

from gameobjects.vector2 import Vector2
from RGB import *

WIDTH, HEIGHT = 400, 400

# initialize pygame and create a window
pygame.init()
pygame.mixer.init()

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Platformer")


#all_sprites = pygame.sprite.Group()

# create background
background = pygame.Surface((WIDTH, HEIGHT))
background.fill(WHITE)
screen.blit(background, (0,0))

# create player image
player_image = pygame.Surface((50, 50))
player_image.fill(BLACK)

player_pos = Vector2(200, 150)
player_speed = 300

screen.blit(player_image, (player_pos.x, player_pos.y))

# game loop
clock = pygame.time.Clock()
running = True
while running:

    # process input (events)
    for event in pygame.event.get(): #check for all events that are happening
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            running = False
    
    pressed_keys = pygame.key.get_pressed()
    key_direction = Vector2(0, 0)
    
    if pressed_keys[K_LEFT]:
        key_direction.x = -1
    elif pressed_keys[K_RIGHT]:
         key_direction.x = +1
    if pressed_keys[K_UP]:
        key_direction.y = -1
    elif pressed_keys[K_DOWN]:
        key_direction.y = +1
    
    
    key_direction.normalize()
    
    time_passed = clock.tick()
    time_passed_seconds = time_passed / 1000.0
    #----------
    player_pos += key_direction * player_speed * time_passed_seconds
        
    # draw/render
    screen.blit(background, (0,0))
    #all_sprites.draw(screen)
    # screen.blit(player_image, (50, 50))

    screen.blit(player_image, (player_pos.x, player_pos.y))
    # after drawing everything, flip the display
    pygame.display.update()

pygame.quit()
<file_sep>class State(object):

  def __init__(self, name):
      self.name = name

  def do_actions(self):
      pass

  def check_conditions(self):
      pass

  def entry_actions(self):
      pass

  def exit_actions(self):
      pass
<file_sep>from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
from pygame.locals import *

screen = pygame.display.set_mode((640, 480), HWSURFACE|DOUBLEBUF|OPENGL)

def resize(width, height):
    glViewport(0, 0, width, height) 
    glMatrixMode(GL_PROJECTION) 
    glLoadIdentity()
    gluPerspective(60, float(width)/height, 1, 10000)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()


<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Mar 20 15:37:57 2020

@author: crtjur
"""
"""
import turtle

tim = turtle.Turtle() # create turtle module object
tim.color('red') #
tim.pensize(5) #thickness of line
tim.shape('turtle')

"""

#==============================================================================
# Turtle adjustments
#==============================================================================
# This is needed to prevent turtle scripts crashes after multiple runs in the
# same IPython Console instance.
# See Spyder issue #6278
try:
    import turtle
    from turtle import Screen, Terminator

    def spyder_bye():
        try:
            Screen().bye()
            turtle.TurtleScreen._RUNNING = True
        except Terminator:
            pass
    turtle.bye = spyder_bye
except:
    pass
<file_sep>"""
Basic Movement and Key Presses
video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5

1. create a rectangle
2. move it by key pressed
"""

import pygame
from pygame.locals import *

pygame.init()

#create window
win = pygame.display.set_mode((500,500))
#set windows title
pygame.display.set_caption("First Game")

#character variables
x = 50
y = 50
width = 40
height = 60
vel = 5


#clock=pygame.time.Clock()
#main game loop
run = True
while run:

	pygame.time.delay(100) #this will be a clock for the game

	for event in pygame.event.get(): #check for all events that are happening
		if event.type == pygame.QUIT:
			run = False
		if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
			run = False

	vx = 0
	vy = 0
	keystate = pygame.key.get_pressed()
	#straight moves
	if keystate[pygame.K_UP]:
		vy = -5
	elif keystate[pygame.K_DOWN]:
		vy = 5
	elif keystate[pygame.K_LEFT]:
		vx = -5
	elif keystate[pygame.K_RIGHT]:
		vx = 5

	x += vx
	y += vy

	#draw rectangle
	win.fill((0,0,0))
	pygame.draw.rect(win,(255,0,0),(x,y,width,height))
	pygame.display.update()
<file_sep># Pygame Tutorials

Building a simple game: character can move, jump, shoot, has health,...
Object oriented.

## Resources
- Channel: Tech With Tim
- [Youtube playlist](https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5)
- [github](https://github.com/techwithtim/Pygame-Tutorials)

## Files
- Pygame Tutorial #1 - Basic Movement and Key Presses
[code](1.py)
- Pygame Tutorial #2 - Jumping and Boundaries
[code](2.py)
- Pygame Tutorial #3 - Character Animation & Sprites
[code](3.py)
- Pygame Tutorial #4 - Optimization & OOP
[code](4.py)
- Pygame Tutorial #5 - Basic Movement and Key Presses
[code](5.py)
- Pygame Tutorial #6 - Enemies
[code](6.py)
- Pygame Tutorial #7 - Collision and hit boxes
[code](7.py)
- Pygame Tutorial #8 - Scoring and health bars
[code](8.py)
- Pygame Tutorial #9 - Sound effects, music, collision
[code](9.py)
- Pygame Tutorial #10 - Finishing touches & next steps
[code](10.py)<file_sep>from enum import Enum, auto
import time


class States(Enum):
    IDLE = auto()
    CHASE = auto()
    ATTACK = auto()
    DEATH = auto()


class GameObject:
    def __init__(self):
        self.__state = States.IDLE

    def set_state(self, state):
        self.__state = state

    def get_state(self):
        return self.__state


class Entity(GameObject):
    def __init__(self):
        super().__init__()
        self.__health = 100

    def sub_health(self):
        self.__health -= 20

    def get_health(self):
        return self.__health

    def set_health(self, health):
        self.__health = health

player = Entity()
player.set_state(States.ATTACK)

enemy = Entity()
enemy.set_health(200)
enemy.set_state(States.CHASE)

while True:
    if player.get_state() == States.ATTACK:
        print("player attacking!")
        enemy.sub_health()
        if enemy.get_state() != States.ATTACK:
            enemy.set_state(States.ATTACK)
        if enemy.get_health() <= 0:
            enemy.set_state(States.DEATH)
            print("enemy died")
            print("proceed to next level")
            break
    elif player.get_state() == States.DEATH:
        print("player died")
        break
    if enemy.get_state() == States.ATTACK:
        print("enemy attacking!")
        player.sub_health()
        if player.get_health() <= 0:
            player.set_state(States.DEATH)
            print("player died")
            print("game over!")
            break

    time.sleep(1)

print("-----------------------------")
print("player's health ", player.get_health())
print("enemy's health", enemy.get_health())
<file_sep>import sys
import math
import random
import pygame
from pygame.locals import *
import tkinter as tk
from tkinter import messagebox

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)

def drawGrid(w, rows, surface):
    """
    This function draws a square grid on main display
    """
    # distance between grid lines
    sizeBtwn = w // rows
    x = 0
    y = 0

    # create grid by drawing lines
    for l in range(rows):
        x = x + sizeBtwn
        y = y + sizeBtwn

    # vertical lines
    pygame.draw.line(surface, WHITE, (x, 0), (x, w))
    # horizontal lines
    pygame.draw.line(surface, WHITE, (0, y), (w, y))

def redrawWindow(surface):
	global rows, width
	#background
	surface.fill(BLACK)
	#draw grid
	drawGrid(width, rows, surface)
	#update display
	pygame.display.update()

#---------------------------------------------------------------------------------------
def key_events():
	for event in pygame.event.get():
			if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
				#pygame.quit()
				#sys.exit()
				return True

	keys = pygame.key.get_pressed()
	for key in keys:
		if keys[pygame.K_UP]:
			self.dirnx = 0
			self.dirny = -1
			self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
		elif keys[pygame.K_DOWN]:
			self.dirnx = 0
			self.dirny = 1
			self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

	return False
#---------------------------------------------------------------------------------------
def main():
	global width, rows, s, snack
	#---------------game initialization---------------------------
	#create game display
	width = 500
	rows = 20
	win = pygame.display.set_mode((width, width)) #square display

	clock = pygame.time.Clock()

	FPScount = 0
	#-----------------------continuous game loop-------------
	GameOver = False
	while not GameOver:
		#pygame.time.delay(50)
		clock.tick(10)	#game max speed 10 FPS
		GameOver = key_events()


		print(FPScount)

		redrawWindow(win)
#---------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------
main()
pygame.quit()
sys.exit()<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Dec 20 15:27:13 2020

@author: crtom
"""
import pygame

WHITE   = (255, 255, 255)
BLACK   = (  0,   0,   0)
GREY    = (128, 128, 128)
SILVER  = (192, 192, 192)

RED     = (255,   0,   0)
YELLOW  = (255, 255,   0)
ORANGE  = (255, 128,   0)
MAGENTA = (255,   0, 255)
PURPLE  = (128,   0, 128)

LIME    = (  0, 255,   0)
BLUE    = (  0,   0, 255)
NAVYBLUE= ( 60,  60, 100)
CYAN    = (  0, 255, 255)
GRAY	= (128, 128, 128)
MAROON  = (128,   0,   0)
OLIVE   = (128, 128,   0)
GREEN   = (  0, 128,   0)
TEAL    = (  0, 128, 128)
NAVY    = (  0,   0, 128)


def draw_rect_alpha(surface, color, rect):
    shape_surf = pygame.Surface(pygame.Rect(rect).size, pygame.SRCALPHA)
    pygame.draw.rect(shape_surf, color, shape_surf.get_rect())
    surface.blit(shape_surf, rect)

def draw_circle_alpha(surface, color, center, radius):
    target_rect = pygame.Rect(center, (0, 0)).inflate((radius * 2, radius * 2))
    shape_surf = pygame.Surface(target_rect.size, pygame.SRCALPHA)
    pygame.draw.circle(shape_surf, color, (radius, radius), radius)
    surface.blit(shape_surf, target_rect)

def draw_polygon_alpha(surface, color, points):
    lx, ly = zip(*points)
    min_x, min_y, max_x, max_y = min(lx), min(ly), max(lx), max(ly)
    target_rect = pygame.Rect(min_x, min_y, max_x - min_x, max_y - min_y)
    shape_surf = pygame.Surface(target_rect.size, pygame.SRCALPHA)
    pygame.draw.polygon(shape_surf, color, [(x - min_x, y - min_y) for x, y in points])
    surface.blit(shape_surf, target_rect)

def draw_background():
    background = pygame.Surface(window.get_size())
    ts, w, h, c1, c2 = 50, *window.get_size(), (160, 160, 160), (192, 192, 192)
    tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]

    for rect, color in tiles:
        pygame.draw.rect(background, color, rect)

    window.blit(background, (0, 0))

pygame.init()
window = pygame.display.set_mode((250, 250))
clock = pygame.time.Clock()

#--------------------------------------------
#------------background----------------------
#--------------------------------------------
background = pygame.Surface((250, 250))
background.fill((128,128,128))
window.blit(background, (0, 0))
#print(window.get_size())

#--------------------------------------------
#-------------line icon-------------
#--------------------------------------------
# icon1 = pygame.Surface((50, 50))
# icon1.fill((255,255,255))
# #pygame.draw.line(surface, color, start_pos, end_pos, width) -> Rect
# # draw horizontal line in icon surface
# pygame.draw.line(icon1, BLUE, (5,25), (45,25), 5)
# # draw vertical line in icon surface
# pygame.draw.line(icon1, BLUE, (25,5), (25,45), 5)
# #blit icon on main surface
# window.blit(icon1, (0, 0))

#--------------------------------------------
#----------------triangle icon----------------
#--------------------------------------------
icon3 = pygame.Surface((50, 50))
icon3.fill((255,255,255))
#line(surface, color, start_pos, end_pos, width) -> Rect
# draw horizontal line in icon surface
#Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect
pygame.draw.polygon(icon3, GREEN, ((10,40),(40,40),(25, 10)),4)
#blit icon on main surface
window.blit(icon3, (0, 0))

#--------------------------------------------
#----------------rectangle empty icon----------------
#--------------------------------------------
#Demo 1: Rectangle
#pygame.draw.rect(surface, color, pygame.Rect(left, top, width, height))

icon2 = pygame.Surface((50, 50))
icon2.fill((255,255,255))
#line(surface, color, start_pos, end_pos, width) -> Rect
# draw horizontal line in icon surface
#Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect
pygame.draw.rect(icon2, RED, [10,10,30,30],5)
#blit icon on main surface
window.blit(icon2, (60, 0))

#--------------------------------------------
#----------------circle empty icon-----------------
#--------------------------------------------
icon3 = pygame.Surface((50, 50))
icon3.fill((255,255,255))
#line(surface, color, start_pos, end_pos, width) -> Rect
# draw horizontal line in icon surface
#Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect
pygame.draw.circle(icon3, GREEN, (25, 25 ), 15, 5)
#blit icon on main surface
window.blit(icon3, (120, 0))

#--------------------------------------------
#----------------triangle icon----------------
#--------------------------------------------
icon3 = pygame.Surface((50, 50))
icon3.fill((255,255,255))
#line(surface, color, start_pos, end_pos, width) -> Rect
# draw horizontal line in icon surface
#Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect
pygame.draw.polygon(icon3, GREEN, ((10,40),(40,40),(25, 10)))
#blit icon on main surface
window.blit(icon3, (0, 60))

# #--------------------------------------------
# #----------------diamond icon----------------
# #--------------------------------------------
# icon4 = pygame.Surface((50, 50))
# icon4.fill((255,255,255))
# #line(surface, color, start_pos, end_pos, width) -> Rect
# # draw horizontal line in icon surface
# #Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect
# pygame.draw.polygon(icon4, GREEN, ((5,25),(25,5),(45, 25),(25, 45)))
# #blit icon on main surface
# window.blit(icon4, (0, 60))

#--------------------------------------------
#----------------rectangle filled icon----------------
#--------------------------------------------
#Demo 1: Rectangle
#pygame.draw.rect(surface, color, pygame.Rect(left, top, width, height))

icon5 = pygame.Surface((50, 50))
icon5.fill((255,255,255))
#line(surface, color, start_pos, end_pos, width) -> Rect
# draw horizontal line in icon surface
#Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect
pygame.draw.rect(icon5, RED, [10,10,30,30])
#blit icon on main surface
window.blit(icon5, (60, 60))

#--------------------------------------------
#----------------circle filled icon-----------------
#--------------------------------------------
icon6 = pygame.Surface((50, 50))
icon6.fill((255,255,255))
#line(surface, color, start_pos, end_pos, width) -> Rect
# draw horizontal line in icon surface
#Rect(left, top, width, height) -> Rect, Rect((left, top), (width, height)) -> Rect
pygame.draw.circle(icon6, GREEN, (25, 25 ), 15)
#blit icon on main surface
window.blit(icon6, (120, 60))

#--------------------------------------------
run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False


#    draw_background()
#    draw_rect_alpha(window, (0, 0, 255, 127), (55, 90, 140, 140))
#    draw_circle_alpha(window, (255, 0, 0, 127), (150, 100), 80)
#    draw_polygon_alpha(window, (255, 255, 0, 127),
#        [(100, 10), (100 + 0.8660 * 90, 145), (100 - 0.8660 * 90, 145)])

    pygame.display.flip()

pygame.quit()
exit()<file_sep>from math import radians

from OpenGL.GL import *
from OpenGL.GLU import *

import pygame
from pygame.locals import *

# Import the Model3D class
import model3d

SCREEN_SIZE = (800, 600)

def resize(width, height):

    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(60.0, float(width)/height, .1, 1000.)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()


def init():
    glEnable(GL_FOG)
    glFogfv(GL_FOG_COLOR, (1.0, 1.0, 1.0))
    glFogi(GL_FOG_MODE, GL_LINEAR)
    glFogf(GL_FOG_START, 1.5)
    glFogf(GL_FOG_END, 3.5)

    # Enable the GL features we will be using
    glEnable(GL_DEPTH_TEST)
    glEnable(GL_LIGHTING)
    glEnable(GL_COLOR_MATERIAL)
    glEnable(GL_TEXTURE_2D)
    glEnable(GL_CULL_FACE)

    glShadeModel(GL_SMOOTH)
    glClearColor(1.0, 1.0, 1.0, 0.0) # white

    # Set the material
    glMaterial(GL_FRONT, GL_AMBIENT, (0.0, 0.0, 0.0, 1.0))
    glMaterial(GL_FRONT, GL_DIFFUSE, (0.2, 0.2, 0.2, 1.0))
    glMaterial(GL_FRONT, GL_SPECULAR, (1.0, 1.0, 1.0, 1.0))
    glMaterial(GL_FRONT, GL_SHININESS, 10.0)

    # Set light parameters
    glLight(GL_LIGHT0, GL_AMBIENT, (0.0, 0.0, 0.0, 1.0))
    glLight(GL_LIGHT0, GL_DIFFUSE, (0.4, 0.4, 0.4, 1.0))
    glLight(GL_LIGHT0, GL_SPECULAR, (1.0, 1.0, 1.0, 1.0))

    # Enable light 1 and set position
    glEnable(GL_LIGHT0)
    glLight(GL_LIGHT0, GL_POSITION,  (0, .5, 1, 0))


def run():

    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|OPENGL|DOUBLEBUF)

    resize(*SCREEN_SIZE)
    init()

    clock = pygame.time.Clock()

    # Read the model
    tank_model = model3d.Model3D()
    tank_model.read_obj('mytank.obj')

    rotation = 0.0

    while True:

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                quit()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        time_passed = clock.tick()
        time_passed_seconds = time_passed / 1000.0

        glLoadIdentity()
        glRotatef(15, 1, 0, 0)
        glTranslatef(0.0, -1.5, -3.5)

        rotation += time_passed_seconds * 45.0
        glRotatef(rotation, 0, 1, 0)

        tank_model.draw_quick()

        pygame.display.flip()
            

if __name__ == "__main__":
    run()
<file_sep># Create a display list 
tank_display_list = glGenLists(1) 
glNewList(tank_display_list, GL_COMPILE)

draw_tank()

# End the display list 
glEndList()
<file_sep>import pygame
from pygame.locals import *
from random import randint 

class Star(object):

    def __init__(self, x, y, speed):

        self.x = x 
        self.y = y 
        self.speed = speed

def run():

    pygame.init()
    screen = pygame.display.set_mode((640, 480), FULLSCREEN)

    stars = []

    # Add a few stars for the first frame 
    for n in range(200):

        x = float(randint(0, 639))
        y = float(randint(0, 479))
        speed = float(randint(10, 300))
        stars.append( Star(x, y, speed) )

    clock = pygame.time.Clock() 

    white = (255, 255, 255) 

    while True:

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                quit()
            if event.type == KEYDOWN:
                pygame.quit()
                quit()

        # Add a new star
        y = float(randint(0, 479))
        speed = float(randint(10, 300)) 
        star = Star(640, y, speed)

        stars.append(star)
        time_passed = clock.tick()
        time_passed_seconds = time_passed / 1000. 

        screen.fill((0, 0, 0))

        # Draw the stars 
        for star in stars:

            new_x = star.x - time_passed_seconds * star.speed 
            pygame.draw.aaline(screen, white, (new_x, star.y), (star.x+1., star.y)) 
            star.x = new_x

        def on_screen(star):
            return star.x > 0

        # Remove stars that are no longer visible 
        stars = list(filter(on_screen, stars))

        pygame.display.update()


if __name__ == "__main__":
    run()
<file_sep>def subtractive_blend(src, dst):
    return dst—src * src.a
<file_sep>"""
Simple pong in python 3 for begginers

tutorial series: https://www.youtube.com/playlist?list=PLlEgNdBJEO-kXk2PyBxhSmo84hsO3HAz2
"""

import turtle
import time
import random

wn = turtle.Screen()
wn.title("Pong by @TokyoEdTech")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)

score_a = 0
score_b = 0

# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed() #sets the speed of animation to max
paddle_a.shape("square") #default is 20x20 pixels
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5, stretch_len = 1) # strech the square
paddle_a.penup()
paddle_a.goto(-350,0)

# Paddle B
paddle_b = turtle.Turtle()
paddle_b.speed() #sets the speed of animation to max
paddle_b.shape("square") #default is 20x20 pixels
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5, stretch_len = 1) # strech the square
paddle_b.penup()
paddle_b.goto(350,0)

# Ball
ball = turtle.Turtle()
ball.speed() #sets the speed of animation to max
ball.shape("square") #default is 20x20 pixels
ball.color("white")
ball.penup()
ball.goto(0,0)

ball.dx = 2 #speed
ball.dy = 2

print(random.choice([-1,1]))

#write scoreboard
pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0,260)
pen.write("Player A:  0  Player B:  0", align="center", font=("courier",24,"normal"))

# Functions
def paddle_a_up():
	y = paddle_a.ycor() #method, returns y coor
	y+= 20 #add 20 pixels to y coor
	paddle_a.sety(y)

def paddle_a_down():
	y = paddle_a.ycor() #method, returns y coor
	y -= 20 #add 20 pixels to y coor
	paddle_a.sety(y)

def paddle_b_up():
	y = paddle_b.ycor() #method, returns y coor
	y+= 20 #add 20 pixels to y coor
	paddle_b.sety(y)

def paddle_b_down():
	y = paddle_b.ycor() #method, returns y coor
	y -= 20 #add 20 pixels to y coor
	paddle_b.sety(y)

#keyboard biding
wn.listen() #listen for key inputs
wn.onkey(paddle_a_up,"w") #when user press "w" call function paddle_a_up
wn.onkey(paddle_a_down,"s") #when user press "w" call function paddle_a_up
wn.onkey(paddle_b_up,"Up") #when user press "w" call function paddle_a_up
wn.onkey(paddle_b_down,"Down") #when user press "w" call function paddle_a_up


# main game loop
GameOver = False
while not GameOver:
	wn.update() #updates screen
	time.sleep(0.01)

	#move the ball
	ball.setx(ball.xcor() + ball.dx)
	ball.sety(ball.ycor() + ball.dy)

	#border checking
	#----------top sides bounce--------
	#top side
	if ball.ycor() > 290:
		ball.sety(290)
		ball.dy *= -1 #reverse direction of the ball
	#bottom side
	elif ball.ycor() < -285:
		ball.sety(-285)
		ball.dy *= -1 #reverse direction of the ball

	#----------bot sides finish the game--------
	#right side
	if ball.xcor() > 390:
		ball.goto(0,0) #put ball back to the start
		ball.dx *= -1 #reverse direction of the ball
		score_a += 1
		pen.clear()
		pen.write(f"Player A:  {score_a}  Player B:  {score_b}", align="center", font=("courier",24,"normal"))


	#left side
	elif ball.xcor() < -390:
		ball.goto(0,0) #put ball back to the start
		ball.dx *= -1 #reverse direction of the ball
		score_b += 1
		pen.clear()
		pen.write(f"Player A:  {score_a}  Player B:  {score_b}", align="center", font=("courier",24,"normal"))

	#Paddle and ball collisions
	#if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor()+50 and ball.ycor()>paddle_b.ycor()-50)
	paddle_b_y_coll = ((ball.ycor() < paddle_b.ycor()+50) and(ball.ycor()>paddle_b.ycor()-50))
	paddle_a_y_coll = ((ball.ycor() < paddle_a.ycor()+50) and(ball.ycor()>paddle_a.ycor()-50))
	right_coll = ((ball.xcor() > 340) and (ball.xcor() < 350))
	left_coll = ((ball.xcor() < -340) and (ball.xcor() > -350))

	if paddle_b_y_coll and right_coll:
		ball.setx(340)
		ball.dx *= -1 #reverse direction of the ball

	if paddle_a_y_coll and left_coll:
		ball.setx(-340)
		ball.dx *= -1 #reverse direction of the ball

	#debug
	#print (f'ball.xcor():{ball.xcor()}')
	#print (f'ball.ycor():{ball.ycor()}')
	#print (f'paddle_b.ycor():{paddle_b.ycor()}')

	#diff = ball.ycor() - paddle_b.ycor()
	#print (f'diff:{diff}')
<file_sep>import math

class Vector2:
    
    def __init__(self, x=0, y=0):        
        self.x = x
        self.y = y
        
    def __str__(self):
        return "(%s, %s)"%(self.x, self.y)
        
    def from_points(P1, P2):        
        return Vector2( P2[0] - P1[0], P2[1] - P1[1] )
    
    def get_magnitude(self):
        return math.sqrt( self.x**2 + self.y**2 )


    
A = (10.0, 20.0) 
B = (30.0, 35.0)
AB = Vector2.from_points(A, B)
print(AB)
print(AB.get_magnitude())
<file_sep>"""
Basic Movement and Key Presses
video: https://www.youtube.com/watch?v=i6xMBig-pP4&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5

1. create a rectangle
2. move it by key pressed
"""

import pygame
from pygame.locals import *
from sys import exit
from gameobjects.vector2 import Vector2

# unit vectors for movement
vector_right = Vector2(1,  0)
vector_left  = Vector2(-1, 0)
vector_up    = Vector2(0, -1)
vector_down  = Vector2(0,  1)

pygame.init()

WIDTH, HEIGHT = 640, 480
#### Create a canvas on which to display everything ####
screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
#set windows title
pygame.display.set_caption("8 way movement vector")

#### Create a surface with the same size as the window ####
background = pygame.Surface((WIDTH, HEIGHT))

#character variables
x = 50
y = 50
width = 40
height = 60
vel = 5

sprite = pygame.Surface((50, 50))
sprite.fill((255,255,255))
rect = sprite.get_rect()
rect.center = (WIDTH / 2, HEIGHT / 2)

clock = pygame.time.Clock()
sprite_pos = Vector2(100.0, 100.0)
sprite_speed = 300.

clock = pygame.time.Clock()

key_direction = Vector2(0, 0)
    
#main game loop
run = True
while run:
    # pygame.time.delay(100) #this will be a clock for the game
    for event in pygame.event.get(): #check for all events that are happening
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            run = False
    	
    key_direction.x, key_direction.y = (0, 0)
    keystate = pygame.key.get_pressed()

    if keystate[pygame.K_UP]:
        # key_direction = vector_up
        key_direction += vector_up
    
    if keystate[pygame.K_DOWN]:
        key_direction += vector_down
    
    if keystate[pygame.K_LEFT]:
        key_direction += vector_left
    
    if keystate[pygame.K_RIGHT]:
         key_direction += vector_right
    
    # direction vector is a unit vector, normalize it
    # diagonals are 0.707
    key_direction.normalize()
    print(key_direction)
    
    time_passed = clock.tick(30)
    time_passed_seconds = time_passed / 1000.0
    
    sprite_pos += key_direction * sprite_speed * time_passed_seconds
    #### Blit the surface onto the canvas ####
    screen.blit(background,(0,0))
    
    #### Blit the surface onto the canvas ####
    screen.blit(sprite,(int(sprite_pos.x), int(sprite_pos.y))) 
    
    
    pygame.display.update()

# exit pygame
pygame.quit()
exit()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Mar 18 21:57:53 2020

@author: crtjur
"""

"""
$ python
Python 2.7.13 (default, Apr  4 2017, 08:47:57)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> from simple_device import SimpleDevice
>>> device = SimpleDevice()
Processing current state: LockedState
>>> 
>>> device.on_event('device_locked')
>>> device.on_event('pin_entered')
Processing current state: UnlockedState
>>> 
>>> device.state
UnlockedState
>>> 
>>> device.on_event('device_locked')
Processing current state: LockedState
>>> 
>>> device.state
LockedState
>>> device.on_event('device_locked')
"""<file_sep>
from OpenGL.GL import *
from OpenGL.GLU import *

import pygame
import os.path

class Material(object):

    def __init__(self):

        self.name = ""
        self.texture_fname = None
        self.texture_id = None


class FaceGroup(object):

    def __init__(self):

        self.tri_indices = []
        self.material_name = ""


class Model3D(object):

    def __init__(self):
        
        self.vertices = []
        self.tex_coords = []
        self.normals = []
        self.materials = {}
        self.face_groups = []
        self.display_list_id = None

    def __del__(self):

        #Called when the model is cleaned up by Python
        self.free_resources()

    def free_resources(self):

        # Delete the display list and textures
        if self.display_list_id is not None:
            glDeleteLists(self.display_list_id, 1)            
            self.display_list_id = None

        # Delete any textures we used
        for material in self.materials.values():
            if material.texture_id is not None:                
                glDeleteTextures(material.texture_id)
                
        # Clear all the materials
        self.materials.clear()        
        
        # Clear the geometry lists
        del self.vertices[:]
        del self.tex_coords[:]
        del self.normals[:]        
        del self.face_groups[:]        
        


    def read_obj(self, fname):

        current_face_group = None

        file_in = open(fname)

        for line in file_in:

            # Parse command and data from each line
            words = line.split()
            command = words[0]
            data = words[1:]

            if command == 'mtllib': # Material library

                model_path = os.path.split(fname)[0]
                mtllib_path = os.path.join( model_path, data[0] )                                
                self.read_mtllib(mtllib_path)
                
            elif command == 'v': # Vertex
                x, y, z = data
                vertex = (float(x), float(y), float(z))
                self.vertices.append(vertex)

            elif command == 'vt': # Texture coordinate

                s, t = data
                tex_coord = (float(s), float(t))
                self.tex_coords.append(tex_coord)

            elif command == 'vn': # Normal

                x, y, z = data
                normal = (float(x), float(y), float(z))
                self.normals.append(normal)

            elif command == 'usemtl' : # Use material

                current_face_group = FaceGroup()
                current_face_group.material_name = data[0]
                self.face_groups.append( current_face_group )

            elif command == 'f':

                assert len(data) ==  3, "Sorry, only triangles are supported"

                # Parse indices from triples
                for word in data:
                    vi, ti, ni = word.split('/')
                    indices = (int(vi) - 1, int(ti) - 1, int(ni) - 1)
                    current_face_group.tri_indices.append(indices)


        for material in self.materials.values():

            model_path = os.path.split(fname)[0]
            texture_path = os.path.join(model_path, material.texture_fname)
            texture_surface = pygame.image.load(texture_path)
            texture_data = pygame.image.tostring(texture_surface, 'RGB', True)

            material.texture_id = glGenTextures(1)
            glBindTexture(GL_TEXTURE_2D, material.texture_id)

            glTexParameteri( GL_TEXTURE_2D,
                             GL_TEXTURE_MAG_FILTER,
                             GL_LINEAR)
            glTexParameteri( GL_TEXTURE_2D,
                             GL_TEXTURE_MIN_FILTER,
                             GL_LINEAR_MIPMAP_LINEAR)

            glPixelStorei(GL_UNPACK_ALIGNMENT,1)
            width, height = texture_surface.get_rect().size
            gluBuild2DMipmaps( GL_TEXTURE_2D,
                               3,
                               width,
                               height,
                               GL_RGB,
                               GL_UNSIGNED_BYTE,
                               texture_data)


    def read_mtllib(self, mtl_fname):

        file_mtllib = open(mtl_fname)
        for line in file_mtllib:

            words = line.split()
            command = words[0]
            data = words[1:]

            if command == 'newmtl':
                material = Material()
                material.name = data[0]
                self.materials[data[0]] = material

            elif command == 'map_Kd':
                material.texture_fname = data[0]


    def draw(self):

        vertices = self.vertices
        tex_coords = self.tex_coords
        normals = self.normals

        for face_group in self.face_groups:
        
            material = self.materials[face_group.material_name]
            glBindTexture(GL_TEXTURE_2D, material.texture_id)

            glBegin(GL_TRIANGLES)
            for vi, ti, ni in face_group.tri_indices:
                glTexCoord2fv( tex_coords[ti] )
                glNormal3fv( normals[ni] )
                glVertex3fv( vertices[vi] )
            glEnd()


    def draw_quick(self):

        if self.display_list_id is None:
            self.display_list_id = glGenLists(1)
            glNewList(self.display_list_id, GL_COMPILE)
            self.draw()
            glEndList()

        glCallList(self.display_list_id)
<file_sep>def get_attenuation(distance, constant, linear, quadratic):
    return 1.0 / (constant + linear * distance + quadratic * (distance ** 2))
<file_sep>https://www.youtube.com/watch?v=3_zEoolypYM&list=PLE3_ZiIESvFSkO7yrG1LVR78VWt4NureV<file_sep>"""Sprite classes for platform game

Attributes:
	vec (TYPE): Description
"""
import pygame as pg
import random
from settings import *
vec = pg.math.Vector2

class Spritesheet:

	"""Utility class for loading and parsing spritesheets
	"""
	def __init__(self, filename):
		self.spritesheet = pg.image.load(filename).convert()

	def get_image(self, x, y, width, height):
		image = pg.Surface((width,height))
		# from spritesheet we cut out an image (x, y, width, height)
		image.blit(self.spritesheet, (0,0), (x, y, width, height))
		#resize image
		image = pg.transform.scale(image, (width//2, height//2))
		return image

class  Player(pg.sprite.Sprite):

	"""Summary

	Attributes:
		acc (TYPE): Description
		game (TYPE): Description
		image (TYPE): Description
		pos (TYPE): Description
		rect (TYPE): Description
		vel (TYPE): Description
	"""

	def __init__(self, game):
		"""Summary

		Args:
		    game (TYPE): Description
		"""
		pg.sprite.Sprite.__init__(self)

		self.game = game #this is a copy of game for reference
		self.jumping = False
		self.walking = False
		self.current_frame = False
		self.last_update = False # frame animation
		self.load_images()
		self.image = pg.Surface((30,40))
		#self.image.fill(YELLOW) # YELLOW RECTANGLE PLAYER
		#get image from spritesheet
		#self.image = self.game.spritesheet.get_image(614,1063,120,191)
		# fix color image background problem
		#self.image.set_colorkey(BLACK)

		self.rect = self.image.get_rect()
		self.rect.center = (WIDTH_MID, HEIGHT_MID)
		self.pos = vec(50, HEIGHT_MID) # player spawn location

		self.vel = vec(0,0)
		self.acc = vec(0,0)

	def load_images(self):
		"""Load player images for animation
		- standing
		- walk right
		- walk left
		- jumping
		"""
		# Standing frames
		self.standing_frames = [
		self.game.spritesheet.get_image(614,1063, 120, 191),
		self.game.spritesheet.get_image(690, 406, 120, 201)]
		# fix color image background problem
		for frame in self.standing_frames:
			frame.set_colorkey(BLACK)
		# Walking right frames
		self.walk_frames_r = [
		self.game.spritesheet.get_image(678, 860, 120, 201),
		self.game.spritesheet.get_image(692, 1458, 120, 207)]
		for frame in self.walk_frames_r:
			frame.set_colorkey(BLACK)
		# Walking left frames
		self.walk_frames_l = []
		for frame in self.walk_frames_r:
			#flip(​Surface, flip vertically, flip horizonally)
			self.walk_frames_l.append(pg.transform.flip(frame, True, False))
		# Jumping frames
		self.jump_frame = self.game.spritesheet.get_image(382, 763, 150, 181)
		self.jump_frame.set_colorkey(BLACK)

	def jump_cut(self):
		""" Jump cut
		- when we are jumping we are traveling at 16 speed
		- jump cut, decreases jump velocity
		"""
		if self.jumping:
			if self.vel.y < -3:
				self.vel.y = -3

	def jump(self):
		"""Jump
		Jump only if standing on platform
		Check 2 pixel below if platform is there, than jump allowed
		1. temporary lower player for 2 pixel
		2. check for collision with platform
		3. move player 2 pixel up to original position
		4. if collided, than a player can jump
		"""
		self.rect.x += 2
		hits = pg.sprite.spritecollide(self, self.game.platforms, False)
		self.rect.x -= 2

		if hits and not self.jumping:
			self.jumping = True
			self.vel.y = PLAYER_JUMP_VELOCITY
			self.game.jump_sound.play()

	def update(self):
		""" Update player
		- key press events
		- movement mehanics equations
		- (friction, gravity, acc, vel, pos)
		"""
		self.animate()

		self.acc = vec(0,PLAYER_GRAVITY) # 0.5 is gravity
		keys = pg.key.get_pressed()
		if keys[pg.K_LEFT]:
			self.acc.x = -PLAYER_ACC
		elif keys[pg.K_RIGHT]:
			self.acc.x = PLAYER_ACC

		# boundaries constraints
		# if on RIGTH and if we are deccelerating toward wall
		if self.pos.x - (self.rect.width//2) <= 0:
			if self.vel.x < 0 or self.acc.x < 0:
				self.acc.x = 0
				self.vel.x = 0
		# if on LEFT and if we are accelerating toward wall
		if self.pos.x + (self.rect.width//2) >= WIDTH:
			if self.vel.x > 0 or self.acc.x > 0:
				self.acc.x = 0
				self.vel.x = 0

		self.vel += self.vel*PLAYER_FRICTION
		self.vel += self.acc

		# if because of friction, we stop. its because velocity
		# is rounded to 0. But its not 0. so we use treshold
		if abs(self.vel.x) < 0.1: # if velocity blow 0.1 pixel treshold
			self.vel.x = 0 # force velocity to 0, if too small

		#oon equation deltaX = 0.5*(v0 + v)
		self.pos += self.vel + 0.5*self.acc
		#self.rect.center = self.pos
		self.rect.midbottom = self.pos #player standing on platform

		#position = myFont.render("Position:", 1, WHITE)
		#screen.blit(position, (0, 0))

	def animate(self):
		"""animation is based on time
		- get current time
		"""
		now = pg.time.get_ticks()
		# animation for moving
		# if x velocity is not 0, than we are walking
		if self.vel.x != 0:
			self.walking = True
		else:
			self.walking = False
		# show walk animation
		if self.walking:
			if now - self.last_update > 150:
				self.last_update = now
				self.current_frame = (self.current_frame + 1) % len(self.walk_frames_l)
				#keep track where our bottom of rectangle is
				#so our character stands on platform
				bottom = self.rect.bottom

				# check direction, right/left
				if self.vel.x > 0: # right walk
					self.image = self.walk_frames_r[self.current_frame]
				else: # left walk
					self.image = self.walk_frames_l[self.current_frame]

				self.rect = self.image.get_rect()
				self.rect.bottom = bottom
		# animation for standing
		if not self.jumping and not self.walking:
			if now - self.last_update > 350:
				self.last_update = now
				self.current_frame = (self.current_frame + 1) % len(self.standing_frames)
				#keep track where our bottom of rectangle is
				#so our character stands on platform
				bottom = self.rect.bottom
				self.image = self.standing_frames[self.current_frame]
				self.rect = self.image.get_rect()
				self.rect.bottom = bottom

class Platform(pg.sprite.Sprite):

	"""Summary

	Attributes:
		image (TYPE): Description
		rect (TYPE): Description
	"""

	def __init__(self, game, x, y):
		"""class to create platform and boundaries
		where we can walk on

		Args:
			x (TYPE): Description
			y (TYPE): Description
			w (TYPE): Description
			h (TYPE): Description
		"""
		pg.sprite.Sprite.__init__(self)
		self.game = game
		# platform frames
		images = [
		self.game.spritesheet.get_image(0, 288, 380 ,94),
		self.game.spritesheet.get_image(213, 1662, 201, 100)]

		#select random image
		self.image = random.choice(images)
		#self.image = pg.Surface((w, h))
		#self.image.fill(PLATFORM_COLOR)
		self.image.set_colorkey(BLACK)
		self.rect = self.image.get_rect()
		self.rect.x = x
		self.rect.y = y<file_sep># Platform game

## Links

- [Kids Can Code Youtube](https://www.youtube.com/channel/UCNaPQ5uLX5iIEHUCLmfAgKg)
- [Pygame Tutorial #2: Platformer](https://www.youtube.com/playlist?list=PLsk-HSGFjnaG-BwZkuAOcVwWldfCLu1pq)

## Code

- [1 Settings Up]()
- [2 ]()
- [3 ]()
- [4 ]()
- [5 ]()
- [6 ]()
- [7 ]()
- [8 ]()
- [9 ]()
- [10 ]()
- [11 ]()
- [12 ]()
- [13 ]()
- [14 ]()
- [15 ]()
- [16 ]()
- [17 ]()
- [18 ]()
- [19 ]()

## Game description<file_sep>    def draw(self):

        vertices = self.vertices
        tex_coords = self.tex_coords
        normals = self.normals

        for face_group in self.face_groups:
        
            material = self.materials[face_group.material_name]
            glBindTexture(GL_TEXTURE_2D, material.texture_id)

            glBegin(GL_TRIANGLES)
            for vi, ti, ni in face_group.tri_indices:
                glTexCoord2fv( tex_coords[ti] )
                glNormal3fv( normals[ni] )
                glVertex3fv( vertices[vi] )
            glEnd()


    def draw_quick(self):

        if self.display_list_id is None:
            self.display_list_id = glGenLists(1)
            glNewList(self.display_list_id, GL_COMPILE)
            self.draw()
            glEndList()

        glCallList(self.display_list_id)
<file_sep>
import time
import msvcrt
from grid import Grid

GRID_WIDTH = 45
GRID_HEIGHT = 40

game_grid = Grid(GRID_WIDTH, GRID_HEIGHT)


def game_loop():

    x, y = game_grid.get_player_pos()
    game_grid.set_cell(x, y, 'U')

    while True:

        oldX, oldY = game_grid.get_player_pos() # first get the old position

        # get user input
        if msvcrt.kbhit():
            char = ord(msvcrt.getch()) # this is blocking without the msvcrt.kbhit()
    
            if char == 27: # the ESC key code, exit game
                break
            elif char == 97: # a key, move left
                x -= 1
            elif char == 100: # d key, move right
                x += 1
            else:
                continue

        if not game_grid.check_Hbounds(x):
            x, y = oldX, oldY
        else:
            game_grid.set_cell(oldX, oldY, '.')

        game_grid.set_player_pos(x, y) # then set the new position
        game_grid.set_cell(x, y, 'U')
    
        # update the eggs
        game_grid.update()

        # draw the game board
        game_grid.draw()

        time.sleep(0.1) # 1/10 or 0.1


if __name__ == "__main__":
    game_loop()<file_sep>import sys
import math
import random
import pygame
from pygame.locals import *
import tkinter as tk
from tkinter import messagebox

clock = pygame.time.Clock()

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
#--------------------------draw grid fuction----------------------------
def drawGrid(w,rows,surface):
	"""
	This function draws a square grid on main display
	"""
	#distance between grid lines
	sizeBtwn = w // rows
	x = 0
	y = 0

	#create grid by drawing lines
	for l in range(rows):
		x = x + sizeBtwn
		y = y + sizeBtwn

		#vertical lines
		pygame.draw.line(surface, WHITE, (x,0), (x,w))
		#horizontal lines
		pygame.draw.line(surface, WHITE, (0,y), (w,y))

#-------------------------cube object-----------------------------------------
class cube(object):
	"""
	class to create a single grid cube, that has position and movement
	"""
	rows = 20 #set number of rows
	w = 500 #set pixel screen width
	def __init__(self, start, dirnx, dirny, color = WHITE):
		self.pos = start	#touple (x,y)
		self.dirnx = 0
		self.dirny = 0
		self.color = color	#touple(r,g,b)

	def set_direction(self,dirnx,dirny):
		self.dirnx = dirnx
		self.dirny = dirny

	def move(self):
		"""
		move cube, by adding new direction to previous position
		"""
		self.pos = (self.pos[0]+self.dirnx, self.pos[1]+self.dirny)

	def draw(self,surface):
		"""
		drawing: convert x,y grid position to pixel position
		"""
		dis = self.w // self.rows #distance between x and y values
		#variables for easy coding
		i = self.pos[0] # row
		j = self.pos[1] # column
		#draw just a little bit less, so we draw inside of the square. and we dont cover grid.
		pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1,dis-2,dis-2 ))
#-----------------------------------------------------------------------------------

def redrawWindow(surface):
	global rows, width
	#background
	surface.fill(BLACK)
	#draw grid
	drawGrid(width, rows, surface)
	#draw ball
	ball.draw(surface)
	#update display
	pygame.display.update()
#---------------------------------------------------------------------------------------
def key_events():
	for event in pygame.event.get():
			if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
				#pygame.quit()
				#sys.exit()
				return True

	#in pong we move in only y directions
	keys = pygame.key.get_pressed()
	for key in keys:
		if keys[pygame.K_UP]:
			self.dirny = -1
			self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
		elif keys[pygame.K_DOWN]:
			self.dirny = 1
			self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

	return False
#---------------------------------------------------------------------------------------
def main():
	global width, rows, ball
	#---------------game initialization---------------------------
	#create game display
	width = 500
	rows = 20

	#create game objects
	win = pygame.display.set_mode((width, width)) #square display
	ball = cube((10,1),0,0,WHITE)
	ball.set_direction(1,1) #set initial ball movement direction

	FPScount = 0
	#-----------------------continuous game loop-------------
	GameOver = False
	while not GameOver:
		#pygame.time.delay(50)
		clock.tick(10)	#game max speed 10 FPS
		GameOver = key_events()

		#update ball position
		ball.move()
		#check next direction-------------------------------
		#CONSTRAINTS X
		if ball.pos[0] <= 0 or ball.pos[0] >= rows-1:
			ball.dirnx = -ball.dirnx
		#CONSTRAINTS Y
		if ball.pos[1] <= 0 or ball.pos[1] >= rows-1:
			ball.dirny = -ball.dirny

		#-------------------------------------------------
		#if we are moving in right direction
		#print(f'rows:{rows} ball.pos[0]:{ball.pos[0]} ball.pos[1]:{ball.pos[1]}')
		#FPScount += 1
		#print(FPScount)

		redrawWindow(win)
#---------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------
main()
pygame.quit()
sys.exit()
<file_sep>#DO NOT TOUCH game_properties!
game_properties = [
"current_score",
 "high_score",
  "number_of_lives",
   "items_in_inventory",
    "power_ups", "ammo",
     "enemies_on_screen",
      "enemy_kills",
       "enemy_kill_streaks",
        "minutes_played",
   "notifications",
"achievements"] 

# Use the game_properties list and dict.fromkeys() to generate a dictionary with all values set to 0. Save the result to a variable called initial_game_state
initial_game_state = {}.fromkeys(game_properties,0)
print(initial_game_state)<file_sep>from gameobjects.matrix44 import *

identity = Matrix44()
print(identity)
p1 = (1.0, 2.0, 3.0)
identity.transform(p1)

assert identity.get_column(3) == (0, 0, 0, 1), "Something is wrong with this matrix!"
<file_sep>"""Snake Game Python Tutorial
youtube video: https://www.youtube.com/watch?v=CD4qAhfFuLo
current time: 33:00
""" 
import sys
import math
import random
import pygame
from pygame.locals import *
import tkinter as tk
from tkinter import messagebox

WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)

class cube(object):
	"""
	"""
	rows = 20 #set number of rows
	w = 500 #set pixel screen width
	def __init__(self,start,dirnx=1,dirny=0,color=RED):
		self.pos = start
		self.dirnx = 1
		self.dirny = 0
		self.color = color

	def move(self,dirnx,dirny):
		"""
		move cube, by adding new direction to previous position
		"""
		self.dirnx = dirnx
		self.dirny = dirny
		self.pos = (self.pos[0]+self.dirnx, self.pos[1]+self.dirny)

	def draw(self,surface,eyes=False):
		"""
		drawing: convert x,y grid position to pixel position
		"""
		dis = self.w // self.rows #distance between x and y values
		#variables for easy coding
		i = self.pos[0] # row
		j = self.pos[1] # column
		#draw just a little bit less, so we draw inside of the square. and we dont cover grid.
		pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1,dis-2,dis-2 ))

		#draw eyes
		if eyes:
				centre = dis//2
				radius = 3
				circleMiddle = (i*dis+centre-radius, j*dis+8 ) #eye 1
				circleMiddle2 = (i*dis+dis-radius*2, j*dis+8 ) #eye 2
				pygame.draw.circle(surface, BLACK, circleMiddle, radius)
				pygame.draw.circle(surface, BLACK, circleMiddle2, radius)

class snake(object):
	"""
	class for snake
	"""
	body = [] #list of cube objects
	turns = {} #dictionary of turns  ADDING A KEY OF-->
	# key = current position of snake head
	# value = direction of turn]
	def __init__(self,color,pos):
		self.color = color
		self.head = cube(pos)
		self.body.append(self.head) # snake starts with one cube = head
		self.dirnx = 0	#direction moving x 1, -1
		self.dirny = 1	#direction moving y 1, -1

	def move(self):
		"""
		moving our snake in x,y thinking
		LEFT  	(self.dirnx=-1, self.dirny=0)
		RIGHT 	(self.dirnx=1, self.dirny=0)
		UP 		(self.dirnx=0, self.dirny=1)
		DOWN 	(self.dirnx=0, self.dirny=-1)
		"""
		for event in pygame.event.get():
			if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
				pygame.quit()
				sys.exit()

			keys = pygame.key.get_pressed()
			for key in keys:
				if keys[pygame.K_LEFT]:
					self.dirnx = -1
					self.dirny = 0
					# we mustremember where we turned, so other cubes can follow
					# add a new key
					#example - here we turned in thar way
					self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
				elif keys[pygame.K_RIGHT]:
					self.dirnx = 1
					self.dirny = 0
					self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
				elif keys[pygame.K_UP]:
					self.dirnx = 0
					self.dirny = -1
					self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
				elif keys[pygame.K_DOWN]:
					self.dirnx = 0
					self.dirny = 1
					self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

		#look trough all position of snake
		#we get the index=i and the cube=c of body
		for i, c in enumerate(self.body):
			p = c.pos[:]
			#for each of the sube, we grab position and check turn
			#if this position in turns, than we move
			if p in self.turns:
				turn = self.turns[p]
				#here we store direction where to move
				c.move(turn[0],turn[1])
				#if we are on the last cube of the snake, remove the turn, we finished it
				if i == len(self.body)-1:
					self.turns.pop(p)

			else:	#CHECK IF WE REACHED EDGE OF THE SCREEN
				#if MOVE LEFT & we are at the left side of screen
				if (c.dirnx == -1) and (c.pos[0] <= 0):
					c.pos = (c.rows-1,c.pos[1])
					#c.pos = (c.rows-1,c.pos[1])
				#if MOVE RIGHT & we are at the left side of screen
				elif (c.dirnx == 1) and (c.pos[0] >= c.rows-1):
					c.pos = (0,c.pos[1])
				#if MOVE DOWN & we are at the left side of screen
				elif (c.dirny == 1) and (c.pos[1] >= c.rows-1):
					c.pos = (c.pos[0],0)
				#if MOVE UP & we are at the left side of screen
				elif (c.dirny == -1) and (c.pos[1] <= 0):
					c.pos = (c.pos[0],c.rows-1)
				#normal move of cube
				else:
					c.move(c.dirnx,c.dirny)

	def reset(self,pos):
		pass

	def addCube(self):
		pass

	def draw(self,surface):
		for index, cube in enumerate(self.body):
			#check where to draw eyes for snake head
			if index == 0:
				cube.draw(surface,True) #with eyes
			else:
				cube.draw(surface,False) #without eyes


def drawGrid(w,rows,surface):
	"""
	This function draws a square grid on main display
	"""
	#distance between grid lines
	sizeBtwn = w // rows
	x = 0
	y = 0

	#create grid by drawing lines
	for l in range(rows):
		x = x + sizeBtwn
		y = y + sizeBtwn
		#vertical lines
		pygame.draw.line(surface, WHITE, (x,0), (x,w))
		#horizontal lines
		pygame.draw.line(surface, WHITE, (0,y), (w,y))

def redrawWindow(surface):
	global rows, width, s
	#background
	surface.fill(BLACK)
	s.draw(surface)
	#draw grid
	drawGrid(width, rows, surface)
	#update display
	pygame.display.update()

def randomSnack(rows,items):
	pass

def message_box(subject,content):
	pass

def key_events():
	pass

#directions = {"right":(1,0), "left":(0,-1), "up":(0,-1), "down":(0,1)}

def main():
	global width, rows, s
	#create game display
	width = 500
	rows = 20
	win = pygame.display.set_mode((width, width)) #square display
	#snake start position
	s = snake(color=RED, pos=(10,10))

	clock = pygame.time.Clock()

	flag = True
	FPScount = 0
	print(FPScount)
	while flag:
		#pygame.time.delay(50)
		clock.tick(10)	#game max speed 10 FPS
		s.move()
		redrawWindow(win)

		FPScount += 1
		print(f'FPScount:{FPScount}')

#rows = 0
#w = 0
#h = 0

#cube.rows = rows
#cube.w = w
main()
pygame.quit()
sys.exit()<file_sep>Here are the codes from my video series on youtube, on how to create a Snake game in Lua and Love2d.
You can watch the videos here: https://www.youtube.com/playlist?list=PL1P11yPQAo7q_BWMKFZvUlLBqLRUJLrJm
<file_sep>import pygame
import time
import random

pygame.init()
#---------game constants variables-------------
display_width = 800
display_height = 600
#RGB color constants 
black = (0,0,0)
white = (255,255,255)
red   = (255,0,0)
green = (0,255,0)
blue  = (0,0,255)
#------------------------------------------------------
#create main display window
gameDisplay = pygame.display.set_mode((display_width,display_height))
#set main display window title
pygame.display.set_caption('Race Game')

clock = pygame.time.Clock()
#-------------------load images-----------------------------------
# load image
carImg = pygame.image.load('race_car_transp_v2.png')
#get image size in pixels. for colision detection
carImg_width = carImg.get_rect().size[0]
carImg_height = carImg.get_rect().size[1]

#-------------------FUNCTIONS------------------------------------
#creating things that move towards car
def things(thingx,thingy,thingw,thingh,color):
	pygame.draw.rect((gameDisplay),color,[thingx,thingy,thingw,thingh])

#function to display a car
def car(x,y):
	gameDisplay.blit(carImg,(x,y)) #we blit car image to a surface

def text_objects(text,font):
	textSurface = font.render(text, True, black)
	return	textSurface, textSurface.get_rect()

def message_display(text):
	#define look of the writing
	largeText = pygame.font.Font('freesansbold.ttf',100)
	#create a custom function for message box display
	TextSurf, TextRect = text_objects(text, largeText)
	#center the message box display on of the middle screen
	TextRect.center =((display_width/2),(display_height/2))
	#draw image with blit
	gameDisplay.blit(TextSurf,TextRect)
	#update display
	pygame.display.update()
	time.sleep(2)
	game_loop()

def crash():
	message_display('You Chrashed')

def game_loop():
	x = display_width*0.45
	y = display_height*0.8
	#for computers (x=0,y=0) is top left corner

#--------------------main game loop--------------------
	x_change = 0
	
	#objects apear randomly on x axis
	thing_startx = random.randrange(0,display_width)
	#start object off the screen-above 
	thing_starty = -600
	thing_speed = 7
	thing_width = 100 #pixles
	thing_height = 100

	gameExit = False

	while not gameExit:

		#------------key press game logic-------------
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				#gameExit = True
				pygame.quit()
				quit()	

				#if key pressed start moving
			if event.type == pygame.KEYDOWN:
			    if event.key == pygame.K_LEFT:
			    	x_change = -5
			    elif event.key == pygame.K_RIGHT:
			    	x_change = 5

				#if key released stop moving
			if event.type == pygame.KEYUP:
			    if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
			    	x_change = 0

		x += x_change

		#------------graphics and logic----------------------
		#draw background
		gameDisplay.fill(white)	
		#draw things
		things(thing_startx, thing_starty,thing_width,thing_height,black)
		#move things
		thing_starty += thing_speed
		#draw car
		car(x,y)				
		#----------check boundaries for chrash----------
		if x > display_width - carImg_width or x < 0:
			crash()
			gameExit = True
		#----------is thing thing that moves off the screen----------
		if thing_starty > display_height:
			thing_starty = 0 - thing_height 
			thing_startx = random.randrange(0,display_width)
		#start is 600 off the screen
		#start is 600 off the screen

		pygame.display.update() #update all changes to display
		clock.tick(60)	
#------------------------------------
game_loop()		#game is running here, until pygame.QUIT
#pygame.quit()	
#quit()<file_sep>from gameobjects.vector3 import *

A = Vector3(6, 8, 12)
B = Vector3(10, 16, 12)

print("A is", A)
print("B is", B)
print("Magnitude of A is", A.get_magnitude())
print("A+B is", A+B)
print("A-B is", A-B)


print("A normalized is", A.get_normalized())
print("A*2 is", A * 2)
<file_sep>import pygame
from random import randint


pygame.font.init()
myfont = pygame.font.SysFont('Comic Sans MS', 18)


class Cell:
    def __init__(self, pos, random_mine):
        self.visible = False
        self.mine = random_mine
        self.show_mine = False
        self.size = 30
        self.color = (200,200,200)
        self.pos = pos
        self.label = False
        self.mine_counter = 0
        self.font_color = (0, 0, 0)
        self.marked = False
        self.explosion = False

    def draw(self, surface):
        if self.visible:
            pygame.draw.rect(surface, self.color, (self.pos[0], self.pos[1], self.size, self.size))
        elif self.marked:
            pygame.draw.rect(surface, (150, 50, 50), (self.pos[0], self.pos[1], self.size, self.size))
        else:
            pygame.draw.rect(surface, (50,50,50), (self.pos[0], self.pos[1], self.size, self.size))
        if self.show_mine and self.mine:
            pygame.draw.circle(surface, (10,10,10), (self.pos[0]+15, self.pos[1]+15), 15)
        if self.explosion:
            pygame.draw.circle(surface, (255,10,10), (self.pos[0]+15, self.pos[1]+15), 15)

        if self.label:
            self.show_label(surface, self.mine_counter, self.pos)

    def show_label(self, surface, label, pos):
        textsurface = myfont.render(label, False, self.font_color)
        surface.blit(textsurface, (pos[0]+10, pos[1]+4))


class Grid:
    def __init__(self, player):
        self.player = player
        self.cells = []
        self.search_dirs = [(0,-1),(-1,-1),(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1)]

        for y in range(30):
            self.cells.append([])
            for x in range(30):
                self.cells[y].append(Cell((x*30, y*30), self.random_mines()))

        self.lines =[]

        for y in range(1, 31, 1):
            temp = []
            temp.append((0, y * 30))
            temp.append((900, y * 30))
            self.lines.append(temp)

        for x in range(1, 31, 1):
            temp = []
            temp.append((x*30, 0))
            temp.append((x*30, 900))
            self.lines.append(temp)

    def random_mines(self):
        r = randint(0, 10)
        if r > 9:
            return True
        else:
            return False

    def draw(self, surface):
        for row in self.cells:
            for cell in row:
                cell.draw(surface)
        for line in self.lines:
            pygame.draw.line(surface, (0, 125, 0), line[0], line[1])

    def is_within_bounds(self, x, y):  # need to check for the edges and corners, so list index will not be out of range
        return x >= 0 and x < 30 and y >= 0 and y < 30

    def search(self, x, y):
        if not self.is_within_bounds(x, y):
            return

        cell = self.cells[y][x]

        if cell.visible:
            return

        if cell.mine:
            #cell.show_mine = True
            cell.explosion = True
            self.player.sub_health()
            return

        cell.visible = True

        num_mines = self.num_of_mines(x, y)

        if num_mines > 0:
            cell.label = True
            cell.mine_counter = str(num_mines)
            return

        for xx, yy in self.search_dirs:
            self.search(x+xx, y+yy)


    def num_of_mines(self, x, y):
        counter = 0
        for xx, yy in self.search_dirs:
            if self.is_within_bounds(x + xx, y + yy) and self.cells[y + yy][x + xx].mine:
                counter += 1
        return counter

    def click(self, x, y):
        grid_x, grid_y = x//30, y//30
        self.search(grid_x, grid_y)

    def reload(self):
        self.player.health = 5
        for row in self.cells:
            for cell in row:
                cell.visible = False
                cell.label = False
                cell.marked = False
                cell.show_mine = False
                cell.explosion = False
                cell.mine = self.random_mines()

    def check_if_win(self):
        if self.player.health < 1:
            return False
        for row in self.cells:
            for cell in row:
                if not cell.visible and not cell.mine:
                    return False
        return True

    def show_mines(self):
        for row in self.cells:
            for cell in row:
                if not cell.show_mine:
                    cell.show_mine = True
                else:
                    cell.show_mine = False


    def mark_mine(self, x, y):
        self.cells[y][x].marked = True

<file_sep># Scoring

After Tetris for Game Boy, most games adopted a scoring system designed to reward difficult clears by giving points for more lines cleared at once. Some systems also encouraged starting at a higher difficulty.

Contents[show]
Original Nintendo Scoring System
This score was used in Nintendo's versions of Tetris for NES, for Game Boy, and for Super NES.

Level   Points for
1 line  Points for
2 lines Points for
3 lines Points for
4 lines
0   40  100 300 1200
1   80  200 600 2400
2   120 300 900 3600
9   400 1000    3000    12000
n   40 * (n + 1)    100 * (n + 1)   300 * (n + 1)   1200 * (n + 1)
For each piece, the game also awards the number of points equal to the number of grid spaces that the player has continuously soft dropped the piece. Unlike the points for lines, this does not increase per level.

The New Tetris
The New Tetris awards "lines": one for each line cleared, one extra line for clearing four lines with one I tetromino, and several lines for clearing parts of a 4x4 square. This does not increase as the game gets faster. Soft and firm drops do not give points instead, they allow the player to place more tetrominoes (and clear more lines) in the three minute sprint game.

Tetris Worlds
Each mode of Tetris Worlds has its own scoring system. As in The New Tetris, the unit of score in each mode is lines 2, 3, and 4-line clears grant additional points in some modes.

Tetris Deluxe
Tetris Deluxe scoring system is similar to Tetris Worlds.

Tetris DS
Each mode of Tetris DS has its own scoring system. Most notably, the system used in Standard mode represents a fusion of the 1, 3, 5, 8 pattern used in several modes of Tetris Worlds with the section multiplier of the NES and Game Boy system.

Guideline scoring system
Most games released after Tetris DS have the same scoring system. Here is the guideline scoring system as of 2009 (uses 3-corner T).

Action      Point Value
Single/Mini T-spin      100×level
Mini T-Spin Single      200×level
Double      300×level
T-Spin      400×level
Triple      500×level
Tetris/T-Spin Single        800×level
B2B T-Spin Single/B2B Tetris/T-Spin Double      1,200×level
T-Spin Triple       1,600×level
B2B T-Spin Double       1,800×level
B2B T-Spin Triple       2,400×level
Combo       LC×LV+50×LV
Soft drop       1 point per cell (Max of 20)
Hard drop       2 points per cell (Max of 40)
<file_sep>def saturate_color(color): 
    red, green, blue = color 
    red   = min(red, 255)
    green = min(green, 255) 
    blue  = min(blue, 255) 
    return red, green, blue
<file_sep>def additive_blend(src, dst):
    return src * src.a + dst
<file_sep>class AntStateExploring(State):

    def __init__(self, ant):

        # Call the base class constructor to initialize the State
        State.__init__(self, "exploring")
        # Set the ant that this State will manipulate
        self.ant = ant

    def random_destination(self):

        # Select a point in the screen
        w, h = SCREEN_SIZE
        self.ant.destination = Vector2(randint(0, w), randint(0, h))

    def do_actions(self):

        # Change direction, 1 in 20 calls
        if randint(1, 20) == 1:
             self.random_destination()

    def check_conditions(self):

        # If there is a nearby leaf, switch to seeking state
        leaf = self.ant.world.get_close_entity("leaf", self.ant.location)
        if leaf is not None:
                self.ant.leaf_id = leaf.id
                return "seeking"
        # If there is a nearby spider, switch to hunting state
        spider = self.ant.world.get_close_entity("spider", NEST_POSITION, NEST_SIZE)
        if spider is not None:
             if self.ant.location.get_distance_to(spider.location) < 100.:
                 self.ant.spider_id = spider.id
                 return "hunting"

        return None

    def entry_actions(self):

        # Start with random speed and heading
        self.ant.speed = 120. + randint(-30, 30)
        self.random_destination()
<file_sep>def scale_color(color, scale): 
    red, green, blue = color 
    red   = int(red*scale)
    green = int(green*scale) 
    blue  = int(blue*scale) 
    return red, green, blue

fireball_orange = (221, 99, 20)
print(fireball_orange)
print(scale_color(fireball_orange, .5))
<file_sep>class GameEntity(object):

    def __init__(self, world, name, image):

        self.world = world
        self.name = name
        self.image = image
        self.location = Vector2(0, 0)
        self.destination = Vector2(0, 0)
        self.speed = 0.

        self.brain = StateMachine()
 
        self.id = 0

    def render(self, surface):

        x, y = self.location
        w, h = self.image.get_size()
        surface.blit(self.image, (x-w/2, y-h/2))

    def process(self, time_passed):

        self.brain.think()

        if self.speed > 0 and self.location != self.destination:

           vec_to_destination = self.destination - self.location
           distance_to_destination = vec_to_destination.get_length()
           heading = vec_to_destination.get_normalized()
           travel_distance = min(distance_to_destination, time_passed * self.speed)
           self.location += travel_distance * heading
<file_sep>
-- game states
GameStates = {pause='pause', running='running', game_over='game over'}
state = GameStates.running

local snakeX = 15
local snakeY = 15
local dirX = 0
local dirY = 0

local SIZE = 30
local appleX = 0
local appleY = 0
local tail = {}

tail_length = 0
up = false
down = false
left = false
right = false

function add_apple() -- randomize the apples's position on x and y between 0 and 29
  math.randomseed(os.time())
  appleX = math.random(SIZE-1)
  appleY = math.random(SIZE-1)
end

function game_draw()
  love.graphics.setColor(1.0, 0.35, 0.4, 1.0) -- draw the snake's head
  love.graphics.rectangle('fill', snakeX*SIZE, snakeY*SIZE, SIZE, SIZE, 10, 10)
  
  love.graphics.setColor(0.7, 0.35, 0.4, 1.0) -- draw the snake's tails
  for _, v in ipairs(tail) do
    love.graphics.rectangle('fill', v[1]*SIZE, v[2]*SIZE, SIZE, SIZE, 15, 15)
  end
  
  love.graphics.setColor(0.8, 0.9, 0.0, 1.0) -- draw the apple
  love.graphics.rectangle('fill', appleX*SIZE, appleY*SIZE, SIZE, SIZE, 10, 10)
  
  love.graphics.setColor(1, 1, 1, 1) -- darw the collected apples text
  love.graphics.print('collected apples: '.. tail_length, 10, 10, 0, 1.5, 1.5)
end

function game_update()
  if up and dirY == 0 then
    dirX, dirY = 0, -1
  elseif down and dirY == 0 then
    dirX, dirY = 0, 1
  elseif left and dirX == 0 then
    dirX, dirY = -1, 0
  elseif right and dirX == 0 then
    dirX, dirY = 1, 0
  end
  
  local oldX = snakeX
  local oldY = snakeY
  
  snakeX = snakeX + dirX
  snakeY = snakeY + dirY
  
  if snakeX == appleX and snakeY == appleY then
    add_apple()
    tail_length = tail_length + 1
    table.insert(tail, {0,0})
  end
  
  if snakeX < 0 then
    snakeX = SIZE - 1
  elseif snakeX > SIZE - 1 then
    snakeX = 0
  elseif snakeY < 0 then
    snakeY = SIZE - 1
  elseif snakeY > SIZE - 1 then
    snakeY = 0
  end
  
  if tail_length > 0 then
    for _, v in ipairs(tail) do 
      local x, y = v[1], v[2] -- following the (c=a, a=b, b=c) logic
      v[1], v[2] = oldX, oldY
      oldX, oldY = x, y
    end
    
  end
  
  for _, v in ipairs(tail) do
    if snakeX == v[1] and snakeY == v[2] then
      state = GameStates.game_over
    end
  end
end

function game_restart()
  snakeX, snakeY = 15, 15
  dirX, dirY = 0, 0
  tail = {}
  up, down, left, right = false, false, false, false
  tail_length = 0
  state = GameStates.running
  add_apple()
end
<file_sep>import pygame
from pygame.locals import *
from sys import exit

pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)

# Get a list of joystick objects
joysticks = []
for joystick_no in range(pygame.joystick.get_count()):
    stick = pygame.joystick.Joystick(joystick_no)
    stick.init()
    joysticks.append(stick)

if not joysticks:
    print("Sorry! No joystick(s) to test.")
    pygame.quit()
    exit()

active_joystick = 0


pygame.display.set_caption(joysticks[0].get_name())

def draw_axis(surface, x, y, axis_x, axis_y, size):

    line_col = (128, 128, 128)
    num_lines = 40
    step = size / float(num_lines)
    for n in range(num_lines):
        line_col = [(192, 192, 192), (220, 220, 220)][n&1]
        pygame.draw.line(surface, line_col, (x+n*step, y), (x+n*step, y+size))
        pygame.draw.line(surface, line_col, (x, y+n*step), (x+size, y+n*step))

    pygame.draw.line(surface, (0, 0, 0), (x, y+size/2), (x+size, y+size/2))
    pygame.draw.line(surface, (0, 0, 0), (x+size/2, y), (x+size/2, y+size))

    draw_x = int(x + (axis_x * size + size) / 2.)
    draw_y = int(y + (axis_y * size + size) / 2.)
    draw_pos = (draw_x, draw_y)
    center_pos = (x+size/2, y+size/2)
    pygame.draw.line(surface, (0, 0, 0), center_pos, draw_pos, 5)
    pygame.draw.circle(surface, (0, 0, 255), draw_pos, 10)


def draw_dpad(surface, x, y, axis_x, axis_y):

    col = (255, 0, 0)
    if axis_x == -1:
        pygame.draw.circle(surface, col, (x-20, y), 10)
    elif axis_x == +1:
       pygame.draw.circle(surface, col, (x+20, y), 10)

    if axis_y == -1:
        pygame.draw.circle(surface, col, (x, y+20), 10)
    elif axis_y == +1:
        pygame.draw.circle(surface, col, (x, y-20), 10)

while True:

    joystick = joysticks[active_joystick]

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()

    if event.type == KEYDOWN:
        if event.key >= K_0 and event.key <= K_1:
            num = event.key - K_0
     
            if num < len(joysticks):
                active_joystick = num
                name = joysticks[active_joystick].get_name()
                pygame.display.set_caption(name)

    # Get a list of all the axis
    axes = []
    for axis_no in range(joystick.get_numaxes()):
        axes.append( joystick.get_axis(axis_no) )

    axis_size = min(256, 640 / (joystick.get_numaxes()/2))

    pygame.draw.rect(screen, (255, 255,255), (0, 0, 640, 480))

    # Draw all the axes (analog sticks)
    x = 0
    for axis_no in range(0, len(axes), 2):
        axis_x = axes[axis_no]
        if axis_no+1 < len(axes):
            axis_y = axes[axis_no+1]
        else:
            axis_y = 0.
        draw_axis(screen, x, 0, axis_x, axis_y, axis_size)
        x += axis_size


    # Draw all the hats (d-pads)
    x, y = 50, 300
    for hat_no in range(joystick.get_numhats()):
        axis_x, axis_y = joystick.get_hat(hat_no)
        draw_dpad(screen, x, y, axis_x, axis_y)
        x+= 100


    #Draw all the buttons x, y = 0.0, 390.0
    button_width = 640 / joystick.get_numbuttons()
    for button_no in range(joystick.get_numbuttons()):
        if joystick.get_button(button_no):
            pygame.draw.circle(screen, (0, 255, 0), (int(x), int(y)), 20)
        x += button_width

    pygame.display.update()
<file_sep>class Ant(GameEntity):

    def __init__(self, world, image):

        # Call the base class constructor
        GameEntity.__init__(self, world, "ant", image)

        # Create instances of each of the states
        exploring_state = AntStateExploring(self)
        seeking_state = AntStateSeeking(self)
        delivering_state = AntStateDelivering(self)
        hunting_state = AntStateHunting(self)

        # Add the states to the state machine (self.brain)
        self.brain.add_state(exploring_state)
        self.brain.add_state(seeking_state)
        self.brain.add_state(delivering_state)
        self.brain.add_state(hunting_state)

        self.carry_image = None

    def carry(self, image):

        self.carry_image = image

    def drop(self, surface):

        # Blit the 'carry' image to the background and reset it
        if self.carry_image:
            x, y = self.location
            w, h = self.carry_image.get_size()
            surface.blit(self.carry_image, (x-w, y-h/2))
            self.carry_image = None

    def render(self, surface):

        # Call the render function of the base class
        GameEntity.render(self, surface)

    # Extra code to render the 'carry' image
    if self.carry_image:
        x, y = self.location
        w, h = self.carry_image.get_size()
        surface.blit(self.carry_image, (x-w, y-h/2))

<file_sep>import pyglet
from pyglet.window import key
from pyglet.window import FPSDisplay
from random import randint, choice


window = pyglet.window.Window(width=1200, height=900, caption="Space Invaders", resizable=False)
window.set_location(400, 100)
fps_display = FPSDisplay(window)
fps_display.label.font_size = 50

main_batch = pyglet.graphics.Batch()

def load_high_score(file):
    with open(file, 'r') as f:
        score = f.read()
    return score

def save_high_score(file, scr):
    with open(file, 'w') as f:
        f.write(str(scr))

# region Sprites, Labels and Animations
# loading static images
space = pyglet.image.load('res/sprites/space.jpg')
player_image = pyglet.image.load('res/sprites/PlayerShip.png') # space_ship.png
player_laser = pyglet.image.load('res/sprites/laser.png')
enemy_laser = pyglet.image.load('res/sprites/enemy_laser.png')
stats_bg_image = pyglet.image.load('res/sprites/stats_bg_white.png')

# loading sprite sheet animations for the ufo_head
ufo_head = pyglet.image.load('res/sprites/ufoHead_Sh.png')
ufo_head_seq = pyglet.image.ImageGrid(ufo_head, 1, 8, item_width=100, item_height=100)
ufo_head_texture = pyglet.image.TextureGrid(ufo_head_seq)
ufo_head_anim = pyglet.image.Animation.from_image_sequence(ufo_head_texture[0:], 0.1, loop=True)

# loading sprite sheet animations for the enemy space ship
enemy_ship = pyglet.image.load('res/sprites/enemyShip_Sh01.png')
enemy_ship_seq = pyglet.image.ImageGrid(enemy_ship, 1, 15, item_width=100, item_height=100)
enemy_ship_texture = pyglet.image.TextureGrid(enemy_ship_seq)
enemy_ship_anim = pyglet.image.Animation.from_image_sequence(enemy_ship_texture[0:], 0.1, loop=True)

# loading sprite sheet animations for explosion
xplosion_image = pyglet.image.load('res/sprites/explosion.png')
xplosion_seq = pyglet.image.ImageGrid(xplosion_image, 4, 5, item_width=96, item_height=96)
xplosion_textures = pyglet.image.TextureGrid(xplosion_seq)
xplosion_anim = pyglet.image.Animation.from_image_sequence(xplosion_textures[0:], 0.05, loop=True)

# creating a label called "enemies destroyed"
text1 = pyglet.text.Label("enemies destroyed", x=1000 , y=850, batch=main_batch)
text1.italic = True
text1.bold = True
text1.font_size = 16

# creating a label called "score"
text2 = pyglet.text.Label("score", x=1000 , y=750, batch=main_batch)
text2.italic = True
text2.bold = True
text2.font_size = 16

# creating a label called "player health"
text3 = pyglet.text.Label("player health", x=1000 , y=650, batch=main_batch)
text3.italic = True
text3.bold = True
text3.font_size = 16

# creating a label for high score text
high_score_text = pyglet.text.Label("high score", x=1000 , y=450, batch=main_batch)
high_score_text.italic = True
high_score_text.bold = True
high_score_text.font_size = 20

# label for displaying the high score value
high_score = load_high_score("res/score.txt")
high_score_value = pyglet.text.Label(high_score, x=1100, y=400, batch=main_batch)
high_score_value.color = (120, 200, 150, 255)
high_score_value.font_size = 24

# creating a label to display the number of destroyed enemies
num_enemies_destroyed = pyglet.text.Label(str(0), x=1100, y=800, batch=main_batch)
num_enemies_destroyed.color = (120, 200, 150, 255)
num_enemies_destroyed.font_size = 22

# creating a label to display the score
num_score = pyglet.text.Label(str(0), x=1100, y=700, batch=main_batch)
num_score.color = (220, 100, 150, 255)
num_score.font_size = 22

# creating a label to display the player's health
numb_player_health = pyglet.text.Label(str(5), x=1100, y=600, batch=main_batch)
numb_player_health.color = (0, 100, 50, 255)
numb_player_health.font_size = 22

game_over_text = pyglet.text.Label("game over", x=600 , y=500)
game_over_text.anchor_x = "center"
game_over_text.anchor_y = "center"
game_over_text.italic = True
game_over_text.bold = True
game_over_text.font_size = 60

reload_text = pyglet.text.Label("press r to reload", x=600 , y=350)
reload_text.anchor_x = "center"
reload_text.anchor_y = "center"
reload_text.italic = True
reload_text.bold = True
reload_text.font_size = 40

intro_text = pyglet.text.Label("press space to start", x=600 , y=450)
intro_text.anchor_x = "center"
intro_text.anchor_y = "center"
intro_text.italic = True
intro_text.bold = True
intro_text.font_size = 40

player = pyglet.sprite.Sprite(player_image, x=500, y=100, batch=main_batch)
stats_bg = pyglet.sprite.Sprite(stats_bg_image, x=980, y=300, batch=main_batch)
stats_bg.opacity = 10
# endregion

#explosion = pyglet.media.StaticSource(pyglet.media.load('../res/sounds/exp_01.wav', streaming=False))
explosion = pyglet.media.load('res/sounds/exp_01.wav', streaming=False)
player_gun_sound = pyglet.media.load('res/sounds/player_gun.wav', streaming=False)

player_laser_list = []
enemy_laser_list = []
enemy_list = []
bg_list = []
explosion_list = []

# when creating a new enemy, it will choose a random direction from the list below
directions = [1, -1]

player_speed = 300
left = False
right = False
destroyed_enemies = 0 # this for only stats
next_wave = 0
score = 0
fire = False
player_fire_rate = 0
enemy_fire_rate = 0
ufo_head_spawner = 0
enemy_ship_spawner = 0
ufo_head_spawner_count = 1
enemy_ship_spawner_count = 5
preloaded =  False
player_health = 5
player_is_alive = True
explode_time = 2
enemy_explode = False
shake_time = 0
game = False
flash_time = 1
player_flash = False

@window.event
def on_draw():
    window.clear()
    if not preloaded:
        preload()
    for bg in bg_list:
        bg.draw()
    if game:
        main_batch.draw()
    else:
        intro_text.draw()
    if not player_is_alive:
        game_over_text.draw()
        reload_text.draw()
    fps_display.draw()

def reload():
    global player_is_alive, next_wave, score, destroyed_enemies, player_fire_rate, enemy_fire_rate, explode_time
    global ufo_head_spawner, enemy_ship_spawner, ufo_head_spawner_count, enemy_ship_spawner_count, player_health
    global enemy_explode, shake_time, high_score
    next_wave = 0
    score = 0
    player_health = 5
    player_fire_rate = 0
    enemy_fire_rate = 0
    ufo_head_spawner = 0
    enemy_ship_spawner = 0
    ufo_head_spawner_count = 1
    enemy_ship_spawner_count = 5
    explode_time = 2
    enemy_explode = False
    shake_time = 0
    destroyed_enemies = 0
    player_is_alive = True
    player.x, player.y = 500, 100
    player.batch = main_batch

    # reload the score from the score text file
    high_score = load_high_score("res/score.txt")
    high_score_value.text = high_score

    num_enemies_destroyed.text = str(destroyed_enemies)
    num_score.text = str(score)
    numb_player_health.text = str(player_health)

    for obj in enemy_list:
        obj.batch = None
    for obj in enemy_laser_list:
        obj.batch = None
    enemy_list.clear()
    enemy_laser_list.clear()

@window.event
def on_key_press(symbol, modifiers):
    global  right, left, fire, game
    if symbol == key.RIGHT:
        right = True
    if symbol == key.LEFT:
        left = True
    if symbol == key.SPACE:
        fire = True
        if not game:
            game = True
            fire = False # to prevent firing when the game starts
    if symbol == key.R:
        reload()

@window.event
def on_key_release(symbol, modifiers):
    global right, left, fire
    if symbol == key.RIGHT:
        right = False
    if symbol == key.LEFT:
        left = False
    if symbol == key.SPACE:
        fire = False

def player_move(entity, dt):
    if right and entity.x < 1000:
        entity.x += player_speed * dt
    if left and entity.x > 100:
        entity.x -= player_speed * dt

# this function runs only once, it loads two background images at the start
def preload():
    global preloaded
    for i in range(2):
        bg_list.append(pyglet.sprite.Sprite(space, x=0, y=i*1200))
    preloaded = True

def bg_move(dt):
    for bg in bg_list:
        bg.y -= 50*dt
        if bg.y <= -1300:
            bg_list.remove(bg)
            bg_list.append(pyglet.sprite.Sprite(space, x=0, y=1100))

def enemy_move(enemies, yspeed, dt):
    global score
    for enemy in enemies:
        if enemy.x >= 1000:
            enemy.x = 1000
            enemy.speed *= -1
        if enemy.x <= 100:
            enemy.x = 100
            enemy.speed *= -1
        enemy.y -= yspeed*dt
        enemy.x += enemy.speed * dt
        if enemy.y <= 450 and enemy.y >= 449.4 and player_is_alive:
            score -= 1
            num_score.text = str(score)
        if enemy.y <= -100:
            enemies.remove(enemy)

def enemy_spawn(dt):
    global ufo_head_spawner, enemy_ship_spawner, player_is_alive, ufo_head_spawner_count, enemy_ship_spawner_count
    global next_wave
    ufo_head_spawner -= dt
    enemy_ship_spawner -= dt
    if player_is_alive:
        if ufo_head_spawner <= 0:
            enemy_list.append(pyglet.sprite.Sprite(ufo_head_anim, x=600, y=950, batch=main_batch))
            enemy_list[-1].speed = randint(100, 300) * choice(directions) # last spawned entity in entity list
            enemy_list[-1].hit_count = 0
            enemy_list[-1].MAX_HIT = 2
            ufo_head_spawner += ufo_head_spawner_count
        if enemy_ship_spawner <= 0:
            enemy_list.append(pyglet.sprite.Sprite(enemy_ship_anim, x=600, y=950, batch=main_batch))
            enemy_list[-1].speed = randint(100, 300) * choice(directions)  # last spawned entity in entity list
            enemy_list[-1].hit_count = 0
            enemy_list[-1].MAX_HIT = 8
            enemy_ship_spawner += enemy_ship_spawner_count
    if next_wave >= 20:
        ufo_head_spawner_count -= 0.05
        enemy_ship_spawner_count -= 0.2
        next_wave = 0

def enemy_shoot(dt):
    global enemy_fire_rate
    enemy_fire_rate -= dt
    if enemy_fire_rate <= 0:
        for enemy in enemy_list:
            if randint(0, 10) >= 5:
                enemy_laser_list.append(pyglet.sprite.Sprite(enemy_laser, enemy.x + 50, enemy.y, batch=main_batch))
        enemy_fire_rate += 5

def update_enemy_shoot(dt):
    for lsr in enemy_laser_list:
        lsr.y -= 400 * dt
        if lsr.y < -50: # if the lasers y position is belov -100 it gets removed from the laser list
            enemy_laser_list.remove(lsr)

def player_shoot(dt):
    global player_fire_rate
    player_fire_rate -= dt
    if player_fire_rate <= 0:
        player_laser_list.append(pyglet.sprite.Sprite(player_laser, player.x + 32, player.y + 96, batch=main_batch))
        player_fire_rate += 0.2
        if player_is_alive:
            player_gun_sound.play()

def update_player_shoot(dt):
    for lsr in player_laser_list:
        lsr.y += 400 * dt
        if lsr.y > 950: # if the lasers y position is above 950 it gets removed from the laser list
            player_laser_list.remove(lsr)

def screen_shake():
    global shake_time, enemy_explode
    shake_time -= 0.1
    x = randint(-10, 10)
    if shake_time <= 0:
        bg_list[0].x = x
        bg_list[1].x = x
        shake_time += 0.11
    elif shake_time >= 0:
        bg_list[0].x = 0
        bg_list[1].x = 0
        enemy_explode = False

def enemy_hit(entity):
    global destroyed_enemies, score, next_wave, enemy_explode
    entity.hit_count += 1
    if entity.hit_count >= entity.MAX_HIT and player_is_alive:
        enemy_explode = True
        explosion_list.append(pyglet.sprite.Sprite(xplosion_anim, x=entity.x, y=entity.y, batch=main_batch))
        enemy_list.remove(entity)  # remove the enemy from enemy list when gets shot two times
        #entity.batch = None # remove the enemy from the main batch
        entity.delete() # here it works,  but in test_02_batcher_tester.py often gives error???
        explosion.play()
        destroyed_enemies += 1 # this only for displaying the stats
        next_wave += 1
        score += 1
        num_enemies_destroyed.text = str(destroyed_enemies)
        num_score.text = str(score)

def player_hit():
    global player_health, numb_player_health, player_flash
    player_health -= 1
    numb_player_health.text = str(player_health)
    player_flash = True
    if player_health <= 0:
        player.batch = None
        game_over()

def update_flash():
    global flash_time, player_flash
    flash_time -= 0.2
    player.color = (255, 0, 0)
    if flash_time <= 0:
        player.color = (255, 255, 255)
        flash_time = 1
        player_flash = False

def update_explosion():
    global explode_time
    explode_time -= 0.1
    if explode_time <= 0:
        for exp in explosion_list:
            explosion_list.remove(exp)
            exp.delete()
        explode_time += 2

def game_over():
    global player_is_alive
    player_is_alive = False
    if score > int(high_score):
        save_high_score('res/score.txt', score)

def bullet_collision(entity, bullet_list):
    for lsr in bullet_list:
        if lsr.x < entity.x + entity.width and lsr.x + lsr.width > entity.x \
                and lsr.y < entity.y + entity.height and lsr.height + lsr.y > entity.y:
            bullet_list.remove(lsr)  # remove the laser from laser list when colliding with an enemy
            return True

def update(dt):
    if game:
        player_move(player, dt)
        enemy_move(enemy_list, 30, dt)
        if fire:
            player_shoot(dt)
        update_player_shoot(dt)
        enemy_shoot(dt)
        update_enemy_shoot(dt)
        for entity in enemy_list:
            if bullet_collision(entity, player_laser_list):
                enemy_hit(entity)
        if bullet_collision(player, enemy_laser_list) and player_is_alive:
            player_hit()
        if player_flash:
            update_flash()
        update_explosion()
        enemy_spawn(dt)
        if enemy_explode:
            screen_shake()
    bg_move(dt)

if __name__ == "__main__":
    pyglet.clock.schedule_interval(update, 1.0/60)
    pyglet.app.run()
<file_sep># import the turtle module so we can use all the neat code it contains
from turtle import Turtle, Screen

KEY_REPEAT_RATE = 20  # in milliseconds

# Create a variable `tina` that is a Turtle() object. Set shape to 'turtle'
tina = Turtle('turtle')

# Create a variable `screen`, a Screen() object, that will handle keys
screen = Screen()

# Define functions for each arrow key
def go_left():
    tina.left(7)
    if repeating:
        screen.ontimer(go_left, KEY_REPEAT_RATE)

def go_right():
    tina.right(7)
    if repeating:
        screen.ontimer(go_right, KEY_REPEAT_RATE)

def go_forward():
    tina.forward(10)
    if repeating:
        screen.ontimer(go_forward, KEY_REPEAT_RATE)

def go_backward():
    tina.backward(10)
    if repeating:
        screen.ontimer(go_backward, KEY_REPEAT_RATE)

def start_repeat(func):
    global repeating

    repeating = True

    func()

def stop_repeat():
    global repeating

    repeating = False

repeating = False

# Tell the program which functions go with which keys
screen.onkeypress(lambda: start_repeat(go_left), 'Left')
screen.onkeyrelease(stop_repeat, 'Left')

screen.onkeypress(lambda: start_repeat(go_right), 'Right')
screen.onkeyrelease(stop_repeat, 'Right')

screen.onkeypress(lambda: start_repeat(go_forward), 'Up')
screen.onkeyrelease(stop_repeat, 'Up')

screen.onkeypress(lambda: start_repeat(go_backward), 'Down')
screen.onkeyrelease(stop_repeat, 'Down')

# Tell the screen to listen for key presses
screen.listen()

screen.mainloop()<file_sep>"""
Python: Bouncing Ball Animation with Real-World Physics!!
video: https://www.youtube.com/watch?v=9LWpCtbSvG4

Analyst Rising 1.36K subscribers

In this tutorial I will be showing you how to code/programme
a bouncing ball, with REAL-WORLD PHYSICS, in Python.
This is one of many great python tutorials that should
get you well on your way to programming some amazing stuff!!
"""

import pygame
from pygame.locals import *
import time

pygame.init()
#---------game constants variables-------------
display_width = 300
display_height = 400
#RGB color constants
black = (0,0,0)
white = (255,255,255)
red   = (255,0,0)
green = (0,255,0)
blue  = (0,0,255)

dt_ms = 100
frame_speed_sec = (1/dt_ms)*1000

#------------------------------------------------------
#create main display window
gameDisplay = pygame.display.set_mode((display_width,display_height))
#set main display window title
pygame.display.set_caption('gameDisplay')

clock = pygame.time.Clock()

#----------------------FUNCTIONS-------------------------
def fps_display(value):
	#1. set type font
	font = pygame.font.SysFont(None,25)
	#2. render it
	text = font.render("FPS count: " + str(value),True,white)
	#3. blit = draw
	gameDisplay.blit(text,(0,0))

class Particle(object):
	def __init__(self, x, y, size, colour, thickness):
	    self.x = x
	    self.y = y
	    self.size = size
	    self.colour = colour
	    self.thickness = thickness

	def display(self):
		#pygame.draw.
		pygame.draw.circle(gameDisplay, self.colour, (self.x, self.y), self.size, self.thickness)

def game_loop(frame_speed):
	#main game loop
	run = True
	counter = 0
	velocity_x = 00
	velocity_y = 10
	gravity = 0.1
	friction = 0.05
	speed=0
	dx = 10
	dy = 10
	while run:
		counter += 1
		#-----------check for pressed keys----------------
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				run = False
			if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
				run = False
		#-------------------------------------------------

		# CONSTRAINTS X RIGHT SIDE
		if particle.x - particle.size <= 0:
			#dx = -dx
			dx *= -(dx*friction)

		# CONSTRAINTS X LEFT SIDE
		if particle.size + particle.x >= display_width:
			#dx = -dx
			dx *= -(dx*friction)

		#CONSTRAINTS Y UP
		if particle.y - particle.size <= 0:
			dy *= -1

		#CONSTRAINTS Y DOWN
		if particle.size + particle.y >= display_height:
			dy *= -1

		#check if we are moving down
		if velocity_y < 0:
			velocity_y = velocity_y*(1-gravity)

		#if velocity_y > 0:
			#dy = velocity_y*(1+gravity)

		#dx = velocity_x
		print(f"{dx} dx")
		print(f"{dy} dy")
		particle.x += int(round(dx))
		particle.y += int(round(dy))

		print(velocity_y)
		#-------------------------------------------------
		gameDisplay.fill(black) # draw background
		#fps_display(counter)
		fps_display(dx)
		#speed_display()
		particle.display()			#draw particle ball
		pygame.display.update()		#update display
		clock.tick(frame_speed)	#set FPS update frequency


#---------------------------------------
#-----------initialization--------------
particle = Particle(x=150, y=50, size=30, colour=white, thickness=0)

#-------------main loop-----------------
game_loop(frame_speed_sec)
#---------------------------------------
#---------------------------------------<file_sep>from math import radians

from OpenGL.GL import *
from OpenGL.GLU import *

import pygame
from pygame.locals import *

from gameobjects.matrix44 import *
from gameobjects.vector3 import *

SCREEN_SIZE = (800, 600)

def resize(width, height):

    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(60.0, float(width)/height, .1, 1000.)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()


def init():

    glEnable(GL_DEPTH_TEST)

    glShadeModel(GL_FLAT)
    glClearColor(1.0, 1.0, 1.0, 0.0)

    glEnable(GL_COLOR_MATERIAL)

    glEnable(GL_LIGHTING)
    glEnable(GL_LIGHT0)
    glLight(GL_LIGHT0, GL_POSITION,  (0, 1, 1, 0))


class Cube(object):


    def __init__(self, position, color):

        self.position = position
        self.color = color

    # Cube information

    num_faces = 6

    vertices = [ (0.0, 0.0, 1.0),
                 (1.0, 0.0, 1.0),
                 (1.0, 1.0, 1.0),
                 (0.0, 1.0, 1.0),
                 (0.0, 0.0, 0.0),
                 (1.0, 0.0, 0.0),
                 (1.0, 1.0, 0.0),
                 (0.0, 1.0, 0.0) ]

    normals = [ (0.0, 0.0, +1.0),  # front
                (0.0, 0.0, -1.0),  # back
                (+1.0, 0.0, 0.0),  # right
                (-1.0, 0.0, 0.0),  # left
                (0.0, +1.0, 0.0),  # top
                (0.0, -1.0, 0.0) ] # bottom

    vertex_indices = [ (0, 1, 2, 3),  # front
                       (4, 5, 6, 7),  # back
                       (1, 5, 6, 2),  # right
                       (0, 4, 7, 3),  # left
                       (3, 2, 6, 7),  # top
                       (0, 1, 5, 4) ] # bottom

    def render(self):

        # Set the cube color, applies to all vertices till next call
        glColor( self.color )

        # Adjust all the vertices so that the cube is at self.position
        vertices = []
        for v in self.vertices:
            vertices.append( tuple(Vector3(v)+ self.position) )


        # Draw all 6 faces of the cube
        glBegin(GL_QUADS)

        for face_no in range(self.num_faces):

            glNormal3dv( self.normals[face_no] )

            v1, v2, v3, v4 = self.vertex_indices[face_no]

            glVertex( vertices[v1] )
            glVertex( vertices[v2] )
            glVertex( vertices[v3] )
            glVertex( vertices[v4] )

        glEnd()


class Map(object):

    def __init__(self):

        map_surface = pygame.image.load("map.png")
        map_surface.lock()

        w, h = map_surface.get_size()

        self.cubes = []

        # Create a cube for every non-white pixel
        for y in range(h):
            for x in range(w):

                r, g, b, a = map_surface.get_at((x, y))

                if (r, g, b) != (255, 255, 255):

                    gl_col = (r/255.0, g/255.0, b/255.0)
                    position = (float(x), 0.0, float(y))
                    cube = Cube( position, gl_col )
                    self.cubes.append(cube)


        map_surface.unlock()

        self.display_list = None

    def render(self):

        if self.display_list is None:

            # Create a display list
            self.display_list = glGenLists(1)
            glNewList(self.display_list, GL_COMPILE)

            # Draw the cubes
            for cube in self.cubes:
                cube.render()

            # End the display list
            glEndList()

        else:

            # Render the display list
            glCallList(self.display_list)


def run():

    pygame.init()
    screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|OPENGL|DOUBLEBUF)

    resize(*SCREEN_SIZE)
    init()

    clock = pygame.time.Clock()

    # This object renders the 'map'
    map = Map()

    # Camera transform matrix
    camera_matrix = Matrix44()
    camera_matrix.translate = (10.0, .6, 10.0)

    # Initialize speeds and directions
    rotation_direction = Vector3()
    rotation_speed = radians(90.0)
    movement_direction = Vector3()
    movement_speed = 5.0

    while True:

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                quit()
            if event.type == KEYUP and event.key == K_ESCAPE:
                pygame.quit()
                quit()

        # Clear the screen, and z-buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        time_passed = clock.tick()
        time_passed_seconds = time_passed / 1000.

        pressed = pygame.key.get_pressed()

        # Reset rotation and movement directions
        rotation_direction.set(0.0, 0.0, 0.0)
        movement_direction.set(0.0, 0.0, 0.0)

        # Modify direction vectors for key presses
        if pressed[K_LEFT]:
            rotation_direction.y = +1.0
        elif pressed[K_RIGHT]:
            rotation_direction.y = -1.0
        if pressed[K_UP]:
            rotation_direction.x = -1.0
        elif pressed[K_DOWN]:
            rotation_direction.x = +1.0
        if pressed[K_z]:
            rotation_direction.z = -1.0
        elif pressed[K_x]:
            rotation_direction.z = +1.0
        if pressed[K_q]:
            movement_direction.z = -1.0
        elif pressed[K_a]:
            movement_direction.z = +1.0

        # Calculate rotation matrix and multiply by camera matrix
        rotation = rotation_direction * rotation_speed * time_passed_seconds
        rotation_matrix = Matrix44.xyz_rotation(*rotation)
        camera_matrix *= rotation_matrix

        # Calcluate movment and add it to camera matrix translate
        heading = Vector3(camera_matrix.forward)
        movement = heading * movement_direction.z * movement_speed
        camera_matrix.translate += movement * time_passed_seconds

        # Upload the inverse camera matrix to OpenGL
        glLoadMatrixd(camera_matrix.get_inverse().to_opengl())

        # Light must be transformed as well
        glLight(GL_LIGHT0, GL_POSITION,  (0, 1.5, 1, 0))

        # Render the map
        map.render()


        # Show the screen
        pygame.display.flip()

if __name__ == "__main__":
    run()
<file_sep>"""
Jumping and variables
video: https://www.youtube.com/watch?v=2-DNswzCkqk&list=PLzMcBGfZo4-lp3jAExUCewBfMx3UZFkh5&index=2

1. constraing are where we can move
2. jumping
IF JUMPING: dont move left right
"""

import pygame
from pygame.locals import *

from rgb_color_dictionary import *

pygame.init()

#create window
win = pygame.display.set_mode((500,500))
#set windows title
pygame.display.set_caption("First Game")

#character variables
x = 50
y = 50
width = 40
height = 60
vel = 20

isJump = False
jumpCount = 10

#clock=pygame.time.Clock()
#main game loop
run = True
while run:

	pygame.time.delay(100) #this will be a clock for the game
	keys = {'left':False,'right':False, 'up':False, 'down':False}

	for event in pygame.event.get(): #check for all events that are happening
		if event.type == pygame.QUIT:
			run = False
		if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
			run = False

	vx = 0
	vy = 0
	keystate = pygame.key.get_pressed()
	#straight moves with screen constraints
	#cant move up
	if keystate[pygame.K_UP] and y > vel:
		vy = -vel
	#cant move down
	if keystate[pygame.K_DOWN] and y < 500 - height - vel:
		vy = vel

	if not isJump:
		#cant move off the left screen border
		if keystate[pygame.K_LEFT] and x > vel:
			vx = -vel
		#cant move off the right screen border
		if keystate[pygame.K_RIGHT] and x < 500 - width - vel:
			vx = vel

		#-----------------jump---------------
		if keystate[pygame.K_SPACE]:
			isJump = True
	else:
		if jumpCount >= -10: # we jump for 10 pixels
			neg = 1
			if jumpCount < 0: #when we get to the top of jump
				neg = -1
			y -= (jumpCount ** 2) * 0.5 * neg
			jumpCount -= 1
		else:
			isJump = False
			jumpCount = 10

	#diagonals must be slower for sq(2)= 1.414 pitagora
	if vx != 0 and vy != 0:
		vx /= 1.414
		vy /= 1.414

	x += vx
	y += vy

	#draw rectangle
	win.fill(BLACK)
	pygame.draw.rect(win,RED,(x,y,width,height))
	pygame.display.update()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 23:13:08 2020

@author: crtom
"""

import pygame as pg
from settings import *

vec = pg.math.Vector2

class Player(pg.sprite.Sprite):
    def __init__(self, game, x, y):
       
        # so player can acces all sprites in the game
        self.game = game
        self.groups = game.all_sprites
        
        # 1.) sprite class default override:
        #Call the parent class (Sprite) constructor
        pg.sprite.Sprite.__init__(self, self.groups)

        # 2.) sprite class default override:
        # tile based game - player is only one tile large
        
        # self.image = pg.Surface((TILESIZE, TILESIZE)) # YELLOW BLOCK SPRITE
        # self.image.fill(YELLOW)
        self.image = game.player_img
        # 3.) sprite class default override:
        # Fetch the rectangle object that has the dimensions of the image
        # Update the position of this object by setting the values of rect.x and rect.y       
        self.rect = self.image.get_rect()
        
        # CUSTOM ATTRIBUTES
        #self.dt = 0
        self.vel = vec(0, 0)
        self.pos = vec(x, y) * TILESIZE
        self.rot = 0
    
    def get_keys(self):
        self.vel = vec(0, 0)
        self.rot_speed = 0
        
        keys = pg.key.get_pressed()
        
        if keys[pg.K_LEFT] or keys[pg.K_a]:
            # self.player.move(dx=-1)
            self.vel.x = -PLAYER_SPEED
        elif keys[pg.K_RIGHT] or keys[pg.K_d]: # IF ENABLES DIAG
            self.vel.x = PLAYER_SPEED
        if keys[pg.K_UP] or keys[pg.K_w]: # IF ENABLES DIAG
            self.vel.y = -PLAYER_SPEED
        if keys[pg.K_DOWN] or keys[pg.K_s]: # IF ENABLES DIAG
            self.vel.y = PLAYER_SPEED
        
        # DIAGONAL PITAGORA
        if self.vel.x != 0 and self.vel.y != 0:
            self.vel *= 0.7071
    
    def collide_with_walls(self, direction):
        # x collision check
        if direction == 'x':
            hits = pg.sprite.spritecollide(self, self.game.walls, False) # false= dont delete the wall
            
            if hits:
                # sprite was moving to the right
                # we need to put the sprite to the left edge of the wall
                if self.vel.x > 0: 
                    self.pos.x = hits[0].rect.left - self.rect.width
                # sprite was moving to the left
                # we need to put the sprite to the right edge of the wall
                if self.vel.x < 0:
                    self.pos.x = hits[0].rect.right #- self.rect.width    
                
                # we run into the wall, x velocity = 0
                self.vel.x = 0
                # update new position
                self.rect.x = self.pos.x

        if direction == 'y':
            hits = pg.sprite.spritecollide(self, self.game.walls, False) # false= dont delete the wall
            
            if hits:
                # sprite was moving down
                # we need to put the sprite to the top of the wall
                if self.vel.y > 0: 
                    self.pos.y = hits[0].rect.top - self.rect.height
                # sprite was moving to the top
                # we need to put the sprite to the bottom edge of the wall
                if self.vel.y < 0:
                    self.pos.y = hits[0].rect.bottom #- self.rect.width    
                
                # we run into the wall, x velocity = 0
                self.vel.y = 0
                # update new position
                self.rect.y = self.pos.y
                    
    def update(self):
        self.get_keys()

        # this will make movement independant of frame rate
        self.pos += self.vel * self.game.dt # get dt from game object
        
        self.rect.x = self.pos.x
        self.collide_with_walls('x')
        
        self.rect.y = self.pos.y
        self.collide_with_walls('y')
        # check if sprite and a group collides
        # # if hits a wall dont move
        # # redo movement position
        # if pg.sprite.spritecollideany(self, self.game.walls):
        #     self.x -= self.vx * self.game.dt # get dt from game object
        #     self.y -= self.vy * self.game.dt # get dt from game object
        #     # self.rect.x = self.x * TILESIZE
        #     # self.rect.y = self.y * TILESIZE
        #     self.rect.topleft = (self.x, self.y)

class Wall(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        
        # so player can acces all sprites in the game
        # member of all sprites group
        # member of all walls group
        self.groups = game.all_sprites, game.walls
        
        pg.sprite.Sprite.__init__(self, self.groups)
        
        self.game = game
        # tile based game - player is only one tile large
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y
        
        self.rect.x = x * TILESIZE
        self.rect.y = y * TILESIZE<file_sep>import turtle
import time
import random
import winsound
import os
import winsound
import tkinter as tk

def key(event):
	"""shows key or tk code for the key"""
	if event.keysym == 'Escape':
		root.destroy()

	if event.char == event.keysym:
		 # normal number and letter characters
		print( 'Normal Key %r' % event.char )
	elif len(event.char) == 1:
		# charcters like []/.,><#$ also Return and ctrl/key
		print( 'Punctuation Key %r (%r)' % (event.keysym, event.char) )
	else:
		# f1 to f12, shift keys, caps lock, Home, End, Delete ...
		print( 'Special Key %r' % event.keysym )

root = tk.Tk()
print( "Press a key (Escape key to exit):" )
root.bind_all('<Key>', key)

# don't show the tk window
root.withdraw()
root.mainloop()