My wxpython program suddenly doesn't work for no reason - windows

I made a program for school few weeks ego.. i have finished it yet.
for some reason, when i am trying to run the program now, it doesn't work, although it worked well in the last time a tried.
I am sure that i didn't change anything in the code, but there is always a chance that something has changed and i didn't payed attention..
I need to pass it to my teacher in these days and i have no idea what is wrong with the program.
I will glad to get some help here..
here is the code:
import wx
import winsound
import wx.grid as gridlib
from random import randint
OPTIONS = [1, 2, 3, 4, 5, 6, 7, 8, 9, "DEL", 0, "SEND"]
# these are the events' IDs sent to a function when you click a button.
# the OPTIONS_ID is in the same order of OPTIONS.
OPTIONS_ID = [-31984,-31983,-31982,-31981,-31980,-31979, -31978, -31977, -31976, -31975, -31974, -31973, -31985] # the built in wxpython IDs for the buttons
GAME_POSITION = (400, 100)
GAME_SIZE = [900, 600]
def RandomNum():
count = 5
while count > 4:
num = randint(1000, 9999)
digits = str(num)
count = 0
for digit in digits:
for digit2 in digits:
if digit == digit2:
count = count + 1
return digits
class Frame(wx.Frame): # class for all the frames in our game.
def __init__(self, parent, id, title, pos, size):
wx.Frame.__init__(self, parent, id, title, pos, size)
self.panel = wx.Panel(self)
self.fdf = wx.TextCtrl(self.panel, size=(275, 75), pos=(520, 20))
self.count = 0
self.turnsCounter = 0
self.numbers = RandomNum()
self.bulls = 0
self.cows = 0
self.counter_of_turns = 0
self.check = False
self.grid = gridlib.Grid(self.panel, pos = (85, 150), size=(323, 212))
self.grid.CreateGrid(10, 3)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.panel, 1, wx.EXPAND)
sizer.Add(self.grid, 1, wx.EXPAND)
self.panel.SetSizer(sizer)
for i in range(10):
for j in range(4):
self.grid.SetReadOnly(i, j)
self.grid.SetColLabelValue(0, "guess")
self.grid.SetColLabelValue(1, "cows")
self.grid.SetColLabelValue(2, "bulls")
def message_dialog(self, message, caption, style=wx.YES_NO, position=GAME_POSITION):
if message != "": # making sure not to execute a message if its empety
message = wx.MessageDialog(None, message, caption, style, position)
answer = message.ShowModal()
if answer == wx.ID_YES:
self.reset()
else:
self.Destroy()
else:
return -1
# this function creates a textbox at a specific position with a specific size.
def write(self, panel, txt, pos, size=20, font_family=wx.SWISS, font_style = wx.NORMAL,font_weight = wx.BOLD, underline = False, color=wx.WHITE):
# create a textbox at a specific position with a specific size.
your_txt = wx.StaticText(panel, -1, txt, pos)
your_txt.SetFont(wx.Font(size,font_family,font_style,font_weight,underline))
your_txt.SetForegroundColour(color)
# same as above, just for a button.
def create_button(self, panel, txt, position, width, height, color, disable):
Size = wx.Size(width, height)
self.button = wx.Button(panel, -1, txt, position, Size)
self.button.SetBackgroundColour(color)
self.border = wx.BoxSizer(wx.VERTICAL)
self.border.Add(self.button)
self.Bind(wx.EVT_BUTTON, lambda evt: self.OnButton(evt), self.button)
if disable == True:
self.button.Disable()
def count_bulls(self, txtctrl, seria):
for i in range(4):
if seria[i] == txtctrl[i]:
self.bulls += 1
replacement = self.bulls
self.bulls = 0
return replacement
def count_cows(self, txtctrl, seria):
for i in range(4):
if seria[i] != txtctrl[i] and seria[i] in txtctrl:
self.cows += 1
replacement = self.cows
self.cows = 0
return replacement
def reset(self):
self.fdf.Clear()
self.grid.ClearGrid()
self.count = 0
self.turnsCounter = 0
self.numbers = RandomNum()
self.bulls = 0
self.cows = 0
self.counter_of_turns = 0
self.check = False
for child in self.panel.GetChildren():
if child.GetLabel() != "SEND":
child.Enable()
else:
child.Disable()
if self.count == 0:
if child.GetLabel() == "DEL" or child.GetLabel() == "0":
child.Disable()
def OnButton(self, event):
print repr(event.Id) + ","
print self.numbers
if event.Id in OPTIONS_ID: # if indeed an option button was pressed
exited = -1 # exited is 5100 if the user exited his dialog box
# assigning the events to the button.
for i in range(13):
if event.Id != -31985 and event.Id != -31975 and event.Id != -31974 and event.Id != -31973 and event.Id == OPTIONS_ID[i]:
self.fdf.AppendText(str(OPTIONS[i]))
self.count += 1
if event.Id == -31974:
self.fdf.AppendText(str(OPTIONS[10]))
self.count += 1
if event.Id == -31985:
self.reset()
if event.Id == -31973:
self.counter_of_turns += 1
print self.numbers
print self.fdf.GetValue()
cows = self.count_cows(self.fdf.GetValue(), self.numbers)
bulls = self.count_bulls(self.fdf.GetValue(), self.numbers)
self.grid.SetCellValue(self.turnsCounter,0, self.fdf.GetValue())
self.grid.SetCellValue(self.turnsCounter, 1, str(cows))
self.grid.SetCellValue(self.turnsCounter, 2, str(bulls))
self.fdf.Clear()
self.count = 0
if self.turnsCounter < 9:
self.turnsCounter += 1
if bulls == 4:
self.check = True
winsound.PlaySound('The_Power_-_Snap_1_.wav', winsound.SND_ASYNC | winsound.SND_LOOP)
self.message_dialog("Well done! you won this game..\n You won the game in %s turns .. \n Play again ? " % self.counter_of_turns , "You won!")
winsound.PlaySound(None, 0)
if event.Id == -31975:
if self.count > 0:
self.count -= 1
self.fdf.Remove(self.fdf.GetLastPosition()-1, self.fdf.GetLastPosition())
if self.count == 4:
for child in self.panel.GetChildren():
if isinstance(child, wx.Button):
try:
int(child.GetLabel())
except ValueError:
if child.GetLabel() == "SEND":
child.Enable()
else:
child.Disable()
elif self.check == False:
for child in self.panel.GetChildren():
if child.GetLabel() != "SEND":
child.Enable()
else:
child.Disable()
if self.count == 0:
if child.GetLabel() == "DEL" or child.GetLabel() == "0":
child.Disable()
#for child in self.panel.GetChildren():
#if isinstance(child, wx.Button):
#if child.GetLabel() in self.fdf.GetValue():
#child.Disable()
if self.counter_of_turns == 10 and self.check == False:
self.message_dialog("YOU LOST :( \n THE NUMBERS WERE %s \n PLAY AGAIN ?" % self.numbers,"Bad news ..")
class Game(wx.App):
def OnInit(self): # upon game opening
# I would like the options window to be the first window's parent
# so I will first set up our options window:
window = Frame(None, -1, "Good Luck!", GAME_POSITION, GAME_SIZE)
first_panel = window.panel
window.SetBackgroundColour(wx.BLACK)
window.write(first_panel, "BULLS AND COWS!", (50, 50), size=(35))
countX = 500
countY = 100
window.create_button(first_panel,"restart!", (50, 400), 100, 100, wx.WHITE, False)
for option in OPTIONS:
if str(option) == "SEND" or str(option) == "DEL":
window.create_button(first_panel,str(option), (countX, countY), 100, 100, wx.GREEN, True)
elif str(option) == "0":
window.create_button(first_panel,str(option), (countX, countY), 100, 100, wx.WHITE, True)
else:
window.create_button(first_panel,str(option), (countX, countY), 100, 100, wx.WHITE, False)
countX += 110
if str(option) == "3" or str(option) == "6" or str(option) == "9":
countY += 110
countX = 500
window.Show(True)
return True
def main():
MasterMind = Game()
MasterMind.MainLoop()
if __name__ == '__main__':
main()
PLEASE NOTE:
I upgraded my windows to windows 10 few days ego, it means that it doesn't work since the upgrade if it means something. (sorry if the grammer of my english not so well, it is not my native language..).

