lewashby 56 Junior Poster

I have my laptop split between Windows Vista and Ubuntu Linux. I recently upgraded Ubuntu and it somehow fraked up my Windows and now it will not load. I need to fix Windows so I can get back to my iTunes but I don't want to do anything that will mess up my Ubuntu either. Any suggestions?

lewashby 56 Junior Poster

movies = [
"The Holy Grail", 1975, "Terry Jones & Terry Gilliam", 91,
["Graham Chapman",
["Michael Palin", "John Cleese", "Terry Gilliam", "Eric Idle", "Terry Jones"]]]

print(movies[4][1][3] = Eric Idle

Could Someone please explain how it counts from the outer loops through the inner loops With the number 4, 1, & 3? Once the first 4 lands on "Graham Chapman", does Graham then count from Graham starting at 0? Thanks for any and all replies.

lewashby 56 Junior Poster

Can someone please help me understand Networks, Broadcast, and Subnets? I'M taking a course at oreillyschools and I'M having a terrible time understanding the lesson. Thanks.

lewashby 56 Junior Poster

In the following two functions, why is it that the first one can see the outside variable but the second one can not?

name = 'Jack'

def say_hello():
    print ('Hello ' + name + '!')

def change_name(new_name):
    name = new_name
lewashby 56 Junior Poster

I see that Rhythembox has been updated along with the new Ubuntu 10.x. Does anyone know if there are any plans to make Rhythembox writable to an iPod? I know about song bird but it doesn't work with my Ubuntu and I hard they were going to stop Linux support anyway. Thanks.

lewashby 56 Junior Poster

In the following program I'M getting an error with the blit function. The error is invalid destination position.

background_image_filename = 'sushiplate.jpg'
sprite_image_filename = 'fugu.png'

import pygame
from pygame.locals import *
from sys import exit
from gameobjects import Vectory2

pygame.init()

screen = pygame.display.set_mode((640, 480), 0, 32)
background = pygame.image.load(sprite_image_filename).convert_alpha()
sprite = pygame.image.load(sprite_image_filename).convert_alpha()

clock = pygame.time.Clock()

sprite_pos = Vectory2(200, 150)
sprite_speed = 300.

while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
            
    pressed_key = pygame.key.get_pressed()
    
    key_direction = Vectory2(1, 0)
    
    if pressed_key[K_LEFT]:
        key_direction.x = -1
    elif pressed_key[K_RIGHT]:
        key_direction.x = + 1
    if pressed_key[K_UP]:
        key_direction.y = - 1
    elif pressed_key[K_DOWN]:
        key_direction.y = + 1
        
    key_direction.normalize()
    
    screen.blit(background, (0,0))
    screen.blit(sprite, sprite_pos)
    
    time_passed = clock.tick(30)
    time_passed_seconds = time_passed / 1000.0
    
    sprite_pos += key_direction * sprite_speed * time_passed_seconds
    
    pygame.display.update()

gameobjects.py

import math

class Vectory2(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)
    
    @staticmethod
    def from_points(P1, P2):
        return Vectory2(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
        
    # rhs stands for right hand side
    def __add__(self, rhs):
        return Vectory2(self.x + rhs.x, self.y + rhs.y)
lewashby 56 Junior Poster

ZeroDivisionError: float division
File "/home/developer/Projects/Beginning Game Development/Chapter 4/keymovement.py", line 38, in <module>
key_direction.normalize()
File "/home/developer/Projects/Beginning Game Development/Chapter 4/gameobjects.py", line 21, in normalize
self.x /= magnitude

lewashby 56 Junior Poster

I'M getting an error in the following program on line 38 to a function call. The function is in the gameobjects module and the there's an error there as well on line 21. Here's the code.

Code:

background_image_filename = 'sushiplate.jpg'
sprite_image_filename = 'fugu.png'

import pygame
from pygame.locals import *
from sys import exit
from gameobjects import Vectory2

pygame.init()

screen = pygame.display.set_mode((640, 480), 0, 32)
background = pygame.image.load(sprite_image_filename).convert_alpha()

clock = pygame.time.Clock()

sprite_pos = Vectory2(200, 150)
sprite_speed = 300.

while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
            
    pressed_key = pygame.key.get_pressed()
    
    key_direction = Vectory2(0, 0)
    
    if pressed_key[K_LEFT]:
        key_direction.x = -1
    elif pressed_key[K_RIGHT]:
        key_direction.x = + 1
    if pressed_key[K_UP]:
        key_direction.y = - 1
    elif pressed_key[K_DOWN]:
        key_direction.y = + 1
        
    key_direction.normalize()
    
    screen.blit(background, (0,0))
    screen.blit(sprite, sprite_pos)
    
    time_passed = clock.tick(30)
    time_passed_seconds = time_passed / 1000.0
    
    sprite_pos += key_direction * sprite_speed * time_passed_seconds
    
    pygame.display.update()

gameobjects.py

import math

class Vectory2(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)
    
    @staticmethod
    def from_points(P1, P2):
        return Vectory2(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
        
    # rhs stands for right hand side
    def __add__(self, rhs):
        return Vectory2(self.x + rhs.x, self.y + rhs.y)

Thanks for any and all help.

lewashby 56 Junior Poster
import pygame
from pygame.locals import *
from sys import exit

pygame.init()

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

font = pygame.font.SysFont('arial', 32)
font_height = font.get_linesize()

while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
            
    screen.fill((255, 255, 255))
    
    pressed_key_text = []
    pressed_keys = pygame.key.get_pressed()
    y = font_height
    
    for key_constant, pressed in enumerate(pressed_keys):
        if pressed:
            key_name = pygame.key.name(key_constant)
            text_surface = font.render(key_name + " pressed", True, (0,0,0))
            screen.blit(text_surface, (8, y))
            y += font_height
            
    pygame.display.update()

In the code above, how does a for loop use two variables? I know this is probably really simples but I've always just used one so I'M not sure how it works.

lewashby 56 Junior Poster

Minimal Server

import socket

s = socket.socket()

host = socket.gethostname()

port = 1234
s.bind((host, port))

s.listen(5)

while True:
    c, addr = s.accept()
    print 'Got connection from', addr
    c.send('Thank you for connecting')
    c.close()

Minimal Client

import socket

s = socket.socket()

host = socket.gethostname()
port = 1234

s.connect((hos

t, port))
print s.recv(1024)

These are the two examples given to me from the python book I'M currently reading in the network chapter. The problem is, I still have know idea how this would work. I don't image having the minimal server .py file floating around somewhere on a server would make it work. I have no idea how servers work but I'M expected to understand this from a book that teaches python. Please help, thanks.

lewashby 56 Junior Poster

I recently upgraded my Ubuntu from 9.10 to 10.04 and now it's messed up my Windows Vista partition. When I try to load Windows it boots to a strange login menu with low resolution. It then takes me to a screen with options like Repair/Fix, Recovery, Complete Recovery... I'll click Repair and and then it will say No errors found, Shut down, Restart. Please help, thanks. And if all you're going to say is "why are you using Windows at all anyway", please don't leave a response at all.

lewashby 56 Junior Poster

My dad got a new Dell lap-top with Windows Vista less than a year ago. Yesterday all the sudden it's wireless network adapters quit working. I went to investigation and found that it wasn't finding any networks, further investigation found that it was turned off. Now on this computer there is no switch on the outside to turn it on or off. And I was unable to find how to turn it on in Windows. I dug deep into all the network setting and the best I could do was to find the icons for the surrounding connections. But when I would click connect it would pop up at the bottom right of the screen and show that there are no connections available. Even though this computer is less than a year old Dell still wants about $200 to fix it. Any help or suggestions would be greatly appreciated. Thanks.

lewashby 56 Junior Poster

32

lewashby 56 Junior Poster

I've just upgraded from Ubuntu 9.10 to 10.04 and now firefox will not play videos on youtube. Please help, thanks.

lewashby 56 Junior Poster
background_image_filename = 'sushiplate.jpg'
sprite_image_filename = 'fugu.png'

# imports
import pygame
from pygame.locals import *
from sys import exit
from gameobjects import Vectory2

pygame.init()

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

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

clock = pygame.time.Clock()

position = Vectory2(100.0, 100.0)
speed = 250.
heading = Vectory2

while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
        if event.type == MOUSEBUTTONDOWN:
            destinatoin = Vectory2(*event.pos) - Vectory2(*sprite.get_size()) / 2
            heading = Vectory2.from_points(position, destinatoin)
            heading.normalize()
            
    screen.blit(background, (0, 0))
    screen.blit(sprite, position)
    
    time_passed = clock.tick()
    time_passed_seconds = time_passed / 1000.0
    
    distance_moved = time_passed_seconds = speed
    position += heading * distance_moved
    
    pygame.display.update()

In the code above I'M getting this error but don't know what's wrong. I've typed it just how it shows it in my book.

TypeError: invalid destination position for blit
File "/home/developer/Projects/Beginning Game Development/Chapter 4/ch5-last.py", line 34, in <module>
screen.blit(sprite, position)

lewashby 56 Junior Poster

I figured out how to play all my iTunes music on my Windows partition through rhythembox but each time I have to pretend I'M going to reset my music directory. When I click on the computer hard drive a password prompt comes up. After tying my password all my songs then load up and I can click cancel without proceeding any further. Is there a way that I can tell rhythembox to start up with these permissions already allowed? Thanks. Oh, one more thing, how is it that I am able to play protect songs from my iTunes library?

lewashby 56 Junior Poster

I have another post entitled 'understanding wxPython' in which my code runs but fails to build the scroll bars as shown by my python programming book. Note that the code in the book is running on Windows and mine is running on Ubuntu.

lewashby 56 Junior Poster
import wx

# create window
app = wx.App()
win = wx.Frame(None, title = "Simple Editor", size = (410, 335))
win.Show()

# create buttons
loadButton = wx.Button(win, label = 'Open',
                       pos = (225, 5), size = (80, 25))
saveButton = wx.Button(win, label = 'Save',
                       pos = (315, 5), size = (80, 25))

fileName = wx.TextCtrl(win, pos = (5, 5), size = (210, 25))

contents = wx.TextCtrl(win, pos = (5, 35), size = (390, 260),
                       style = wx.TE_MULTILINE | wx.HSCROLL)

app.MainLoop()

In the program above, is the 'win' argument telling the Button and TextCtrl classes that they inherit from the Frame class? If not, what are they, what do they, and how do they work? Thanks.

lewashby 56 Junior Poster

Program 1

import math

class Vectory2(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)
    
    @classmethod
    def from_points(cls, P1, P2):
        return cls( 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
        
A = (10.0, 20.0)
B = (30.0, 35.0)
AB = Vectory2.from_points(A, B)

print "Vectory AB is", AB
print "Magnitude of Vector AB is", AB.get_magnitude()
AB.normalize()
print "Vector AB normalized is", AB

Program 2

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)
    
    @classmethod
    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
        
    # rhs stands for Right Hand Side
    def __add__(self, rhs):
        return Vector2(self.x + rhs.x, self.y + rhs.y)
    
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)

AC = Vector2.from_points(A, C)

print "Vector AC is", AC

AC = AB + BC
print "AB + BC is ", AC

IN the two programs above I'M having trouble understanding the return values of the from_points functions.

In program 1 they are returned by an extra argument calles cls put in program to they are returned directly with the class name. Could someone please …

lewashby 56 Junior Poster

One more time, I've never seen dot notation in an argument.

rhs is a name author of this code have choose.
You can can use whatever name you want when it comes to method/function arguments.
__add__ in this class will have an other meaing that normal __add__.
AB + BC call Vector2 and method def __add__(self, rhs)

# rhs stands for power of
def foo(rhs):
    a = 5
    b = a ** rhs
    return b

print foo(5) #3125

Or.
# my_car stands for power of
def foo(my_car):
    a = 5
    b = a ** my_car
    return b

print foo(5) #3125

So you see that you can use stupid name that confuse.

lewashby 56 Junior Poster

Thanks, but what the hell is rhs.x and .y?

@classmethod
    def from_points(cls, P1, P2):
        return Vector2(P2[0] - P1[0], P2[1] - P1[1])

http://docs.python.org/library/functions.html?highlight=classmethod#classmethod

>>> x = 5
>>> y = 6
>>> x + y
11
>>> dir(x)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']

So a simple explanation is to say that everything in Python is an object.
So x is an object and has method,and has a special method called __add__.
When + is used __add__ get called.
We can write it like this.

>>> x = 5
>>> y = 6
>>> x.__add__(y)
11
>>> 
>>> x.__add__.__doc__
'x.__add__(y) <==> x+y'
>>>

So we can say that special methods two underscore __something__ work in the background an get call when we as an example use * - + /.

lewashby 56 Junior Poster
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)
    
    @classmethod
    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
        
    # rhs stands for Right Hand Side
    def __add__(self, rhs):
        return Vector2(self.x + rhs.x, self.y + rhs.y)
    
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)

