I have a small animation code that is built using PyGame (and Python 2.7). I am able to build the executable folder with Pyinstaller, however when I try to run the executable it is crashing, although I am able to run the same files (i.e. source code) through my terminal without any problem.
import pygame
import exercise
import random as rd
import copy
import pandas as pd
import numpy as np
def animate():
debug_mode=False
done1 = False
dc_x = 30
dc_y = 30
plant_x = 110
plant_y = 30
supp_x = 190
supp_y = 30
WHITE = (255, 255, 255)
BLACK = (0, 0, 0) #arrows
RED = (255, 0, 0) # Box frames for summary of t, cost and lost sales
GREEN = (0, 255, 0) # Box frames for shipment amounts
DEEPSKYBLUE = (0,191,255) # arc to represent backup WIP inv
DOGERBLUE = (0,191,255) # arc to represent backup FG inv
INDIGO = (75,0,130) # DC/Supp up state
LAVENDER=(238, 130, 238) #DC/Supp down state
OLIVE=(128,128,0) #plant down state
YELLOWGREEN=(173,255,47) #plant up state
DARKYELLOW=(204,204,0)
pygame.init()
screen = pygame.display.set_mode((1000, 600))
clock = pygame.time.Clock()
grand_record={}
############ READ AND PREPARE INITIAL SCREEN for t==0 ################
PLANT_status, SUPP_status, DC_status, disruption, DC_BUp_Plan, Plant_BUp_Plan, Supp_BUp_Plan, Demand, P=exercise.init(debug_mode,False)
grand_record[0]={"DC":DC_status, "Plant":PLANT_status, "Supplier":SUPP_status}
basicFont = pygame.font.SysFont(None, 24)
largeFont = pygame.font.SysFont(None, 35)
pygame.display.set_caption('SCREAM!')
if debug_mode: R=1
else: R= rd.randint(0,25)
scenario_score={"cost":0, "service":0}
while not done1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done1 = True
#if event.type == pygame.KEYDOWN:
# if event.key == pygame.K_DOWN:
# paused()
end_of_one_run=1
total_lost_customer=0
cumulative_inv_holding_cost=0
total_fixed_cost_paid=0
table_output=[]
chart_output=[]
header=["Week","Demand","Upstream shipment", "Shipment from regular DC", "Shipment from backup DC",
"FG Inv at Reg. DC", "FG Inv at B/up. DC", "FG Inv as B/up","LostSales","Start Order for b/up DC", "B/up DC starts","DC Disruption at","Disruption duration", "TotalAvailableWIPSupplyCap",
"Start Order for b/up Supplier", "B/up Supplier starts","Supplier Disruption at","Disruption duration", "Storage Cap Available", "Plant production",
"WIP Inv as B/up","Start Order for b/up Plant", "B/up Plant starts","Plant Disruption at","Disruption duration"]
table_output.append(header)
for t in range(1,P+1): # for the specified number of periods
screen.fill((0, 0, 0))
picture = pygame.image.load('Background.png').convert() #MITwallpaper
screen.blit(picture, [0, 0])
#import pdb; pdb.set_trace()
################################## MAKE CALCULATIONS FOR t>0 ################
grand_record,output=exercise.calculate(t, grand_record[t-1]["Plant"], grand_record[t-1]["Supplier"], grand_record[t-1]["DC"], disruption, DC_BUp_Plan, Plant_BUp_Plan, Supp_BUp_Plan,Demand[R*P+t],grand_record,debug_mode)
chart_output=exercise.prepare_chart_output(chart_output, grand_record)
output_loc=copy.deepcopy(output)
table_output.append(output_loc)
end_of_one_run=end_of_one_run+1
objectives=exercise.calculate_objectives(grand_record, DC_BUp_Plan, Plant_BUp_Plan, Supp_BUp_Plan, t)
lost_cust_text = largeFont.render("Service: "+str(objectives["Service"]), True, WHITE, BLACK)
lost_cust_textRect = lost_cust_text.get_rect()
lost_cust_textRect.centerx = 380
lost_cust_textRect.centery = 420
pygame.draw.rect(screen, RED, (lost_cust_textRect.left - 3, lost_cust_textRect.top - 3, lost_cust_textRect.width + 3, lost_cust_textRect.height + 3))
screen.blit(lost_cust_text, lost_cust_textRect)
inv_hold_text = largeFont.render("Inv.Holding Cost(k$): "+str(round(objectives["InvHoldingCost"]*0.001,1)), True, WHITE, BLACK)
inv_hold_textRect = inv_hold_text.get_rect()
inv_hold_textRect.centerx = 600
inv_hold_textRect.centery = 445
pygame.draw.rect(screen, RED, (inv_hold_textRect.left - 3, inv_hold_textRect.top - 3, inv_hold_textRect.width + 3, inv_hold_textRect.height + 3))
screen.blit(inv_hold_text, inv_hold_textRect)
startup_text = largeFont.render("Startup Cost(k$): "+str(round(objectives["Startup_cost"]*0.001,1)), True, WHITE, BLACK)
startup_textRect = startup_text.get_rect()
startup_textRect.centerx = 840
startup_textRect.centery = 470
pygame.draw.rect(screen, RED, (startup_textRect.left - 3, startup_textRect.top - 3, startup_textRect.width + 3, startup_textRect.height + 3))
screen.blit(startup_text, startup_textRect)
###################################################################################
if t<P:
pygame.display.flip()
clock.tick(8)
else:
#import pdb; pdb.set_trace()
table = pd.DataFrame(table_output)
table.to_excel("Details.xlsx",index=False)
#import pdb; pdb.set_trace()
done1 = True
################################ Want A PARETO Button ###################################
x=500
y=500
w=200
h=50
pygame.draw.rect(screen, DEEPSKYBLUE,(x,y,w,h))
buttontext = basicFont.render("Want A Pareto Solution?", True, BLACK , WHITE )
buttontext_rect=buttontext.get_rect()
buttontext_rect.centerx = (x+(w/2))
buttontext_rect.centery = (y+(h/2))
screen.blit(buttontext, buttontext_rect)
pygame.display.flip()
pygame.time.delay(120)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exercise.plotcharts(chart_output)
################################################################################
animate()
I had the same problem (also Python 2.7), and this did it for me:
pyinstaller usually has trouble with pygame.font.SysFont("some_font", 24)
Instead use pygame.font.Font("your_own_font.ttf", 24).
Download a font and either put it in the same folder as your file, or in a data folder.
I use VeraMono and put it in a data folder, so my code would be
...
basicFont = pygame.font.Font("data/VeraMono", 24)
largeFont = pygame.font.Font("data/VeraMono", 35)
pygame.display.set_caption('SCREAM!')
...
If you don't have a data/ folder added to your project yet, then add the following lines to your spec file (the spec file is created as soon as you run you pyinstaller the first time. It has the same name as your python file.)
# -*- mode: python -*-
block_cipher = None
# This entry is new!
added_files = [
( 'data', 'data'),
]
a = Analysis(['CleanTest.py'],
pathex=['/home/angela/Desktop/Arbeit/VisualTest'],
binaries=[],
datas=added_files, # add the new file to your data tree
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
...
Run pyinstaller <your_file>.spec, and hopefully it'll work.
my guess is that it crashes when trying to load the background image:
picture = pygame.image.load('Background.png').convert() #MITwallpaper
When pyinstaller compiles your code, that is all it compiles (including the imported dependencies). It creates the dist directory where you can run your executable and you are good to go.
But, by default, pyinstaller will not pull in external resources. So when you run the executable, it can't find your image because it is in a different directory. You can test this by manually copying the image to the folder where the exe is located and see if it works.
Also, you can run the exe and push the output into a debug file:
your_file.exe > debug.txt
This way you can capture the output from your program (including error messages).
Related
I am creating a program that allows a user to make a custom dice, but when I open a GUI window with a button that calls the backend dice roll logic, it breaks. In other words, the window doesn't open, and the code just runs in the terminal. It doesn't happen when the button is clicked like I want it to, instead when I run the code, it doesn't open any GUI window and the code executes in the terminal. The code works without the GUI, and if i take out the dice button callback, the GUI works but together it doesn't.
Any help is appreciated!
import random
import tkinter as tk
def dice_roll():
dice = []
x = 0
# used to check if the input is a whole number, if it isn't, you get a message
while True:
while x == 0:
try:
SIDE_AMT = int(input("How many sides would you like? (min is 2, max is infinite): ")) # amt is amount
x = 1
except ValueError:
print("Sorry it has to be a whole number.")
if SIDE_AMT > 1:
for side in range(SIDE_AMT):
print(f"What would you like side {side + 1} to be?:")
dice.append(str(input()))
break
else:
print("You can't have a dice with one side!")
x = 0
# roll function
def roll():
dice_side = random.choice(dice)
print(f"I choose {dice_side}!")
roll_num = 0
while True:
if roll_num == 0:
spin_it = str(input("Type 'roll' if you would like to roll the dice: "))
if spin_it == "roll":
roll()
else:
print("Sorry, you have to type roll correctly.")
roll_num += 1
elif roll_num == 1:
while True:
spin_it = str(input("Type 'roll' if you would like to roll the dice again!: "))
if spin_it == "roll":
roll()
else:
print("Sorry, you have to type roll correctly.")
if __name__ == '__main__':
gui = tk.Tk()
gui.title("Dice Roll")
gui.geometry("1912x1090")
gui.configure(bg='#a2a2a1', borderwidth=5,
relief="raised")
# title
title = tk.Label(gui, text='Unique Dice', font=("Times
New Roman", 52))
title.configure(bg='#a2a2a1', fg='#195190',
borderwidth=3, relief='raised')
# make a dice?
dice = tk.Button(gui,
text="Yes!",
fg="red",
command=dice_roll())
no_dice = tk.Button(gui,
text="No",
fg="red",
command=quit)
# frame = tk.Frame(gui, height=200, width=200)
# frame['borderwidth'] = 10
# frame['relief'] = 'sunken'
# frame.pack()
dice.pack()
no_dice.pack()
title.pack()
gui.mainloop()
you may want to do something like this:
import tkinter as tk
from random import choice
root = tk.Tk()
root.geometry('400x600')
root.resizable(False, False)
root.config(bg='light blue')
dice_numbers = [1, 2, 3, 4, 5, 6]
rolled_nums = []
def roll():
if len(rolled_nums):
rolled_nums[0].pack_forget()
rolled_nums.pop(0)
chosen_number = choice(dice_numbers)
text = tk.Label(root, text=f'{chosen_number}',
font='arial 500 bold', bg='light blue')
text.pack()
rolled_nums.append(text)
button = tk.Button(root, text='Roll Dice!', font='arial 20 bold', relief='raised', width='300',
bg='dark red', fg='black', command=lambda: roll())
button.pack()
root.mainloop()
fell free to adjust this code and if you have questions -> ask
ok so i dont really understand functions atm and my assignment is to create a separate python module that has all of the functions need to make a program run. the program being supplied by the professor and is already completed and can not be changed by me. im not asking anybody to sit here and do all of the functions them self, although that would be amazing, i just need maybe 1 or two completed and maybe an explanation on how they work. below is completed program given to me.
import pygame
import lab06_bubbles as bubbles
import random
# ### NOTE: In this lab, I *DON'T* want you to change anything in this file. I want you to create
# lab06_bubbles.py so that this works as described in the lab document (and video) ###
# Pygame setup
win_width = 1200
win_height = 800
pygame.display.init()
pygame.font.init()
screen = pygame.display.set_mode((win_width, win_height))
font = pygame.font.SysFont("Courier New", 12)
clock = pygame.time.Clock()
done = False
numBubbles = random.randint(50, 100) # Initial number of bubbles
numWebs = 2 # Initial number of connections between each bubble
paused = False # Are we paused?
minAreaWidth = 50 # The minimum width of the bubble area
maxAreaWidth = win_width # The maximum width of the bubble area
minAreaHeight = 50 # The minimum height of the bubble area
maxAreaHeight = win_height - 50 # The maximum height of the bubble area
# Generate the initial play area and bubble list
currentArea = bubbles.randomArea(minAreaWidth, minAreaHeight, maxAreaWidth, maxAreaHeight)
bubbleList = bubbles.spawnBubbles(numBubbles, currentArea, 5, 20, 100)
# Game Loop
while not done:
# #############
# # UPDATE #
# #############
deltaTime = clock.tick() / 1000.0
if paused:
deltaTime = 0.0
bubbles.updateBubbles(bubbleList, currentArea, deltaTime)
# #############
# # INPUT #
# #############
event = pygame.event.poll()
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
elif event.key == pygame.K_LEFT:
numBubbles -= 5
if numBubbles < 5:
numBubbles = 5
bubbleList = bubbles.spawnBubbles(numBubbles, currentArea, 5, 20, 100)
elif event.key == pygame.K_RIGHT:
numBubbles += 5
if numBubbles > 100:
numBubbles = 100
bubbleList = bubbles.spawnBubbles(numBubbles, currentArea, 5, 20, 100)
elif event.key == pygame.K_UP:
numWebs += 1
elif event.key == pygame.K_DOWN:
numWebs -= 1
if numWebs < 0:
numWebs = 0
elif event.key == pygame.K_SPACE:
currentArea = bubbles.randomArea(minAreaWidth, minAreaHeight, maxAreaWidth, maxAreaHeight)
bubbleList = bubbles.spawnBubbles(numBubbles, currentArea, 5, 20, 100)
elif event.key == pygame.K_p:
paused = not paused
# #############
# # DRAW #
# #############
screen.fill((0,0,0))
pygame.draw.rect(screen, (255,255,255), currentArea, 1)
bubbles.drawBubbles(bubbleList, screen, numWebs)
screen.blit(font.render("# Bubbles: " + str(len(bubbleList)) + " area: " + str(currentArea) + \
" num_webs: " + str(numWebs), False, (128,128,128)), (0, win_height - 48))
screen.blit(font.render("[Left / Right] : decrease / increase number of bubbles [space]: regenerate bounds [escape]: quit", \
False, (128,128,128)), (0, win_height - 32))
screen.blit(font.render("[Up / Down] : decrease / increase number of connections [p]: pause", False, \
(128,128,128)), (0, win_height - 16))
pygame.display.flip()
# Pygame shutdown
pygame.font.quit()
pygame.display.quit()
this is the function outline module that was given to me and this is where i have no idea what to do.
def randomArea(minW, minH, maxW, maxH):
"""
:param minW: the minimum width of this box
:param minH: the minimum height of this box
:param maxW: the maximum width of this box (normally the width of the "playfield")
:param maxH: the maximum height of this box (normally the height of the "playfield")
:return: a pygame-style rect (x, y, w, h) that fits within the "playfield"
"""
def spawnBubbles(num, area, minSize, maxSize, maxSpeed):
"""
:param num: the number of bubbles to create
:param area: a pygame-style rect (x, y, w, h) that all bubbles should spawn completely inside
:param minSize: the minimum size of a bubble
:param maxSize: the maximum size of a bubble (should fit within the minimum size passed to
randomArea)
:param maxSpeed: the maximum horizontal and vertical speed a bubble should have (in px / s)
:return: A list of lists where each sub-list is of the form [x, y, radius, horiz_speed,
vert_speed]
"""
def getClosest(interest, L, num):
"""
:param interest: the bubble of interest
:param L: the list of all bubbles
:param num: the number of closest bubbles to find
:return: a list of num bubbles (not counting the interest) that are closest to the interest
object
"""
def updateBubbles(L, area, dt):
"""
Makes all bubbles move. If a bubble hits the left / right sides of the area, negate their
horiz_speed and
move them just inside the area; if a bubble hits the top / bottom of the area, negate their
vert_speed and
move them just inside the area.
:param L: The list of all bubbles
:param area: the pygame-style rect bounding the play area.
:param dt: The number of seconds that has passed since the last update
:return: None
"""
def drawBubbles(L, surf, num_webs):
"""
Draws the bubbles and the connections between them. This function calls the getClosest
function internally
:param L: The list of all bubbles
:param surf: The surface to draw to
:param num_webs: The number of connections to draw between bubbles
:return: None
"""
i just need some help with this please. this is what the final product should look like.
First thing I won't do your assignment for you but I can try and help by giving you the following clues:
every time you use the import statement in a python script to import a module (fancy name for another script), Python will go and look for that module in two places:
the current working directory (usually the folder where the script you are working on is)
if it can't find it in the current working directory it will go and look for it in the Python installed libraries.
So the first thing you want, is to make sure that lab06_bubbles is in the same directory as the script you will run.
then, since your professor imports lab06_bubbles as bubbles , everywhere in his program where bubbles.function is mentioned it will go and look for that function in the lab06_bubbles.py file in which you have to build all the functions that the program will need.
Then the professor gives you all the information you need to build the function:
what the arguments are
what the function should return
You, have to do the magic in the middle.
say one of the functions was called getDist with the following description:
def getDist(pointa, pointb):
"""
Takes two points, and return the distance between those points.
:param pointa: a tuple with the x, y coordinates of point a
:param pointb: a tuple with the x, y coordinates of point b
:return: a float representing the distance between the two points
"""
you would need to code the function as follow:
def getDist(pointa, pointb):
xa,ya = pointa
xb,yb = pointb
dist_ab = ((xa-xb)**2+(ya-yb)**2)**0.5
return float(dist_ab)
hope that helps
Modifying the Squirrel Eat Squirrel Pygame for a class project. Trying to add in a menu, with basic Start, Quit and Settings buttons. I have the buttons there, and they will light up as the mouse scrolls over them. However, I can't figure out how to call their respective functions when I click on them. I am trying to call them by this:
def runMenu(self):
mainloop = True
while mainloop:
self.__clock.tick(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop == False
if event.type == MOUSEBUTTONDOWN:
for item in self.__items:
#print(item)
if item.isMouseSelecting(pygame.mouse.get_pos()):
print(self.__functions)
self.__functions[item]() #HERE <----
I believe it is because I am using a dictionary in my if name == "main" (See below) therefore it's not actually the dictionary, but its referencing its location? If that makes sense. (i'm not very good at explaining it, so sorry)
if __name__ == "__main__":
screen = pygame.display.set_mode((640, 480), 0 , 32)
menuItems = ('Start', 'Quit', 'Settings')
functions = {'Start': main, 'Quit': terminate, 'Settings': None}
pygame.display.set_caption('Main Menu')
game = MainMenu(screen, functions, menuItems)
game.runMenu()
The error it gives me in shell:
>>> ================================ RESTART ================================
>>>
({'Start': <function main at 0x2969ab0>, 'Settings': None, 'Quit': <function terminate at 0x2969cf0>}, '#')
{'Start': <function main at 0x2969ab0>, 'Settings': None, 'Quit': <function terminate at 0x2969cf0>}
Traceback (most recent call last):
File "/Users/tjleggz/Documents/CS 110/squirrel/squirrel.py", line 501, in <module>
game.runMenu()
File "/Users/tjleggz/Documents/CS 110/squirrel/squirrel.py", line 138, in runMenu
self.__functions[item]() #cant call bc its not same object, just a ref to object or something???#
KeyError: <__main__.MenuItem object at 0x29758c8>
>>>
THANKS!
EDIT:
class MenuItem(pygame.font.Font):
def __init__(self, text, font=None, fontSize=30,
fontColor=(255, 255, 255), (posX, posY)=(0, 0)):
pygame.font.Font.__init__(self, font, fontSize) #initializes font module
self.__text = text
self.__fontSize = fontSize
self.__fontColor = fontColor
self.label = self.render(self.__text, 1, self.__fontColor) #not private??
self.width = self.label.get_rect().width
self.height = self.label.get_rect().height
self.__posX = posX
self.__posY = posY
self.position = posX, posY
def set_position(self, x, y):
self.position = (x, y)
self.__posX = x
self.__posY = y
def isMouseSelecting(self, (posX, posY)): #change to conditional?!
if (posX >= self.__posX and posX <= self.__posX + self.width) and \
(posY >= self.__posY and posY <= self.__posY + self.height):
return True
else:
return False
def setFontColor(self, rgbTuple):
self.fontColor = rgbTuple
self.label = self.render(self.__text, 1, self.fontColor)
Your self.items contains MenuItem objects, not strings which are the keys to your dictionary. You can work around this in a couple ways, for example you could use the __text attribute of MenuItem which is I think what you are looking for.
A better way to do this (instead of using a dictionary of functions like you are now) might be to pass an on_click function to each MenuItem instance you make, and then you just have to write
if item.isMouseSelecting(pygame.mouse.get_pos()):
item.on_click()
however you seem to be relatively new to programming, so you may just want to use the first suggestion.
i am totally new to python. thus please explain thoroughly wen u respond to my query.
in my code i want to measure the time the player lasts before his cursor touches the bouncing ball on the screen but the time i am obtaining is the sum of all the seconds since the first time the command was initialised. i need to stop the counting of seconds as soon as the user ends the game and to begin afresh wen the play again option is chosen...
also i wud lyk a way to make the player qualify for the next level without usin d detection of position of mouse....since dat is making the program code logic incorrect...
here is my code:
import pygame,sys
from pygame.locals import*
from pygame import *
import random
def main():
# set up sounds
# import pygame
#gameOverSound = pygame.mixer.Sound('gameover.wav')
#pygame.mixer.music.load('background.mid')
#from pygame import *
#import random
#pygame.mixer.pre_init(44100, 16, 2, 4096)
#background =image.load('C:\Users\Administrator\Desktop\oearth.png')
ballpic = image.load('ball1.png')
ballpic.set_colorkey((0,0,0))
#find a way to include verification of more than one colour key
# to add more than one shape....pending
numballs = 10
delay = 5
done = False
balls = []
stars = []
#generate an if loop for execution of both the parts
k = 2
init()
screen = display.set_mode((640, 480))
display.set_caption('mouse game by shivangi and ananya')
event.set_grab(1)
#pygame.time.Clock() Creates a Clock object (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()
#pygame.time.delay(milliseconds) Pauses game for time specified
#pygame.time.get_ticks() Returns the number of milliseconds passed since pygame.init() was #called
for count in range(numballs):
balls.append(dict)
balls[count] = {'x': 0, 'y': 0, 'xmove': random.randint(1, 2), 'ymove': random.randint(1, 2)}
screen = display.set_mode((640, 480)) #####screen = display.set_mode((640,480),FULLSCREEN,32).....check functioning...
#pygame.display.list_modes()
#[(800, 600), (1280, 1024), (1280, 960), (1280, 800), (1280, 768), (1280, 720),
#(1152, 864), (1088, 612), (1024, 768), (960, 600), (848, 480), (800, 600),
#(720, 576), (720, 480), (640, 480), (640, 400), (512, 384), (480, 360), (400, 300),
#(320, 240), (320, 200), (640, 480)]
while done == False:
pygame.time.Clock()
init()
screen.fill((0,100,0))
for count in range(numballs):
screen.blit(ballpic, (balls[count]['x'], balls[count]['y']))
display.update()
time.delay(delay)
for count in range(numballs):
balls[count]['x'] = balls[count]['x'] + balls[count]['xmove']
balls[count]['y'] = balls[count]['y'] + balls[count]['ymove']
for count in range(numballs):
if balls[count]['x'] > 620:
balls[count]['xmove'] = random.randint(-2, 0)
if balls[count]['x'] < -10:
balls[count]['xmove'] = random.randint(0, 6)
if balls[count]['y'] > 470:
balls[count]['ymove'] = random.randint(-9, 0)
if balls[count]['y'] < -10:
balls[count]['ymove'] = random.randint(0, 5)
for e in event.get():
if e.type == KEYUP:
if e.key == K_ESCAPE:
done = True
if screen.get_at((mouse.get_pos())) == (227,209,43):
done = True
if done == True:
#pygame.mixer.init()
break
sec = time.get_ticks()/1000
quit()
while sec < k:
print "you lasted for only",sec,"seconds...try again to qualify for the next level..."
quit()
break
time_lasted = 0
while sec >= k:
starpic = image.load('star.png')
starpic.set_colorkey((0,0,0))
#find a way to include verification of more than one colour key...PENDING
numstars = 30
delay = 8
done = False
stars = []
for count in range(numstars):
stars.append(dict)
stars[count] = {'x': 0, 'y': 0, 'xmove': random.randint(1, 2), 'ymove': random.randint(1, 2)}
screen = display.set_mode((640, 480))
display.set_caption('mouse game')
event.set_grab(1)
while done == False:
init()
screen.fill((160,32,240))
for count in range(numstars):
screen.blit(starpic, (stars[count]['x'], stars[count]['y']))
display.update()
time.delay(delay)
for count in range(numstars):
stars[count]['x'] = stars[count]['x'] + stars[count]['xmove']
stars[count]['y'] = stars[count]['y'] + stars[count]['ymove']
for count in range(numstars):
if stars[count]['x'] > 620:
stars[count]['xmove'] = random.randint(-2, 0)
if stars[count]['x'] < -10:
stars[count]['xmove'] = random.randint(0, 2)
if stars[count]['y'] > 470:
stars[count]['ymove'] = random.randint(-2, 0)
if stars[count]['y'] < -10:
stars[count]['ymove'] = random.randint(0, 2)
for e in event.get():
if e.type == KEYUP:
if e.key == K_ESCAPE:
done = True
if screen.get_at((mouse.get_pos())) == (255,255,255,255):
done = True
if done == True:
time_lasted = time.get_ticks()/1000
quit()
break
#sec = time.update()
#time_lasted = time.update()
#correction of time error to be done....pending....
quit()
print "You lasted for", sec, "seconds in the first level!"
print "\n"
print "you lasted for",time_lasted,"in the second level!"
print "\n"
print "your total score is :", int(sec) + int(time_lasted)
print "\n"
print "game over...! Thank you for playing!! :D :P :)"
quit()
break
main()
x = 1
x = raw_input("Do you want to play again?")
while x.upper() in ['YES','Y']:
main()
x = raw_input("Do you want to play again?")
while x.upper() in ['NO','N']:
break
# when player starts game
start = time.get_ticks()
# during game
current = time.get_ticks()
time_you_played = (current - start)/1000
EDIT:
Timer to count seconds.
class Timer():
def __init__(self):
self._start = 0
def start(self):
self._start = pygame.time.get_ticks()
def current(self):
return (pygame.time.get_ticks() - self._start)/1000
Example - how to use:
import pygame
# add class Timer here
pygame.init()
t = Timer()
t.start() # start or restart timer
pygame.time.wait(3000) # for test only
print t.current() # print seconds
pygame.time.wait(2000) # for test only
print t.current() # print seconds
You don't have to stop timer because you can use start() to restart timer.
# 1 - Import library
import pygame
from pygame.locals import *
import math
import random
# 2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
keys = [False, False, False, False]
playerpos=[100,100]
acc=[0,0]
arrows=[]
badtimer=100
badtimer1=0
badguys=[[640,100]]
healthvalue=194
pygame.mixer.init()
# 3 - Load image
player = pygame.image.load("C:\python27\PyGame\resources\images\dude.png")
grass = pygame.image.load("C:\python27\PyGame\resources\images\grass.png")
castle = pygame.image.load("C:\python27\PyGame\resources\images\castle.png")
arrow = pygame.image.load("C:\python27\PyGame\resources\images\bullet.png")
badguyimg1 = pygame.image.load("C:\python27\PyGame\resources\image\badguy.png")
badguyimg=badguyimg1
healthbar = pygame.image.load("C:\python27\PyGame\resources\images\healthbar.png")
health = pygame.image.load("C:\python27\PyGame\resources\images\health.png")
gameover = pygame.image.load("C:\python27\PyGame\resources\images\gameover.png")
youwin = pygame.image.load("C:\python27\PyGame\resources\images\youwin.png")
# 3.1 - Load audio
hit = pygame.mixer.Sound("C:\python27\PyGame\resources\audio\explode.wav")
enemy = pygame.mixer.Sound("C:\python27\PyGame\resources\audio\enemy.wav")
shoot = pygame.mixer.Sound("C:\python27\PyGame\resources\audio\shoot.wav")
hit.set_volume(0.05)
enemy.set_volume(0.05)
shoot.set_volume(0.05)
pygame.mixer.music.load('C:\python27\PyGame\resources\audio\moonlight.wav')
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)
# 4 - keep looping through
running = 1
exitcode = 0
while running:
badtimer-=1
# 5 - clear the screen before drawing it again
screen.fill(0)
# 6 - draw the player on the screen at X:100, Y:100
for x in range(width/grass.get_width()+1):
for y in range(height/grass.get_height()+1):
screen.blit(grass,(x*100,y*100))
screen.blit(castle,(0,30))
screen.blit(castle,(0,135))
screen.blit(castle,(0,240))
screen.blit(castle,(0,345 ))
# 6.1 - Set player position and rotation
position = pygame.mouse.get_pos()
angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26))
playerrot = pygame.transform.rotate(player, 360-angle*57.29)
playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2)
screen.blit(playerrot, playerpos1)
# 6.2 - Draw arrows
for bullet in arrows:
index=0
velx=math.cos(bullet[0])*10
vely=math.sin(bullet[0])*10
bullet[1]+=velx
bullet[2]+=vely
if bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480:
arrows.pop(index)
index+=1
for projectile in arrows:
arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29)
screen.blit(arrow1, (projectile[1], projectile[2]))
# 6.3 - Draw badgers
if badtimer==0:
badguys.append([640, random.randint(50,430)])
badtimer=100-(badtimer1*2)
if badtimer1>=35:
badtimer1=35
else:
badtimer1+=5
index=0
for badguy in badguys:
if badguy[0]<-64:
badguys.pop(index)
badguy[0]-=7
# 6.3.1 - Attack castle
badrect=pygame.Rect(badguyimg.get_rect())
badrect.top=badguy[1]
badrect.left=badguy[0]
if badrect.left<64:
hit.play()
healthvalue -= random.randint(5,20)
badguys.pop(index)
#6.3.2 - Check for collisions
index1=0
for bullet in arrows:
bullrect=pygame.Rect(arrow.get_rect())
bullrect.left=bullet[1]
bullrect.top=bullet[2]
if badrect.colliderect(bullrect):
enemy.play()
acc[0]+=1
badguys.pop(index)
arrows.pop(index1)
index1+=1
# 6.3.3 - Next bad guy
index+=1
for badguy in badguys:
screen.blit(badguyimg, badguy)
# 6.4 - Draw clock
font = pygame.font.Font(None, 24)
survivedtext = font.render(str((90000-pygame.time.get_ticks())/60000)+":"+str((90000-pygame.time.get_ticks())/1000%60).zfill(2), True, (0,0,0))
textRect = survivedtext.get_rect()
textRect.topright=[635,5]
screen.blit(survivedtext, textRect)
# 6.5 - Draw health bar
screen.blit(healthbar, (5,5))
for health1 in range(healthvalue):
screen.blit(health, (health1+8,8))
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type==pygame.QUIT:
# if it is quit the game
pygame.quit()
exit(0)
if event.type == pygame.KEYDOWN:
if event.key==K_w:
keys[0]=True
elif event.key==K_a:
keys[1]=True
elif event.key==K_s:
keys[2]=True
elif event.key==K_d:
keys[3]=True
if event.type == pygame.KEYUP:
if event.key==pygame.K_w:
keys[0]=False
elif event.key==pygame.K_a:
keys[1]=False
elif event.key==pygame.K_s:
keys[2]=False
elif event.key==pygame.K_d:
keys[3]=False
if event.type==pygame.MOUSEBUTTONDOWN:
shoot.play()
position=pygame.mouse.get_pos()
acc[1]+=1
arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32])
# 9 - Move player
if keys[0]:
playerpos[1]-=5
elif keys[2]:
playerpos[1]+=5
if keys[1]:
playerpos[0]-=5
elif keys[3]:
playerpos[0]+=5
#10 - Win/Lose check
if pygame.time.get_ticks()>=90000:
running=0
exitcode=1
if healthvalue<=0:
running=0
exitcode=0
if acc[1]!=0:
accuracy=acc[0]*1.0/acc[1]*100
else:
accuracy=0
# 11 - Win/lose display
if exitcode==0:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(gameover, (0,0))
screen.blit(text, textRect)
else:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(youwin, (0,0))
screen.blit(text, textRect)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
pygame.display.flip()
here is the error message
Traceback (most recent call last):
File "C:\Python27\game2.py", line 22, in
player = pygame.image.load("C:\python27\PyGame\resources\images\dude.png")
error: Couldn't open C:\python27\PyGame\resources\images\dude.png
What should I do?
First, make sure the file exists.
Next, using single backslashes, \, may lead to problems. For example, \r is the carriage return sequence (\n is the more widely known newline sequence). Your file path, happens to contain a \r, which could be causing your issue.
Try one of these instead:
# Use forward slashes
pygame.image.load("C:/python27/PyGame/resources/images/dude.png")
# Use double back-slashes. For file path specification, \\ indicates '\' (depending
# on the platform)
pygame.image.load("C:\\python27\\PyGame\\resources\\images\\dude.png")
# Use the os module
# Note that this assembles a path relative to your .py file.
# Absolute path can still be done here, it's just more verbose.
pygame.image.load(os.path.join("Pygame", "resources", "images", "dude.png"))
The last option is probably the best practice.