In my computer works fine (Python 2.7.11 and windows 7). If you import this class in another file, make sure if you call the main function.

Related

How can I create a group that would contain some lists of sprites (animations)? [duplicate]

This question already has answers here:
Animated sprite from few images
(4 answers)
How do I create animated sprites using Sprite Sheets in Pygame?
(1 answer)
Closed 3 months ago.
So I am pretty new to pygame, I am trying to do my player to shoot bullets so I decided after watching some video to create a group with all my bullets, however my bullets are animated.
I am trying to use a draw function that would draw my every frame , but I also used pygame.sprite.Group() that allows me to use only the normal draw function. Again I am a total noob and I would really appreciate some help ,thanks !
`
mainloop.py
import pygame
from Player import player
from test import Bullet
pygame.init()
DISPLAY_W, DISPLAY_H = 480, 270
canvas = pygame.Surface((DISPLAY_W, DISPLAY_H))
window = pygame.display.set_mode(((DISPLAY_W, DISPLAY_H)))
running = True
clock = pygame.time.Clock()
house = pygame.image.load('house.png').convert()
bullet_group = pygame.sprite.Group()
bro = player()
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
bro.LEFT_KEY, bro.FACING_LEFT = True, True
elif event.key == pygame.K_RIGHT:
bro.RIGHT_KEY, bro.FACING_LEFT = True, False
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
bro.LEFT_KEY = False
elif event.key == pygame.K_RIGHT:
bro.RIGHT_KEY = False
if event.type == pygame.MOUSEBUTTONDOWN:
bullet_group.add(bro.create_bullet())
bro.update()
canvas.blit(house, (0, 0))
bro.draw(canvas)
bullet_group.draww(canvas)
bullet_group.update()
window.blit(canvas, (0, 0))
pygame.display.update()
`
`
test.py
import pygame
from Sprite import Spritesheet
class Bullet(pygame.sprite.Sprite):
def __init__(self, pos_x, pos_y):
pygame.sprite.Sprite.__init__(self)
self.load_frames()
self.FACING_LEFT = False
self.image = self.frames_left[0]
self.velocity = 0
self.rect = self.image.get_rect(center=(pos_x, pos_y))
self.current_frame = 0
self.last_updated = 0
self.velocity = 0
self.current_image = self.frames_left[0]
def draww(self, display):
display.blit(self.current_image, self.rect)
def update(self):
self.rect.x += 5
self.animate()
def animate(self):
now = pygame.time.get_ticks()
if now - self.last_updated > 200:
self.last_updated = now
self.current_frame = (self.current_frame +
1) % len(self.frames_left)
self.current_image = self.frames_left[self.current_frame]
def load_frames(self):
sprite = Spritesheet('broforce.png')
self.frames_left = [sprite.parse_sprite(
'Sheet/g1.png'), sprite.parse_sprite('Sheet/g1.png'), sprite.parse_sprite('Sheet/g2.png'), sprite.parse_sprite('Sheet/g3.png'), sprite.parse_sprite('Sheet/g4.png'), ]
self.frames_right = []
for frame in self.frames_left:
self.frames_right.append(pygame.transform.flip(frame, True, False))
`
`
player.py
import pygame
from Sprite import Spritesheet
from test import Bullet
class player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.LEFT_KEY, self.RIGHT_KEY, self.FACING_LEFT = False, False, False
self.load_frames()
self.rect = self.idle_frames_left[0].get_rect()
self.rect.midbottom = (240, 244)
self.current_frame = 0
self.last_updated = 0
self.velocity = 0
self.state = 'idle'
self.current_image = self.idle_frames_left[0]
def create_bullet(self):
return Bullet(self.rect.x, self.rect.y)
def draw(self, display):
display.blit(self.current_image, self.rect)
def update(self):
self.velocity = 0
if self.LEFT_KEY:
self.velocity = -3
elif self.RIGHT_KEY:
self.velocity = 3
self.rect.x += self.velocity
self.set_state()
self.animate()
def set_state(self):
self.state = ' idle'
if self.velocity > 0:
self.state = 'moving right'
elif self.velocity < 0:
self.state = 'moving left'
def animate(self):
now = pygame.time.get_ticks()
if self.state == ' idle':
if now - self.last_updated > 200:
self.last_updated = now
self.current_frame = (
self.current_frame + 1) % len(self.idle_frames_left)
if self.FACING_LEFT:
self.current_image = self.idle_frames_left[self.current_frame]
elif not self.FACING_LEFT:
self.current_image = self.idle_frames_right[self.current_frame]
else:
if now - self.last_updated > 60:
self.last_updated = now
self.current_frame = (
self.current_frame + 1) % len(self.walking_frames_left)
if self.state == 'moving left':
self.current_image = self.walking_frames_left[self.current_frame]
elif self.state == 'moving right':
self.current_image = self.walking_frames_right[self.current_frame]
def load_frames(self):
sprite = Spritesheet('broforce.png')
self.idle_frames_left = [sprite.parse_sprite('Sheet/1.png')]
self.walking_frames_left = [sprite.parse_sprite('Sheet/2.png'), sprite.parse_sprite(
'Sheet/3.png'), sprite.parse_sprite('Sheet/4.png'), sprite.parse_sprite('Sheet/5.png'), sprite.parse_sprite('Sheet/1.png')]
self.idle_frames_right = []
for frame in self.idle_frames_left:
self.idle_frames_right.append(
pygame.transform.flip(frame, True, False))
self.walking_frames_right = []
for frame in self.walking_frames_left:
self.walking_frames_right.append(
pygame.transform.flip(frame, True, False))
`
Well I don't really know what to try