AC = Vector2.from_points(A, C)

print "Vector AC is", AC

AC = AB + BC
print "AB + BC is ", AC

In the code above I'M getting an error at the from_points function. It telling that it need 2 arguments but I've given it three. I can't find a third. There was also a program similar to this one where the from_points function returned an extra argument in it parameter called cls, why doesn't this one need what?
One last thing, could someone please explain the __add__ constructor to me? Thanks.

lewashby 56 Junior Poster

I'M reading the book "Beginning Game Development with Python and Pygame". The book showed me how to calculate the distance between two points using vectors. It first explained that you just subtract the values in the first point from the second. But just page or two pages later it says that in order to calculate the distance I need to get the square root of x squared + y squared. math.sqrt(self.x**2 + self.y**2)
The book seem to be describing the same thing in two completely different ways. Could someone please clarify this for me? Thanks.

lewashby 56 Junior Poster

If the argument cls is the constructor then I would assume that it is through cls that from_points class methods gets it's x & y arguments from the constructor, being that is what cls represents. But then from_points is called directly via AB = Vector2.from_points(A, B). Which should also call __init__ at that time as well. So does from_points get the x & y values from it parameter cls or from the call in Vectory2.from_points(A, B).
Sorry if slowness, I am somewhat dyslexic.

lewashby 56 Junior Poster
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)
    
    @classmethod
    def from_points(cls, P1, P2):
        return cls( 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

I'M having trouble understanding some of this code. First of all, is the classmethod the same thing as a static method? At what point in this program is it actually called. I also thought I remembered there was another way to right class methods.
What is the parameter cls?
Last but not least, what produces the final output? Is it the line print AB or the __str__ method?

Thanks for any and all replies.

lewashby 56 Junior Poster
background_image_filename = 'sushiplate.jpg'
sprice_image_filename = 'fugu.png'

import pygame
from pygame.locals import *
from sys import exit

pygame.init()

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

background = pygame.image.load(background_image_filename).convert()
sprite = pygame.image.load(sprice_image_filename)

# our clock object
clock = pygame.time.Clock()

x1 = 0.
x2 = 0.

# speed in pixels per second
speed = 250.

frame_no = 0

while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
            
    screen.blit(background, (0, 0))
    screen.blit(sprite, (x1, 50))
    screen.blit(sprite, (x2, 250))
    
    time_passed = clock.tick(30)
    time_passed_seconds = time_passed / 1000.0
    
    distance_moved = time_passed_seconds * speed
    x1 += distance_moved
    
    if (frame_no % 5) == 0:
        distance_moved = time_passed_seconds * speed
        x2 += distance_moved * 5
        
    # if the image goes of the end of the screen, move it back
    if x1 > 640.:
        x1 -= 640.
    if x2 > 640.:
        x2 -= 640.
        
    pygame.display.update()
    frame_no += 1

Could someone please explain to me what going on in the if statement. I don't understand why there is a duplicate line of code in the if statement that was also just a few lines back. The variable frame_no is also getting me. It's already 0 so the remainder of 0 \ 5 is always going to be 0. Thanks for any and all replies.

lewashby 56 Junior Poster

I'M reading the book "Simply SQL" and I need to use the files for the book. It was suggested to be to use postgreSQL and now I've got it up and running on my Ubuntu machine. But I'M having a little bit of trouble getting started. When I first start postgre I have to click on mydb database to the left and then right-click on connected to the right and click connect. Once I've done this I was told I need to click on the icon that looks like a little piece of paper that says SQL on it and a pencil writing on it, so tha'st what I've done. Once I click on that and select the directory for the sql files for the book I have to open them one at a time and there are 50. The problem is, how do I know they've been loaded into my database and will be there next time I start postgresql? Where can I see them? Thanks.

lewashby 56 Junior Poster

Thanks but I'M not trying to find another way to do it. I just want to know how that's possible.

lewashby 56 Junior Poster
class FooBar:
     def __init__(self, value = 42):
         self.somevar = value

f = FooBar('This is a constructor argument')
f.somevar

This is a constructor argument

How can the parameter value know what kind of data it's going to be given? Int, float, string, etc? thanks.

lewashby 56 Junior Poster

I click that icon/button, click on each .sql file and click open, save, and then repeat until I have them all loaded into postresql, is that right? thanks.

Hi

great!

click on the SQL icon in the tool bar. the icon looks like a small magnifying glass or sometimes like a piece of paper with a pen (depending on the versions).

I wish you good luck

-- tesu

lewashby 56 Junior Poster

I just got postgresql & pgAdmin III up and running. I'M trying to start the book "Simply SQL" so how do I go about getting to .sql files for the book into pgAdmin? Thanks for any and all replies.

lewashby 56 Junior Poster
+--------------+------+------------------------------------+-------+
| ProductCode  | Qty  | Title                              | Price |
+--------------+------+------------------------------------+-------+
| relationaldb | NULL | The Relational Database Dictionary | 14.99 | 
| artofsql     |   50 | The Art of SQL                     | 44.99 | 
| databaseid   |    0 | Database in Depth                  | 29.95 | 
| mysqlspp     |    5 | MySQL Stored Procedure Programming | 44.99 | 
| sqlhks       |   32 | SQL Hacks                          | 29.99 | 
| sqltuning    |  105 | SQL Tuning                         | 39.95 | 
+--------------+------+------------------------------------+-------+

The table above was selected from the following select statement.

mysql> SELECT P.ProductCode, MAX(I.QuantityInStock) as Qty, P.Title, P.Price
FROM Products as P 
LEFT JOIN Inventory as I on (P.ProductCode = I.ProductCode) 
GROUP BY I.ProductCode, P.Title, P.Price;

What is the max function and the group by statements really doing?

lewashby 56 Junior Poster

I'M new to SQL and I'M reading the book "Simply SQL". I'M running Ubuntu Linux and I downloaded MySQL Workbench. I also downloaded the source .sql files for the book. I need some help getting started. How do I get the files into Workbench so I can follow along with the book? There are a lot of options upon start up. New Connection, Create New EER, Create EER Model form Existing Database, New Server Instance, etc. Thanks for any and all replies.

lewashby 56 Junior Poster

I just got a new book on sql. So what software do I need to get started to and play around with these statements and load the querys supplied by the book. Thanks.

By the way I'M running Ubuntu Linux

lewashby 56 Junior Poster

To help increase sales, your management decides to give customers a one-time bonus.

Here are the credit rules:

for 1-15 credits, add 1 credit
for 16-30 credits, add 2 credits
for 31+ credits, add 10% and round up (10% of 35 is 3.5, rounded up to 4)

Write an update statement that uses those rules to add credit to a customer's account.

Save your query as dba1lesson7project2.sql and then hand it in.

This is my project and below is what I have so far but I'M guessing that I've missed the mark by a long shot. Could you please steer me in the right direction? Thanks. The table is CustomerAccounts and the column is CurrentCredit.

update CustomerAccounts
set CurrentCredit = CurrentCredit + 1
where CurrentCredit > 1 and <= 15,

set CurrentCredit = CurrentCredit + 2
where CurrentCredit >15 and <= 30,

set CurrentCredit = CurrentCredit + 10%
where CurrentCredit >= 31;
lewashby 56 Junior Poster

According to the book I'M reading clock = pygame.time.Clock() creates a new clock object. But when I took a look at the time module, I didn't find a class by the name of Clock so I could I have an object? All I found was a function and it was clock with a lower case c. Thanks.

lewashby 56 Junior Poster

Yes it did, thanks.

The 'blit' loads a image object to the window surface.

In your example 'blit' loads the 'background' image to the window starting at cordinates 0 in x and 0 in y.

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

The second 'blit' loads the 'sprite' image to the screen, with a fixed cordinate of 100 in 'y', and uses a variable 'x' to define the cordinate on x, that is incremented by 10 every cycle.

screen.blit(sprite, (x, 100))
x += 10

Hope it helps,

Cheers and Happy coding

lewashby 56 Junior Poster
background_image_filename = "sushiplate.jpg"
sprite_image_filename = 'fugu.png'

import pygame
from pygame.locals import *
from sys import exit

pygame.init()

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

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

# The x coordinate of our sprite
x = 0.

while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
        
        screen.blit(background, (0, 0))
        screen.blit(sprite, (x, 100))
        
        x += 10.
        
        # If the image goes off the end of the screen, move it back
        if x > 640.:
            x -= 640.
            
        pygame.display.update()

In the above code I'M trying to understand the two blit lines. I was unable to simply click go to definition. When I searched the pygame documentation I found blit belonging to the Surface module. But I'M trying to understand how it's using the parameters (x, 100). I couldn't find an example or a list of how it works in the pygame documentation. Thanks.

lewashby 56 Junior Poster

The creators of the pygame module expect its users to be somewhat familiar with the basics of Python.

I thought I was. Perhaps I have jumped the gun with pygame.

lewashby 56 Junior Poster
import pygame
from pygame.locals import *
from sys import exit
from random import *

pygame.init()

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

while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
            
    random_color = (randint(0, 255), randint(0, 255), randint(0, 255))
    random_pos = (randint(0, 639), randint(0, 479))
    random_radius = randint(1,200)
    
    pygame.draw.circle(screen, random_color, random_pos, random_radius)
    
    pygame.display.update()

I lookup the the pygame circle function and found it needed five arguments, not four a listed here. And how am I to know of what data type these arguments should be? There is the pygame circle function.

def circle():
  """ pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect
  draw a circle around a point """
  pass
lewashby 56 Junior Poster

Thanks everyone. Snippsat, what if you want them with a different number or arguments?

lewashby 56 Junior Poster
import pygame
from pygame.locals import *
from sys import exit

from random import *

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

while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
            
    screen.lock()
    
    for count in range(10):
        random_color = (randint(0, 255), randint(0, 255), randint(0, 255))
        random_pos = (randint(0, 639), randint(0, 479))
        random_size = (639-randint(random_pos[0], 639), 479-randint(random_pos[1], 479))
        
        pygame.draw.rect(screen, random_color, Rect(random_pos, random_size))
    screen.unlock()
    
    pygame.display.update()

In the above code, why are the three lines following the second for loop encased in parentheses? And what is the last of those three lines.(639-randint? How did they just slap a number and a dash right in front of a function. Thanks for any and all replies.

On a side note, why doesn't python support function, method, and constructor overloading? And what does it do to compensate?

lewashby 56 Junior Poster
import pygame
from pygame.locals import *
from sys import exit
from random import randint

pygame.init()

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

while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
            
        rand_col = (randint(0, 255), randint(0, 255), randint(0, 255))
        
        for _ in xrange(100):
            rand_pos = (randint(0, 630), randint(0, 479))
            screen.set_at(rand_pos, rand_col)
            
        pygame.display.update()

In the above code, what on earth is the little underscore doing in that for loop?
for _

Also, what does xrange do? I'M pretty sure that's a simple one but I can't remember. Thanks.

lewashby 56 Junior Poster

I'M learning python and I can write very small simple programs with Tkinter or play sound through pygame. I've just started the book "Beginning Game Development with Python and Pygame". I'M in the earlier part of the book and I've just been given the program below. The thing is, even though I may know some basics, I find the following code to be intimidating to say the least. Am I over my head or is this expected at this level? Thanks.

import pygame
from pygame.locals import *
from sys import exit

pygame.init()

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

# create images with smooth gradients
def create_scales(height):
    red_scale_surface = pygame.surface.Surface((640, height))
    green_scale_surface = pygame.surface.Surface((640, height))
    blue_scale_surface = pygame.surface.Surface((640, height))
    
    for x in range(640):
        c = int((x/639.)*255.)
        red = (c, 0, 0)
        green = (0, c, 0)
        blue = (0, 0, c)
        line_rect = Rect(x, 0, 1, height)
        
        pygame.draw.rect(red_scale_surface, red, line_rect)
        pygame.draw.rect(green_scale_surface, green, line_rect)
        pygame.draw.rect(blue_scale_surface, blue, line_rect)
    return red_scale_surface, green_scale_surface, blue_scale_surface
red_scale, green_scale, blue_scale = create_scales(80)

color = [127, 127, 127]

while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
            
    screen.fill((0, 0, 0))
    
    # Draw the scales to the screen
    screen.blit(red_scale, (0, 00))
    screen.blit(green_scale, (0, 80))
    screen.blit(blue_scale, (0, 160))
    
    x, y = pygame.mouse.get_pos()
    
    # If the mouse was pressed on the sliders, adjust the color component
    if pygame.mouse.get_pressed()[0]:
        for component in range(3):
            if y > component * 80 and y < (component + 1) * 80:
                color[component] = int((x/638.)*255.)
            
            pygame.display.set_caption("Pygame Color Test = " + str(tuple(color)))
            
            # Draw a …
lewashby 56 Junior Poster

Could someone please tell me why this code will not close my app when the [X] at top right corner is clicked?

def shutdown():
        track.stop()
        app.destroy()
    
app.protocol("WM_DELETE_WINDOW", shutdown)

If you want to see the whole code it's on an earlier post called "Tkinter Scale".
Thanks.

lewashby 56 Junior Poster

I was a good one. But the first Half-Life was better. I still believe it's the best game ever made.

lewashby 56 Junior Poster

file = hfmix2.py
error is on line 3

# imports
from Tkinter import *
from sound_panel2 import *
import pygame.mixer

# create gui
app = Tk()
app.title("Head First Mix")

# create mixder
mixer = pygame.mixer
mixer.init()

# call functions
panel1 = SoundPanel(app, mixer, "50459_M_RED_Nephlimizer.wav")
panel1.pack()
panel1 = SoundPanel(app, mixer, "49119_M_RED_HardBouncer.wav")
panel1.pack()

def shutdown():
        track.stop()
        app.destroy()
    
app.protocol("WM_DELETE_WINDOW", shutdown)
app.mainloop()

file = sound_panel2.py
error is on line 19

# this is a module

# imports
from Tkinter import *
import pygame.mixer

# create class
class SoundPanel(Frame):
    def __init__(self, app, mixer, sound_file):
        Frame.__init__(self, app)
        self.track = mixer.Sound(sound_file)
        self.track_playing = IntVar()
        
        track_button = Checkbutton(self, variable = self.track_playing,
                                   command = self.track_toggle, text = sound_file)
        track_button.pack(side = LEFT)
        self.volume = DoubleVar()
        self.volume.set(self.track.get_volume())
        volume_scale = Scale(self, variable = self.volume, from_ = 0.0, to 1.0,
                             resolution = 0.1, command = self.change_volume,
                             label = "Volume", orient = HORIZONTAL)
        volume_scale.pack(side = RIGHT)
        
    def track_toggle(self):
        if self.track_playing.get() == 1:
            self.track.play(loops = -1)
        else:
            self.track.stop()
            
    def change_volume(self, v):
        self.track.set_volume(sel.volume.get())
lewashby 56 Junior Poster

I'M currently tacking Database Administration at http://www.oreillyschool.com/certificates/

I want to get into the IT community and out of this factory work. Could some more experienced people please take a look at that site and tell me if my certificate or any of them are worth taking, both in terms of quality as well as the likely hood of getting hired. These type of online classes, Amazon.com, and Book-A-Million are pretty much the only type of educations that is do able for me. So, is it worth it? Thanks.

lewashby 56 Junior Poster

In the following program I don't understand why 'mixer' is given as an argument to the function 'create_gui'. Please explain.

File 1

# imports
from Tkinter import *
from sound_panel import *
import pygame.mixer

# create gui
app = Tk()
app.title("Head First Mix")

# create mixder
mixer = pygame.mixer
mixer.init()

# call functions
create_gui(app, mixer, "50459_M_RED_Nephlimizer.wav")
create_gui(app, mixer, "49119_M_RED_HardBouncer.wav")

def shutdown():
        track.stop()
        app.destroy()
    
app.protocol("WM_DELETE_WINDOW", shutdown)
app.mainloop()

file 2(sound_panel.py)

# this is a module

# imports
from Tkinter import *
import pygame.mixer

# create GUI panel
def create_gui(app, mixer, sound_file):
    def track_toggle():
        if track_playing.get() == 1:
            track.play(loops = -1)
        else:
            track.stop()
            
    def change_volume(v):
        track.set_volume(volume.get())
    
    track = mixer.Sound(sound_file)
    track_playing = IntVar()
    track_button = Checkbutton(app, variable = track_playing,
                               command = track_toggle, text = sound_file)
    track_button.pack(side = LEFT)
    volume = DoubleVar()
    volume.set(track.get_volume())
    volume_scale = Scale(variable = volume, from_ = 0.0, to = 1.0,
                         resolution = 0.1, command = change_volume,
                         label = "Volume", orient = HORIZONTAL)
    volume_scale.pack(side = RIGHT)
lewashby 56 Junior Poster

In the following program can someone help me figure out why the close button [X] at the top right corner isn't working?

# imports
from Tkinter import *
from sound_panel import *
import pygame.mixer

# create gui
app = Tk()
app.title("Head First Mix")

# create mixder
mixer = pygame.mixer
mixer.init()

# call functions
create_gui(app, mixer, "50459_M_RED_Nephlimizer.wav")
create_gui(app, mixer, "49119_M_RED_HardBouncer.wav")

def shutdown():
        track.stop()
        app.destroy()
    
app.protocol("WM_DELETE_WINDOW", shutdown)
app.mainloop()