How can I compare lists properly?

So I am trying to teach myself some coding and decided to create a little lotto simulator but I just cannot manage to get the program to compare my four lists properly, what is the matter with my def compList code?.
from random import randint as rnd
myGuess_list = []
myGuess_normal = []
myGuess_bonus = []
numbers =[]
drawNumbers = []
normalNumbers = []
bonusNumbers = []
normal_correct = 0
bonus_correct = 0
CORRECT_list = []
BONUS_list = []
winnings = 0
def main():
# generate list of possible numbers
i = 0
for i in range(0, 34):
i += 1
numbers.append(i)
print(numbers)
# draw random numbers from list as lists guessed
def myGuess():
for i in range(0, 10):
numbers = rnd(1, 34)
while numbers in myGuess_list:
numbers = rnd(1, 34)
myGuess_list.append(numbers)
myGuess_list.sort()
myGuess_normal = myGuess_list[0:7]
myGuess_bonus = myGuess_list[-3:]
return myGuess_normal, myGuess_bonus
print(myGuess())
# drawing the lotto numbers from the pool of numbers
def drawNumber(numbers, N):
for i in range(0, N):
number = random.choice(numbers)
while number in drawNumbers:
number = random.choice(numbers)
drawNumbers.append(number)
drawNumbers.sort()
normalNumbers = drawNumbers[0:7]
bonusNumbers = drawNumbers[-3:]
return normalNumbers, bonusNumbers
print(drawNumber(numbers, 10))
comparing list drawn list A with guessed list B and drawn list C with guessed list D
def compList(A, B, C, D):
global normal_correct
global bonus_correct
for i in A and j in C:
if i in B:
normal_correct += 1
CORRECT_list.append(i)
elif j in D:
bonus_correct += 1
BONUS_list.append(j)
print(CORRECT_list + BONUS_list)
return normal_correct, bonus_correct
print(compList(normalNumbers, myGuess_normal, bonusNumbers, myGuess_bonus))
calculate winnings base on previous function
def Winnings(normal_correct, bonus_correct):
global winnings
i = 0
for i in range(0, 10):
i += 1
if normal_correct <= 3:
winnings = 0 - 5
elif normal_correct == 4:
winnings = 45 - 5
elif normal_correct == 5:
winnings = 100 - 5
elif normal_correct == 6:
winnings = 3695 - 5
elif normal_correct == 6 and bonus_correct == 1:
winnings = 169410 - 5
elif normal_correct == 7:
winnings = 'JACKPOT!!'
return winnings
print(Winnings(normal_correct, bonus_correct))
calling main
main()

How to create a Minimax algorithm comparing arrays

I'm trying to code a "minimax" algorithm for Tic Tac Toe.
Each node of the tree is of the form [nil/Int, String] where the last element is a nine character string describing the board, and the first is an Integer ranking the node, or nil by default.
If the value is nil, it tries to inherit the appropriate value from child nodes.
This is where I get an error, when comparing an array with an array failed.
class Scene_TicTacToe #Script 2/2
def initialize
#Boardstate as a str from top left corner to bottom right corner.
#boardstate = "---------"
#1 = player, -1 = comp
#active_player = 1
end
def wincheck(boardstate=#boardstate)
#should return -1 for loss, 0 for draw, 1 for win
["OOO","XXX"].each do |f|
for i in 0..2
if (boardstate[i]+boardstate[i+3]+boardstate[i+6]).chr == f || boardstate[(3*i)..(3*i)+2] == f
return f == "OOO" ? 1 : -1
end
end
if (boardstate[0]+boardstate[4]+boardstate[8]).chr == f || (boardstate[2]+boardstate[4]+boardstate[6]).chr == f
return f == "OOO" ? 1 : -1
end
end
return 0
end
def computer_play
#Sets depth,and alpha/beta for pruning, so far so good
depth = 3
alpha = -100
beta = 100
##boardstate starts as "---------"
##active_player: 1=player, -1=computer
play(minimax(#boardstate, depth, alpha, beta, #active_player))
end
def play(array)
#Check actual boardside with parameter boardside to see what move has been
#selected and plays that move
for i in 0...array[1].length
if #boardstate[i] != array[1][i]
#color = array[1][i].chr == "X" ? #ai : #player
##cursor.y = (i / 3) * #side
##cursor.x = (i % 3) * #side
##board.bitmap.fill_rect(#cursor.x,#cursor.y,#side,#side,color)
#boardstate = array[1].dup
end
end
end
def minimax(boardstate, depth, alpha, beta, active_player)
#If bottom node reached, returns [boardstate_score, boardstate]
#wincheck returns 1 if player wins, -1 if computer wins, and 0 otherwise
if depth == 0 or wincheck(boardstate) != 0 or (/-/ =~ boardstate) == nil
return [wincheck(boardstate),boardstate]
end
if active_player == 1 #if player's turn
#Gets an array of all the next possible boardstates and return the one with
#the best eval.
child = generate_child(boardstate, active_player)
child.each do |f| #f = [Int/nil, String]
if f[0] == nil
#This should turn all the nil wincheck values to the best value of children nodes
f[0] = minimax(f[1], depth-1, alpha, beta, -active_player).last[0]
end
alpha = [f[0], alpha].max
if beta <= alpha
break
end
end
return child.sort_by{|c| c[0]}
end
if active_player == -1 #if computer's turn
#Same as above but with worst eval.
child = generate_child(boardstate, active_player)
child.each do |f|
if f[0] == nil
f[0] = minimax(f[1], depth-1, alpha, beta, -active_player).first[0]
end
beta = [f[0], beta].min
if beta <= alpha
break
end
end
#Following line raises "comparison of array with array failed" error :
return child.sort_by{|c| c[0]}
end
end
def generate_child(boardstate, active_player)
#returns boardstate string with one X or O more than current boardstate
#and sets nil as a default wincheck value
c = active_player == 1 ? "O" : "X"
a = []
for i in 0...boardstate.length
if boardstate[i].chr == "-"
s = boardstate.dup
s[i]= c
a << [nil, s]
end
end
return a
end
end
Error: comparison of array with array failed

Run-time error in my realization of deque in Python3

Could you please help me to find an error in the realization of deque? There is a restriction on the number of possible elements in the deque (namely 100).
I suppose that my code has mistakes because it runs out with a run-time error when I am trying to pass it on the contest. The problem is that when I seek to
find this mistake manually I can't get such an error.
Here is my code:
def push_front(dequeue, elem):
global dequeuestart
dequeue[dequeuestart] = elem
dequeuestart -= 1
print('ok')
def push_back(dequeue, elem):
global dequeueend
dequeue[dequeueend] = elem
dequeueend += 1
print('ok')
def pop_front(dequeue):
global dequeuestart
dequeuestart += 1
return dequeue[dequeuestart]
def pop_back(dequeue):
global dequeueend
dequeueend -= 1
return dequeue[dequeueend]
def front(dequeue):
return dequeue[dequeuestart + 1]
def back(dequeue):
return dequeue[dequeueend - 1]
def size(dequeue):
return dequeueend - dequeuestart - 1
def clear(dequeue):
global dequeuestart
global dequeueend
dequeuestart = 99
dequeueend = 100
print('ok')
def exit(dequeue):
print('bye')
dequeue = ['None' for i in range(200)]
dequeuestart = 99
dequeueend = 100
line = input()
while line:
elems = line.split()
if elems[0] == 'push_front':
push_front(dequeue, elems[1])
elif elems[0] == 'push_back':
push_back(dequeue, int(elems[1]))
elif elems[0] == 'pop_front':
print(pop_front(dequeue))
elif elems[0] == 'pop_back':
print(pop_back(dequeue))
elif elems[0] == 'front':
print(front(dequeue))
elif elems[0] == 'back':
print(back(dequeue))
elif elems[0] == 'size':
print(size(dequeue))
elif elems[0] == 'clear':
clear(dequeue)
else:
exit(dequeue)
break
line = input()
Thanks in advance!

Pygame animating image by transforming it

I am trying to create an animation of a rectangle in pygame but I struggle to animate it over the given frame-rate.
class Muscle(pygame.sprite.Sprite):
def __init__(self, screen, posX=200, posY=200, contraction=0.5, extension=1.5, length=10, thickness=5, min_len=0.2,max_len=1.5, power=20):
super(Muscle, self).__init__()
self.screen = screen
self.contraction = contraction
self.relaxation = relaxation
self.length = length
self.thickness = thickness
if power < 1:
self.power = 1
power = 1
else:
self.power = power
self.image = pygame.Surface((length, thickness))
color_index = 5 * power
self.image.fill((255, color_index, color_index))
self.rect = self.image.get_rect()
self.rect.x = posX
self.rect.y = posY
def render(self):
self.screen.blit(self.image, (self.rect.x, self.rect.y))
def contract(self):
expected_width = self.length * self.contraction
counter = 0
while self.image.get_width() > expected_width:
self.image = pygame.transform.scale(self.image, (self.rect.width, self.image.get_height()))
self.rect.x += 1;
self.rect.width -= 2
self.render()
counter += 1
def extend(self):
expected_width = self.length * self.relaxation
counter = 0
while self.image.get_width() < expected_width:
self.image = pygame.transform.scale(self.image, (self.rect.width, self.image.get_height()))
self.rect.x -= 1;
self.rect.width += 2
self.render()
#print("Relaxation:" + str(counter))
counter += 1
If I call the contract and extend methods separately, they resize the image of the rectangle successfully, but I would like to perform it over time, without interrupting my main loop which draws the environment and the sprite.
The simplest solution would be to call extend or contract once per frame, but then the animation would be frame rate bound.
import pygame
class Muscle(pygame.sprite.Sprite):
def __init__(self, screen, posX=200, posY=200, contraction=0.5,
extension=1.5, length=40, thickness=20, min_len=0.2,max_len=1.5, power=20):
super(Muscle, self).__init__()
self.screen = screen
self.contracting = False # To check if the muscle is contracting or extending.
self.contraction = contraction
self.relaxation = 1
self.length = length
self.thickness = thickness
if power < 1:
self.power = 1
power = 1
else:
self.power = power
self.image = pygame.Surface((length, thickness))
color_index = 5 * power
self.image.fill((255, color_index, color_index))
self.rect = self.image.get_rect()
self.rect.x = posX
self.rect.y = posY
# This method gets called every frame.
def update(self):
if self.contracting:
self.contract()
else:
self.extend()
def render(self):
self.screen.blit(self.image, (self.rect.x, self.rect.y))
def contract(self):
expected_width = self.length * self.contraction
counter = 0
if self.image.get_width() > expected_width:
self.image = pygame.transform.scale(self.image, (self.rect.width, self.image.get_height()))
self.rect.x += 1
self.rect.width -= 2
self.render()
counter += 1
def extend(self):
expected_width = self.length * self.relaxation
counter = 0
if self.image.get_width() < expected_width:
self.image = pygame.transform.scale(self.image, (self.rect.width, self.image.get_height()))
self.rect.x -= 1
self.rect.width += 2
self.render()
counter += 1
def main():
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
muscle = Muscle(screen)
all_sprites = pygame.sprite.Group(muscle)
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Change the state of the muscle.
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
muscle.contracting = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_c:
muscle.contracting = False
all_sprites.update()
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pygame.display.flip()
clock.tick(30)
if __name__ == '__main__':
pygame.init()
main()
pygame.quit()
Alternatively, you can call extend or contract after some time interval. Check out these answers to see how you can implement a timer.

Resources